blob: 2dcbbce0babdd8989c9338c24a7c750b810bee2e [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung25a80ac2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
jiabin220eea12024-05-17 17:55:20 +000036#include <com_android_media_audioserver.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070037#ifdef DEBUG_CPU_USAGE
38#include <audio_utils/Statistics.h>
39#include <cpustats/ThreadCpuUsage.h>
40#endif
41#include <audio_utils/channels.h>
42#include <audio_utils/format.h>
43#include <audio_utils/minifloat.h>
44#include <audio_utils/mono_blend.h>
45#include <audio_utils/primitives.h>
46#include <audio_utils/safe_math.h>
47#include <audiomanager/AudioManager.h>
48#include <binder/IPCThreadState.h>
49#include <binder/IServiceManager.h>
50#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010051#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070052#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070054#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070055#include <media/AudioContainers.h>
56#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070057#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070058#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070059#ifdef ADD_BATTERY_DATA
60#include <media/IMediaPlayerService.h>
61#include <media/IMediaDeathNotifier.h>
62#endif
63#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080064#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070065#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070066#include <media/audiohal/EffectsFactoryHalInterface.h>
67#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070068#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069#include <media/nbaio/AudioStreamOutSink.h>
70#include <media/nbaio/MonoPipe.h>
71#include <media/nbaio/MonoPipeReader.h>
72#include <media/nbaio/Pipe.h>
73#include <media/nbaio/PipeReader.h>
74#include <media/nbaio/SourceAudioBufferProvider.h>
Atneya Nair5997a652024-06-14 17:24:45 -070075#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080076#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070077#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070078#include <mediautils/SchedulingPolicyService.h>
79#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070080#include <powermanager/PowerManager.h>
81#include <private/android_filesystem_config.h>
82#include <private/media/AudioTrackShared.h>
83#include <system/audio_effects/effect_aec.h>
84#include <system/audio_effects/effect_downmix.h>
85#include <system/audio_effects/effect_ns.h>
86#include <system/audio_effects/effect_spatializer.h>
87#include <utils/Log.h>
88#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080089
Andy Hung25a80ac2023-07-19 12:47:35 -070090#include <fcntl.h>
91#include <linux/futex.h>
92#include <math.h>
93#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080094#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070095#include <sstream>
96#include <string>
97#include <sys/stat.h>
98#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100// ----------------------------------------------------------------------------
101
102// Note: the following macro is used for extremely verbose logging message. In
103// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
104// 0; but one side effect of this is to turn all LOGV's as well. Some messages
105// are so verbose that we want to suppress them even when we have ALOG_ASSERT
106// turned on. Do not uncomment the #def below unless you really know what you
107// are doing and want to see all of the extremely verbose messages.
108//#define VERY_VERY_VERBOSE_LOGGING
109#ifdef VERY_VERY_VERBOSE_LOGGING
110#define ALOGVV ALOGV
111#else
112#define ALOGVV(a...) do { } while(0)
113#endif
114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700116#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700117
Andy Hung6770c6f2015-04-07 13:43:36 -0700118template <typename T>
119static inline T min(const T& a, const T& b)
120{
121 return a < b ? a : b;
122}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700123
Atneya Nair5997a652024-06-14 17:24:45 -0700124using com::android::media::permission::ValidatedAttributionSourceState;
125
Eric Laurent81784c32012-11-19 14:55:58 -0800126namespace android {
127
Andy Hungee58e4a2023-07-07 13:47:37 -0700128using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000130using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131
Andy Hung25a80ac2023-07-19 12:47:35 -0700132// Keep in sync with java definition in media/java/android/media/AudioRecord.java
133static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// retry counts for buffer fill timeout
136// 50 * ~20msecs = 1 second
137static const int8_t kMaxTrackRetries = 50;
138static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700139
Eric Laurent81784c32012-11-19 14:55:58 -0800140// allow less retry attempts on direct output thread.
141// direct outputs can be a scarce resource in audio hardware and should
142// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700143// Notes:
144// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
145// in case the data write is bursty for the AudioTrack. The application
146// should endeavor to write at least once every kMaxTrackRetriesDirectMs
147// to prevent an underrun situation. If the data is bursty, then
148// the application can also throttle the data sent to be even.
149// 2) For compressed audio data, any data present in the AudioTrack buffer
150// will be sent and reset the retry count. This delivers data as
151// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
152// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
153// of data to be available, then any remaining data is delivered.
154// This is required to ensure the last bit of data is delivered before underrun.
155//
156// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
157// or the size of the HAL period for proportional / linear PCM tracks.
158static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800159
160// don't warn about blocked writes or record buffer overflows more often than this
161static const nsecs_t kWarningThrottleNs = seconds(5);
162
163// RecordThread loop sleep time upon application overrun or audio HAL read error
164static const int kRecordThreadSleepUs = 5000;
165
Eric Laurent10351942014-05-08 18:49:52 -0700166// maximum time to wait in sendConfigEvent_l() for a status to be received
167static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800168
169// minimum sleep time for the mixer thread loop when tracks are active but in underrun
170static const uint32_t kMinThreadSleepTimeUs = 5000;
171// maximum divider applied to the active sleep time in the mixer thread loop
172static const uint32_t kMaxThreadSleepTimeShift = 2;
173
Andy Hung09a50072014-02-27 14:30:47 -0800174// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700175// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800176static const uint32_t kMinNormalSinkBufferSizeMs = 20;
177// maximum normal sink buffer size
178static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800179
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700180// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
181// FIXME This should be based on experimentally observed scheduling jitter
182static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
183
Eric Laurent972a1732013-09-04 09:42:59 -0700184// Offloaded output thread standby delay: allows track transition without going to standby
185static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
186
Eric Laurent51716182016-02-29 18:00:56 -0800187// Direct output thread minimum sleep time in idle or active(underrun) state
188static const nsecs_t kDirectMinSleepTimeUs = 10000;
189
Brian Lindahl65e90012022-07-27 18:01:07 +0200190// Minimum amount of time between checking to see if the timestamp is advancing
191// for underrun detection. If we check too frequently, we may not detect a
192// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800193static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200194
Glenn Kasten1b291842016-07-18 14:55:21 -0700195// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
196// balance between power consumption and latency, and allows threads to be scheduled reliably
197// by the CFS scheduler.
198// FIXME Express other hardcoded references to 20ms with references to this constant and move
199// it appropriately.
200#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// Whether to use fast mixer
203static const enum {
204 FastMixer_Never, // never initialize or use: for debugging only
205 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
206 // normal mixer multiplier is 1
207 FastMixer_Static, // initialize if needed, then use all the time if initialized,
208 // multiplier is calculated based on min & max normal mixer buffer size
209 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
210 // multiplier is calculated based on min & max normal mixer buffer size
211 // FIXME for FastMixer_Dynamic:
212 // Supporting this option will require fixing HALs that can't handle large writes.
213 // For example, one HAL implementation returns an error from a large write,
214 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
215 // We could either fix the HAL implementations, or provide a wrapper that breaks
216 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
217} kUseFastMixer = FastMixer_Static;
218
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700219// Whether to use fast capture
220static const enum {
221 FastCapture_Never, // never initialize or use: for debugging only
222 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
223 FastCapture_Static, // initialize if needed, then use all the time if initialized
224} kUseFastCapture = FastCapture_Static;
225
Eric Laurent81784c32012-11-19 14:55:58 -0800226// Priorities for requestPriority
227static const int kPriorityAudioApp = 2;
228static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700229static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000230// Request real-time priority for PlaybackThread in ARC
231static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800232
Glenn Kastenea38ee72016-04-18 11:08:01 -0700233// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
234// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
235// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700236
237// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800238static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800239
Glenn Kasten03490092014-05-27 12:30:54 -0700240// The minimum and maximum allowed values
241static const int kFastTrackMultiplierMin = 1;
242static const int kFastTrackMultiplierMax = 2;
243
244// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
245static int sFastTrackMultiplier = kFastTrackMultiplier;
246
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700247// See Thread::readOnlyHeap().
248// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
249// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
250// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700251static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700252
Andy Hung25a80ac2023-07-19 12:47:35 -0700253static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700254
255static nsecs_t getStandbyTimeInNanos() {
256 static nsecs_t standbyTimeInNanos = []() {
257 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
258 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
259 ALOGI("%s: Using %d ms as standby time", __func__, ms);
260 return milliseconds(ms);
261 }();
262 return standbyTimeInNanos;
263}
264
Andy Hung81994d62023-07-20 21:44:14 -0700265// Set kEnableExtendedChannels to true to enable greater than stereo output
266// for the MixerThread and device sink. Number of channels allowed is
267// FCC_2 <= channels <= FCC_LIMIT.
268constexpr bool kEnableExtendedChannels = true;
269
270// Returns true if channel mask is permitted for the PCM sink in the MixerThread
271/* static */
272bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
273 switch (audio_channel_mask_get_representation(channelMask)) {
274 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
275 // Haptic channel mask is only applicable for channel position mask.
276 const uint32_t channelCount = audio_channel_count_from_out_mask(
277 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
278 const uint32_t maxChannelCount = kEnableExtendedChannels
279 ? FCC_LIMIT : FCC_2;
280 if (channelCount < FCC_2 // mono is not supported at this time
281 || channelCount > maxChannelCount) {
282 return false;
283 }
284 // check that channelMask is the "canonical" one we expect for the channelCount.
285 return audio_channel_position_mask_is_out_canonical(channelMask);
286 }
287 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
288 if (kEnableExtendedChannels) {
289 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
290 if (channelCount >= FCC_2 // mono is not supported at this time
291 && channelCount <= FCC_LIMIT) {
292 return true;
293 }
294 }
295 return false;
296 default:
297 return false;
298 }
299}
300
301// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
302constexpr bool kEnableExtendedPrecision = true;
303
304// Returns true if format is permitted for the PCM sink in the MixerThread
305/* static */
306bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
307 switch (format) {
308 case AUDIO_FORMAT_PCM_16_BIT:
309 return true;
310 case AUDIO_FORMAT_PCM_FLOAT:
311 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
312 case AUDIO_FORMAT_PCM_32_BIT:
313 case AUDIO_FORMAT_PCM_8_24_BIT:
314 return kEnableExtendedPrecision;
315 default:
316 return false;
317 }
318}
319
Eric Laurent81784c32012-11-19 14:55:58 -0800320// ----------------------------------------------------------------------------
321
Andy Hung25a80ac2023-07-19 12:47:35 -0700322// formatToString() needs to be exact for MediaMetrics purposes.
323// Do not use media/TypeConverter.h toString().
324/* static */
325std::string IAfThreadBase::formatToString(audio_format_t format) {
326 std::string result;
327 FormatConverter::toString(format, result);
328 return result;
329}
330
Andy Hungb68f5eb2019-12-03 16:49:17 -0800331// TODO: move all toString helpers to audio.h
332// under #ifdef __cplusplus #endif
333static std::string patchSinksToString(const struct audio_patch *patch)
334{
335 std::stringstream ss;
336 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700337 if (i > 0) {
338 ss << "|";
339 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800340 ss << "(" << toString(patch->sinks[i].ext.device.type)
341 << ", " << patch->sinks[i].ext.device.address << ")";
342 }
343 return ss.str();
344}
345
346static std::string patchSourcesToString(const struct audio_patch *patch)
347{
348 std::stringstream ss;
349 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700350 if (i > 0) {
351 ss << "|";
352 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800353 ss << "(" << toString(patch->sources[i].ext.device.type)
354 << ", " << patch->sources[i].ext.device.address << ")";
355 }
356 return ss.str();
357}
358
Andy Hung4bd53e72022-11-17 17:21:45 -0800359static std::string toString(audio_latency_mode_t mode) {
360 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000361 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
362 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800363}
364
365// Could be made a template, but other toString overloads for std::vector are confused.
366static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
367 std::string s("{ ");
368 for (const auto& e : elements) {
369 s.append(toString(e));
370 s.append(" ");
371 }
372 s.append("}");
373 return s;
374}
375
Glenn Kasten03490092014-05-27 12:30:54 -0700376static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
377
378static void sFastTrackMultiplierInit()
379{
380 char value[PROPERTY_VALUE_MAX];
381 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
382 char *endptr;
383 unsigned long ul = strtoul(value, &endptr, 0);
384 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
385 sFastTrackMultiplier = (int) ul;
386 }
387 }
388}
389
390// ----------------------------------------------------------------------------
391
Eric Laurent81784c32012-11-19 14:55:58 -0800392#ifdef ADD_BATTERY_DATA
393// To collect the amplifier usage
394static void addBatteryData(uint32_t params) {
395 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
396 if (service == NULL) {
397 // it already logged
398 return;
399 }
400
401 service->addBatteryData(params);
402}
403#endif
404
Andy Hung3f0c9022016-01-15 17:49:46 -0800405// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
406struct {
407 // call when you acquire a partial wakelock
408 void acquire(const sp<IBinder> &wakeLockToken) {
409 pthread_mutex_lock(&mLock);
410 if (wakeLockToken.get() == nullptr) {
411 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
412 } else {
413 if (mCount == 0) {
414 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
415 }
416 ++mCount;
417 }
418 pthread_mutex_unlock(&mLock);
419 }
420
421 // call when you release a partial wakelock.
422 void release(const sp<IBinder> &wakeLockToken) {
423 if (wakeLockToken.get() == nullptr) {
424 return;
425 }
426 pthread_mutex_lock(&mLock);
427 if (--mCount < 0) {
428 ALOGE("negative wakelock count");
429 mCount = 0;
430 }
431 pthread_mutex_unlock(&mLock);
432 }
433
434 // retrieves the boottime timebase offset from monotonic.
435 int64_t getBoottimeOffset() {
436 pthread_mutex_lock(&mLock);
437 int64_t boottimeOffset = mBoottimeOffset;
438 pthread_mutex_unlock(&mLock);
439 return boottimeOffset;
440 }
441
442 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
443 // and the selected timebase.
444 // Currently only TIMEBASE_BOOTTIME is allowed.
445 //
446 // This only needs to be called upon acquiring the first partial wakelock
447 // after all other partial wakelocks are released.
448 //
449 // We do an empirical measurement of the offset rather than parsing
450 // /proc/timer_list since the latter is not a formal kernel ABI.
451 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
452 int clockbase;
453 switch (timebase) {
454 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
455 clockbase = SYSTEM_TIME_BOOTTIME;
456 break;
457 default:
458 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
459 break;
460 }
461 // try three times to get the clock offset, choose the one
462 // with the minimum gap in measurements.
463 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700464 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800465 for (int i = 0; i < tries; ++i) {
466 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
467 const nsecs_t tbase = systemTime(clockbase);
468 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
469 const nsecs_t gap = tmono2 - tmono;
470 if (i == 0 || gap < bestGap) {
471 bestGap = gap;
472 measured = tbase - ((tmono + tmono2) >> 1);
473 }
474 }
475
476 // to avoid micro-adjusting, we don't change the timebase
477 // unless it is significantly different.
478 //
479 // Assumption: It probably takes more than toleranceNs to
480 // suspend and resume the device.
481 static int64_t toleranceNs = 10000; // 10 us
482 if (llabs(*offset - measured) > toleranceNs) {
483 ALOGV("Adjusting timebase offset old: %lld new: %lld",
484 (long long)*offset, (long long)measured);
485 *offset = measured;
486 }
487 }
488
489 pthread_mutex_t mLock;
490 int32_t mCount;
491 int64_t mBoottimeOffset;
492} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800493
494// ----------------------------------------------------------------------------
495// CPU Stats
496// ----------------------------------------------------------------------------
497
498class CpuStats {
499public:
500 CpuStats();
501 void sample(const String8 &title);
502#ifdef DEBUG_CPU_USAGE
503private:
504 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700505 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800506
Andy Hung16698b82018-08-01 10:48:38 -0700507 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800508
509 int mCpuNum; // thread's current CPU number
510 int mCpukHz; // frequency of thread's current CPU in kHz
511#endif
512};
513
514CpuStats::CpuStats()
515#ifdef DEBUG_CPU_USAGE
516 : mCpuNum(-1), mCpukHz(-1)
517#endif
518{
519}
520
Glenn Kasten0f11b512014-01-31 16:18:54 -0800521void CpuStats::sample(const String8 &title
522#ifndef DEBUG_CPU_USAGE
523 __unused
524#endif
525 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800526#ifdef DEBUG_CPU_USAGE
527 // get current thread's delta CPU time in wall clock ns
528 double wcNs;
529 bool valid = mCpuUsage.sampleAndEnable(wcNs);
530
531 // record sample for wall clock statistics
532 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700533 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800534 }
535
536 // get the current CPU number
537 int cpuNum = sched_getcpu();
538
539 // get the current CPU frequency in kHz
540 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
541
542 // check if either CPU number or frequency changed
543 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
544 mCpuNum = cpuNum;
545 mCpukHz = cpukHz;
546 // ignore sample for purposes of cycles
547 valid = false;
548 }
549
550 // if no change in CPU number or frequency, then record sample for cycle statistics
551 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const double cycles = wcNs * cpukHz * 0.000001;
553 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800554 }
555
Eric Tan5b13ff82018-07-27 11:20:17 -0700556 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800557 // mCpuUsage.elapsed() is expensive, so don't call it every loop
558 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700559 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800560 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700561 const double perLoop = elapsed / (double) n;
562 const double perLoop100 = perLoop * 0.01;
563 const double perLoop1k = perLoop * 0.001;
564 const double mean = mWcStats.getMean();
565 const double stddev = mWcStats.getStdDev();
566 const double minimum = mWcStats.getMin();
567 const double maximum = mWcStats.getMax();
568 const double meanCycles = mHzStats.getMean();
569 const double stddevCycles = mHzStats.getStdDev();
570 const double minCycles = mHzStats.getMin();
571 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800572 mCpuUsage.resetElapsed();
573 mWcStats.reset();
574 mHzStats.reset();
575 ALOGD("CPU usage for %s over past %.1f secs\n"
576 " (%u mixer loops at %.1f mean ms per loop):\n"
577 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
578 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
579 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000580 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800581 elapsed * .000000001, n, perLoop * .000001,
582 mean * .001,
583 stddev * .001,
584 minimum * .001,
585 maximum * .001,
586 mean / perLoop100,
587 stddev / perLoop100,
588 minimum / perLoop100,
589 maximum / perLoop100,
590 meanCycles / perLoop1k,
591 stddevCycles / perLoop1k,
592 minCycles / perLoop1k,
593 maxCycles / perLoop1k);
594
595 }
596 }
597#endif
598};
599
600// ----------------------------------------------------------------------------
601// ThreadBase
602// ----------------------------------------------------------------------------
603
Glenn Kasten97b7b752014-09-28 13:04:24 -0700604// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700605const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700606{
607 switch (type) {
608 case MIXER:
609 return "MIXER";
610 case DIRECT:
611 return "DIRECT";
612 case DUPLICATING:
613 return "DUPLICATING";
614 case RECORD:
615 return "RECORD";
616 case OFFLOAD:
617 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700618 case MMAP_PLAYBACK:
619 return "MMAP_PLAYBACK";
620 case MMAP_CAPTURE:
621 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200622 case SPATIALIZER:
623 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000624 case BIT_PERFECT:
625 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700626 default:
627 return "unknown";
628 }
629}
630
Andy Hung583043b2023-07-17 17:05:00 -0700631ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700632 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800633 : Thread(false /*canCallJava*/),
634 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700635 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700636 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
637 isOut),
638 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700639 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800640 // are set by PlaybackThread::readOutputParameters_l() or
641 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700642 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700643 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700644 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800645 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700646 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800647 mSystemReady(systemReady),
648 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800649{
Andy Hungcf10d742020-04-28 15:38:24 -0700650 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700651 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Andy Hungee58e4a2023-07-07 13:47:37 -0700654ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700656 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700657 mConfigEvents.clear();
658
Eric Laurent81784c32012-11-19 14:55:58 -0800659 // do not lock the mutex in destructor
660 releaseWakeLock_l();
661 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800662 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800663 binder->unlinkToDeath(mDeathRecipient);
664 }
Andy Hungd0979812019-02-21 15:51:44 -0800665
666 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800667}
668
Andy Hungee58e4a2023-07-07 13:47:37 -0700669status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700670{
671 status_t status = initCheck();
672 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800673 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700674 } else {
675 ALOGE("No working audio driver found.");
676 }
677 return status;
678}
679
Andy Hungee58e4a2023-07-07 13:47:37 -0700680void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800681{
682 ALOGV("ThreadBase::exit");
683 // do any cleanup required for exit to succeed
684 preExit();
685 {
686 // This lock prevents the following race in thread (uniprocessor for illustration):
687 // if (!exitPending()) {
688 // // context switch from here to exit()
689 // // exit() calls requestExit(), what exitPending() observes
690 // // exit() calls signal(), which is dropped since no waiters
691 // // context switch back from exit() to here
692 // mWaitWorkCV.wait(...);
693 // // now thread is hung
694 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700695 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800696 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700697 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800698 }
699 // When Thread::requestExitAndWait is made virtual and this method is renamed to
700 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700701
702 // For TimeCheck: track waiting on the thread join of getTid().
703 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
704
Eric Laurent81784c32012-11-19 14:55:58 -0800705 requestExitAndWait();
706}
707
Andy Hungee58e4a2023-07-07 13:47:37 -0700708status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800709{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000710 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700711 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800712
Eric Laurent10351942014-05-08 18:49:52 -0700713 return sendSetParameterConfigEvent_l(keyValuePairs);
714}
715
716// sendConfigEvent_l() must be called with ThreadBase::mLock held
717// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700718status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700719NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700720{
721 status_t status = NO_ERROR;
722
Eric Laurent72e3f392015-05-20 14:43:50 -0700723 if (event->mRequiresSystemReady && !mSystemReady) {
724 event->mWaitStatus = false;
725 mPendingConfigEvents.add(event);
726 return status;
727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700729 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700730 mWaitWorkCV.notify_one();
731 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700732 {
Andy Hungc5007f82023-08-29 14:26:09 -0700733 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700734 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800735 if (event->mCondition.wait_for(
736 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
737 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700738 event->mStatus = TIMED_OUT;
739 event->mWaitStatus = false;
740 }
741 }
742 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800743 }
Andy Hungc5007f82023-08-29 14:26:09 -0700744 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800745 return status;
746}
747
Andy Hungee58e4a2023-07-07 13:47:37 -0700748void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700749 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800750{
Andy Hung972bec12023-08-31 16:13:39 -0700751 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700752 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800753}
754
Andy Hungc5007f82023-08-29 14:26:09 -0700755// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700756void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700757 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800758{
Andy Hungd0979812019-02-21 15:51:44 -0800759 // The audio statistics history is exponentially weighted to forget events
760 // about five or more seconds in the past. In order to have
761 // crisper statistics for mediametrics, we reset the statistics on
762 // an IoConfigEvent, to reflect different properties for a new device.
763 mIoJitterMs.reset();
764 mLatencyMs.reset();
765 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000766 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100767 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800768
Eric Laurent09f1ed22019-04-24 17:45:17 -0700769 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700770 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800771}
772
Andy Hungee58e4a2023-07-07 13:47:37 -0700773void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700774{
Andy Hung972bec12023-08-31 16:13:39 -0700775 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800776 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700777}
778
Andy Hungc5007f82023-08-29 14:26:09 -0700779// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700780void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800781 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800782{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800783 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700784 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800785}
786
Andy Hungc5007f82023-08-29 14:26:09 -0700787// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700788status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800789{
Andy Hung2ddee192015-12-18 17:34:44 -0800790 sp<ConfigEvent> configEvent;
791 AudioParameter param(keyValuePair);
792 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700793 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800794 setMasterMono_l(value != 0);
795 if (param.size() == 1) {
796 return NO_ERROR; // should be a solo parameter - we don't pass down
797 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700798 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800799 configEvent = new SetParameterConfigEvent(param.toString());
800 } else {
801 configEvent = new SetParameterConfigEvent(keyValuePair);
802 }
Eric Laurent10351942014-05-08 18:49:52 -0700803 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700804}
805
Andy Hungee58e4a2023-07-07 13:47:37 -0700806status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700807 const struct audio_patch *patch,
808 audio_patch_handle_t *handle)
809{
Andy Hung972bec12023-08-31 16:13:39 -0700810 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700811 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
812 status_t status = sendConfigEvent_l(configEvent);
813 if (status == NO_ERROR) {
814 CreateAudioPatchConfigEventData *data =
815 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
816 *handle = data->mHandle;
817 }
818 return status;
819}
820
Andy Hungee58e4a2023-07-07 13:47:37 -0700821status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700822 const audio_patch_handle_t handle)
823{
Andy Hung972bec12023-08-31 16:13:39 -0700824 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700825 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
826 return sendConfigEvent_l(configEvent);
827}
828
Andy Hungee58e4a2023-07-07 13:47:37 -0700829status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700830 const DeviceDescriptorBaseVector& outDevices)
831{
832 if (type() != RECORD) {
833 // The update out device operation is only for record thread.
834 return INVALID_OPERATION;
835 }
Andy Hung972bec12023-08-31 16:13:39 -0700836 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700837 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
838 return sendConfigEvent_l(configEvent);
839}
840
Andy Hungee58e4a2023-07-07 13:47:37 -0700841void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200842{
843 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
844 sp<ConfigEvent> configEvent =
845 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
846 sendConfigEvent_l(configEvent);
847}
Eric Laurent1c333e22014-05-20 10:48:17 -0700848
Andy Hungee58e4a2023-07-07 13:47:37 -0700849void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200850{
Andy Hung972bec12023-08-31 16:13:39 -0700851 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200852 sendCheckOutputStageEffectsEvent_l();
853}
854
Andy Hungee58e4a2023-07-07 13:47:37 -0700855void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200856{
857 sp<ConfigEvent> configEvent =
858 (ConfigEvent *)new CheckOutputStageEffectsEvent();
859 sendConfigEvent_l(configEvent);
860}
861
Andy Hungee58e4a2023-07-07 13:47:37 -0700862void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200863{
864 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
865 sendConfigEvent_l(configEvent);
866}
867
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700868// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700869void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700870{
Eric Laurent10351942014-05-08 18:49:52 -0700871 bool configChanged = false;
872
Eric Laurent81784c32012-11-19 14:55:58 -0800873 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700874 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700875 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800876 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700877 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700878 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700879 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
880 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800881 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700882 true /*asynchronous*/);
883 if (err != 0) {
884 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700885 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700886 }
887 } break;
888 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700889 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700890 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700891 } break;
892 case CFG_EVENT_SET_PARAMETER: {
893 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
894 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
895 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700896 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000897 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700898 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700899 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700900 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700901 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 CreateAudioPatchConfigEventData *data =
903 (CreateAudioPatchConfigEventData *)event->mData.get();
904 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700905 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200906 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700907 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
908 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
909 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700910 } break;
911 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700912 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700913 ReleaseAudioPatchConfigEventData *data =
914 (ReleaseAudioPatchConfigEventData *)event->mData.get();
915 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700916 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200917 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700918 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
919 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
920 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
921 } break;
922 case CFG_EVENT_UPDATE_OUT_DEVICE: {
923 UpdateOutDevicesConfigEventData *data =
924 (UpdateOutDevicesConfigEventData *)event->mData.get();
925 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700926 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200927 case CFG_EVENT_RESIZE_BUFFER: {
928 ResizeBufferConfigEventData *data =
929 (ResizeBufferConfigEventData *)event->mData.get();
930 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
931 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200932
933 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
934 setCheckOutputStageEffects();
935 } break;
936
Eric Laurent68a40a82022-05-03 18:15:04 +0200937 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
938 onHalLatencyModesChanged_l();
939 } break;
940
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700941 default:
Eric Laurent10351942014-05-08 18:49:52 -0700942 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700943 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800944 }
Eric Laurent10351942014-05-08 18:49:52 -0700945 {
Andy Hung972bec12023-08-31 16:13:39 -0700946 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700947 if (event->mWaitStatus) {
948 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700949 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700950 }
951 }
952 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
953 }
954
955 if (configChanged) {
956 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
Eric Laurent81784c32012-11-19 14:55:58 -0800958}
959
Marco Nelissenb2208842014-02-07 14:00:50 -0800960String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
961 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700962 const audio_channel_representation_t representation =
963 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700964
965 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800966 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700967 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
968 if (output) {
969 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
971 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700972 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700973 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
974 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
975 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
976 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
977 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
978 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
981 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
982 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
983 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
984 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700985 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
986 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
987 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
988 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
989 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
990 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
991 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700992 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700993 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
994 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700995 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
996 } else {
997 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
998 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
999 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1000 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1001 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1002 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1003 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1004 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1005 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1006 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1007 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1008 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001009 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1010 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1011 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001012 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001013 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1014 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001015 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1016 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1017 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1018 }
1019 const int len = s.length();
1020 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001021 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001022 s.unlockBuffer(len - 2); // remove trailing ", "
1023 }
1024 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001025 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001026 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1027 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1028 return s;
1029 default:
1030 s.appendFormat("unknown mask, representation:%d bits:%#x",
1031 representation, audio_channel_mask_get_bits(mask));
1032 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001033 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001034}
1035
Andy Hungee58e4a2023-07-07 13:47:37 -07001036void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001037NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001038{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001039 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1040 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1041
Andy Hungc5007f82023-08-29 14:26:09 -07001042 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001043 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001044 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001045 }
1046
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001047 dumpBase_l(fd, args);
1048 dumpInternals_l(fd, args);
1049 dumpTracks_l(fd, args);
1050 dumpEffectChains_l(fd, args);
1051
1052 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001053 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001054 }
1055
1056 dprintf(fd, " Local log:\n");
1057 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001058
1059 // --all does the statistics
1060 bool dumpAll = false;
1061 for (const auto &arg : args) {
1062 if (arg == String16("--all")) {
1063 dumpAll = true;
1064 }
1065 }
1066 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001067 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001068 if (!sched.empty()) {
1069 (void)write(fd, sched.c_str(), sched.size());
1070 }
1071 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001072}
1073
Andy Hungee58e4a2023-07-07 13:47:37 -07001074void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001075{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001076 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001077 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001078 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001079 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001080 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1081 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001082 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001083 dprintf(fd, " Channel count: %u\n", mChannelCount);
1084 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001085 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001086 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1087 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001088 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001090 size_t numConfig = mConfigEvents.size();
1091 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001092 const size_t SIZE = 256;
1093 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001094 for (size_t i = 0; i < numConfig; i++) {
1095 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001096 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001097 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001098 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001099 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001100 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001101 }
Andy Hung293558a2017-03-21 12:19:20 -07001102 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001103 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001104 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001105 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001106 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001107 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001108
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001109 // Dump timestamp statistics for the Thread types that support it.
1110 if (mType == RECORD
1111 || mType == MIXER
1112 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001113 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001114 || mType == OFFLOAD
1115 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001116 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001117 dprintf(fd, " Timestamp corrected: %s\n",
1118 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001119 }
1120
Andy Hung446f4df2019-02-21 12:26:41 -08001121 if (mLastIoBeginNs > 0) { // MMAP may not set this
1122 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1123 isOutput() ? "write" : "read",
1124 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1125 }
1126
1127 if (mProcessTimeMs.getN() > 0) {
1128 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1129 }
1130
1131 if (mIoJitterMs.getN() > 0) {
1132 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1133 isOutput() ? "write" : "read",
1134 mIoJitterMs.toString().c_str());
1135 }
1136
Andy Hunge6c37112019-02-26 17:38:10 -08001137 if (mLatencyMs.getN() > 0) {
1138 dprintf(fd, " Threadloop %s latency stats: %s\n",
1139 isOutput() ? "write" : "read",
1140 mLatencyMs.toString().c_str());
1141 }
Robert Wu06db0a32021-08-10 19:05:34 +00001142
1143 if (mMonopipePipeDepthStats.getN() > 0) {
1144 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1145 isOutput() ? "write" : "read",
1146 mMonopipePipeDepthStats.toString().c_str());
1147 }
Eric Laurent81784c32012-11-19 14:55:58 -08001148}
1149
Andy Hungee58e4a2023-07-07 13:47:37 -07001150void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001151{
1152 const size_t SIZE = 256;
1153 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001154
Marco Nelissenb2208842014-02-07 14:00:50 -08001155 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001156 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001157 write(fd, buffer, strlen(buffer));
1158
Marco Nelissenb2208842014-02-07 14:00:50 -08001159 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001160 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001161 if (chain != 0) {
1162 chain->dump(fd, args);
1163 }
1164 }
1165}
1166
Andy Hungee58e4a2023-07-07 13:47:37 -07001167void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001168{
Andy Hung972bec12023-08-31 16:13:39 -07001169 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001170 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001171}
1172
Andy Hungee58e4a2023-07-07 13:47:37 -07001173String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001174{
1175 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001176 case MIXER:
1177 return String16("AudioMix");
1178 case DIRECT:
1179 return String16("AudioDirectOut");
1180 case DUPLICATING:
1181 return String16("AudioDup");
1182 case RECORD:
1183 return String16("AudioIn");
1184 case OFFLOAD:
1185 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001186 case MMAP_PLAYBACK:
1187 return String16("MmapPlayback");
1188 case MMAP_CAPTURE:
1189 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001190 case SPATIALIZER:
1191 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001192 default:
1193 ALOG_ASSERT(false);
1194 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001195 }
1196}
1197
Andy Hungee58e4a2023-07-07 13:47:37 -07001198void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001200 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001201 if (mPowerManager != 0) {
1202 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001203 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001204 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1205 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001206 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001207 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001208 {} /* workSource */,
1209 {} /* historyTag */);
1210 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001211 mWakeLockToken = binder;
1212 }
Chris Ye6597d732020-02-28 22:38:25 -08001213 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001214 }
Wei Jia3f273d12015-11-24 09:06:49 -08001215
Andy Hung3f0c9022016-01-15 17:49:46 -08001216 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001217 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1218 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001219}
1220
Andy Hungee58e4a2023-07-07 13:47:37 -07001221void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001222{
Andy Hung972bec12023-08-31 16:13:39 -07001223 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001224 releaseWakeLock_l();
1225}
1226
Andy Hungee58e4a2023-07-07 13:47:37 -07001227void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001228{
Andy Hung3f0c9022016-01-15 17:49:46 -08001229 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001230 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001231 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001232 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001233 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001234 }
1235 mWakeLockToken.clear();
1236 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237}
1238
Andy Hungee58e4a2023-07-07 13:47:37 -07001239void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001240 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001241 // use checkService() to avoid blocking if power service is not up yet
1242 sp<IBinder> binder =
1243 defaultServiceManager()->checkService(String16("power"));
1244 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001245 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001246 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001247 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001248 binder->linkToDeath(mDeathRecipient);
1249 }
1250 }
1251}
1252
Andy Hungee58e4a2023-07-07 13:47:37 -07001253void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001254 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001255
1256#if !LOG_NDEBUG
1257 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001258 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001259 s << uid << " ";
1260 }
1261 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1262#endif
1263
Andy Hung438e7572015-12-14 15:51:17 -08001264 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1265 if (mSystemReady) {
1266 ALOGE("no wake lock to update, but system ready!");
1267 } else {
1268 ALOGW("no wake lock to update, system not ready yet");
1269 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001270 return;
1271 }
1272 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001273 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001274 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1275 mWakeLockToken, uidsAsInt);
1276 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001277 }
1278}
1279
Andy Hungee58e4a2023-07-07 13:47:37 -07001280void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001281{
Andy Hung972bec12023-08-31 16:13:39 -07001282 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001283 releaseWakeLock_l();
1284 mPowerManager.clear();
1285}
1286
Andy Hungee58e4a2023-07-07 13:47:37 -07001287void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001288 const DeviceDescriptorBaseVector& outDevices __unused)
1289{
1290 ALOGE("%s should only be called in RecordThread", __func__);
1291}
1292
Andy Hungee58e4a2023-07-07 13:47:37 -07001293void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001294{
1295 ALOGE("%s should only be called in RecordThread", __func__);
1296}
1297
Andy Hungee58e4a2023-07-07 13:47:37 -07001298void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001299{
1300 sp<ThreadBase> thread = mThread.promote();
1301 if (thread != 0) {
1302 thread->clearPowerManager();
1303 }
1304 ALOGW("power manager service died !!!");
1305}
1306
Andy Hungee58e4a2023-07-07 13:47:37 -07001307void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001308 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001309{
Andy Hung116bc262023-06-20 18:56:17 -07001310 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001311 if (chain != 0) {
1312 if (type != NULL) {
1313 chain->setEffectSuspended_l(type, suspend);
1314 } else {
1315 chain->setEffectSuspendedAll_l(suspend);
1316 }
1317 }
1318
1319 updateSuspendedSessions_l(type, suspend, sessionId);
1320}
1321
Andy Hungee58e4a2023-07-07 13:47:37 -07001322void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001323{
1324 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1325 if (index < 0) {
1326 return;
1327 }
1328
1329 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1330 mSuspendedSessions.valueAt(index);
1331
1332 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001333 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001334 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001335 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001336 chain->setEffectSuspendedAll_l(true);
1337 } else {
1338 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1339 desc->mType.timeLow);
1340 chain->setEffectSuspended_l(&desc->mType, true);
1341 }
1342 }
1343 }
1344}
1345
Andy Hungee58e4a2023-07-07 13:47:37 -07001346void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001347 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001348 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001349{
1350 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1351
1352 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1353
1354 if (suspend) {
1355 if (index >= 0) {
1356 sessionEffects = mSuspendedSessions.valueAt(index);
1357 } else {
1358 mSuspendedSessions.add(sessionId, sessionEffects);
1359 }
1360 } else {
1361 if (index < 0) {
1362 return;
1363 }
1364 sessionEffects = mSuspendedSessions.valueAt(index);
1365 }
1366
1367
Andy Hung116bc262023-06-20 18:56:17 -07001368 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001369 if (type != NULL) {
1370 key = type->timeLow;
1371 }
1372 index = sessionEffects.indexOfKey(key);
1373
1374 sp<SuspendedSessionDesc> desc;
1375 if (suspend) {
1376 if (index >= 0) {
1377 desc = sessionEffects.valueAt(index);
1378 } else {
1379 desc = new SuspendedSessionDesc();
1380 if (type != NULL) {
1381 desc->mType = *type;
1382 }
1383 sessionEffects.add(key, desc);
1384 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1385 }
1386 desc->mRefCount++;
1387 } else {
1388 if (index < 0) {
1389 return;
1390 }
1391 desc = sessionEffects.valueAt(index);
1392 if (--desc->mRefCount == 0) {
1393 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1394 sessionEffects.removeItemsAt(index);
1395 if (sessionEffects.isEmpty()) {
1396 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1397 sessionId);
1398 mSuspendedSessions.removeItem(sessionId);
1399 }
1400 }
1401 }
1402 if (!sessionEffects.isEmpty()) {
1403 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1404 }
1405}
1406
Andy Hungee58e4a2023-07-07 13:47:37 -07001407void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001408 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001409 bool threadLocked)
1410NO_THREAD_SAFETY_ANALYSIS // manual locking
1411{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001412 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001413 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001414 }
Eric Laurent81784c32012-11-19 14:55:58 -08001415
Eric Laurent81784c32012-11-19 14:55:58 -08001416 if (mType != RECORD) {
1417 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1418 // another session. This gives the priority to well behaved effect control panels
1419 // and applications not using global effects.
1420 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1421 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001422 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001423 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1424 }
1425 }
1426
Eric Laurent6b446ce2019-12-13 10:56:31 -08001427 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001428 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001429 }
1430}
1431
Andy Hungc5007f82023-08-29 14:26:09 -07001432// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001433status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001434 const effect_descriptor_t *desc, audio_session_t sessionId)
1435{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001436 // No global output effect sessions on record threads
1437 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1438 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001439 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1440 desc->name, mThreadName);
1441 return BAD_VALUE;
1442 }
1443 // only pre processing effects on record thread
1444 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1445 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1446 desc->name, mThreadName);
1447 return BAD_VALUE;
1448 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001449
1450 // always allow effects without processing load or latency
1451 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1452 return NO_ERROR;
1453 }
1454
Eric Laurent4c415062016-06-17 16:14:16 -07001455 audio_input_flags_t flags = mInput->flags;
1456 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1457 if (flags & AUDIO_INPUT_FLAG_RAW) {
1458 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1459 desc->name, mThreadName);
1460 return BAD_VALUE;
1461 }
1462 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1463 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1464 desc->name, mThreadName);
1465 return BAD_VALUE;
1466 }
1467 }
jiabineb3bda02020-06-30 14:07:03 -07001468
Andy Hung116bc262023-06-20 18:56:17 -07001469 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001470 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1471 return BAD_VALUE;
1472 }
Eric Laurent4c415062016-06-17 16:14:16 -07001473 return NO_ERROR;
1474}
1475
Andy Hungc5007f82023-08-29 14:26:09 -07001476// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001477status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001478 const effect_descriptor_t *desc, audio_session_t sessionId)
1479{
1480 // no preprocessing on playback threads
1481 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001482 ALOGW("%s: pre processing effect %s created on playback"
1483 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001484 return BAD_VALUE;
1485 }
1486
Eric Laurent3e4de772017-07-16 16:55:08 -07001487 // always allow effects without processing load or latency
1488 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1489 return NO_ERROR;
1490 }
1491
Andy Hung116bc262023-06-20 18:56:17 -07001492 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001493 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1494 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001495 return BAD_VALUE;
1496 }
1497
Eric Laurent4eb45d02023-12-20 12:07:17 +01001498 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001499 && mType != SPATIALIZER) {
1500 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1501 __func__, mType);
1502 return BAD_VALUE;
1503 }
1504
Eric Laurent4c415062016-06-17 16:14:16 -07001505 switch (mType) {
1506 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001507 audio_output_flags_t flags = mOutput->flags;
1508 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1509 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1510 // global effects are applied only to non fast tracks if they are SW
1511 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1512 break;
1513 }
1514 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1515 // only post processing on output stage session
1516 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001517 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1518 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001519 return BAD_VALUE;
1520 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001521 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1522 // only post processing on output stage session
1523 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001524 ALOGW("%s: non post processing effect %s not allowed on device session",
1525 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001526 return BAD_VALUE;
1527 }
Eric Laurent4c415062016-06-17 16:14:16 -07001528 } else {
1529 // no restriction on effects applied on non fast tracks
1530 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1531 break;
1532 }
1533 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001534
Eric Laurent4c415062016-06-17 16:14:16 -07001535 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001536 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001537 return BAD_VALUE;
1538 }
1539 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001540 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1541 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001542 return BAD_VALUE;
1543 }
1544 }
1545 } break;
1546 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001547 // nothing actionable on offload threads, if the effect:
1548 // - is offloadable: the effect can be created
1549 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1550 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001551 break;
1552 case DIRECT:
1553 // Reject any effect on Direct output threads for now, since the format of
1554 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001555 ALOGW("%s: effect %s on DIRECT output thread %s",
1556 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001557 return BAD_VALUE;
1558 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001559 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001560 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1561 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001562 return BAD_VALUE;
1563 }
1564 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001565 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1566 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001567 return BAD_VALUE;
1568 }
1569 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001570 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1571 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001572 return BAD_VALUE;
1573 }
1574 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001575 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001576 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1577 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1578 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1579 // are supported and added after the spatializer.
1580 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1581 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1582 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001583 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001584 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1585 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001586 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001587 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1588 break;
1589 }
1590 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1591 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1592 __func__, desc->name);
1593 return BAD_VALUE;
1594 }
1595 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1596 // only post processing on output stage session
1597 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1598 ALOGW("%s: non post processing effect %s not allowed on device session",
1599 __func__, desc->name);
1600 return BAD_VALUE;
1601 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001602 }
1603 break;
jiabinc658e452022-10-21 20:52:21 +00001604 case BIT_PERFECT:
1605 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1606 // Allow HW accelerated effects of tunnel type
1607 break;
1608 }
1609 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1610 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1611 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1612 // 3) there is any bit-perfect track with the given session id.
1613 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1614 sessionId == AUDIO_SESSION_DEVICE) {
1615 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1616 __func__, desc->name, mThreadName);
1617 return BAD_VALUE;
1618 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1619 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1620 __func__, desc->name, sessionId);
1621 return BAD_VALUE;
1622 }
1623 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001624 default:
1625 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1626 }
1627
1628 return NO_ERROR;
1629}
1630
Andy Hungc5007f82023-08-29 14:26:09 -07001631// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001632sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001633 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001634 const sp<IEffectClient>& effectClient,
1635 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001636 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001637 effect_descriptor_t *desc,
1638 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001639 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001640 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001641 bool probe,
1642 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001643{
Andy Hung116bc262023-06-20 18:56:17 -07001644 sp<IAfEffectModule> effect;
1645 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001646 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001647 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001648 bool chainCreated = false;
1649 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001650 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001651
1652 lStatus = initCheck();
1653 if (lStatus != NO_ERROR) {
1654 ALOGW("createEffect_l() Audio driver not initialized.");
1655 goto Exit;
1656 }
1657
Eric Laurent81784c32012-11-19 14:55:58 -08001658 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1659
Andy Hungc5007f82023-08-29 14:26:09 -07001660 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001661 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001662
Eric Laurent4c415062016-06-17 16:14:16 -07001663 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001664 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001665 goto Exit;
1666 }
1667
Eric Laurent81784c32012-11-19 14:55:58 -08001668 // check for existing effect chain with the requested audio session
1669 chain = getEffectChain_l(sessionId);
1670 if (chain == 0) {
1671 // create a new chain for this session
1672 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001673 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 addEffectChain_l(chain);
1675 chain->setStrategy(getStrategyForSession_l(sessionId));
1676 chainCreated = true;
1677 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001678 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001679 }
1680
1681 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1682
1683 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001684 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001685 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001686 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001687 if (lStatus != NO_ERROR) {
1688 goto Exit;
1689 }
1690 effectCreated = true;
1691
jiabinc52b1ff2019-10-31 17:20:42 -07001692 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001693 effect->setDevices(outDeviceTypeAddrs());
1694 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001695 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001696 effect->setAudioSource(mAudioSource);
1697 }
jiabin1319f5a2021-03-30 22:21:24 +00001698 if (effect->isHapticGenerator()) {
1699 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1700 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001701 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001702 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001703 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001704 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001705 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001706 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001707 }
1708 }
Eric Laurent81784c32012-11-19 14:55:58 -08001709 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001710 handle = IAfEffectHandle::create(
1711 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001712 lStatus = handle->initCheck();
1713 if (lStatus == OK) {
1714 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001715 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001716 }
Eric Laurent81784c32012-11-19 14:55:58 -08001717 if (enabled != NULL) {
1718 *enabled = (int)effect->isEnabled();
1719 }
1720 }
1721
1722Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001723 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001724 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001725 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001726 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001727 }
Eric Laurent81784c32012-11-19 14:55:58 -08001728 if (chainCreated) {
1729 removeEffectChain_l(chain);
1730 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001731 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001732 }
1733
Glenn Kasten9156ef32013-08-06 15:39:08 -07001734 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001735 return handle;
1736}
1737
Andy Hungee58e4a2023-07-07 13:47:37 -07001738void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001739 bool unpinIfLast)
1740{
1741 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001742 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001743 {
Andy Hung972bec12023-08-31 16:13:39 -07001744 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001745 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001746 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 return;
1748 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001749 effect = effectBase->asEffectModule();
1750 if (effect == nullptr) {
1751 return;
1752 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001753 // restore suspended effects if the disconnected handle was enabled and the last one.
1754 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1755 if (remove) {
1756 removeEffect_l(effect, true);
1757 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001758 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001759 }
1760 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001761 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001762 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001763 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001764 }
1765 }
1766}
1767
Andy Hungee58e4a2023-07-07 13:47:37 -07001768void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001769 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001770 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001771 broadcast_l();
1772 }
1773 if (!effect->isOffloadable()) {
1774 if (mType == ThreadBase::OFFLOAD) {
1775 PlaybackThread *t = (PlaybackThread *)this;
1776 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1777 }
1778 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001779 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001780 }
1781 }
1782}
1783
Andy Hungee58e4a2023-07-07 13:47:37 -07001784void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001785 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001786 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001787 broadcast_l();
1788 }
1789}
1790
Andy Hungee58e4a2023-07-07 13:47:37 -07001791sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001792 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001793{
Andy Hung972bec12023-08-31 16:13:39 -07001794 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001795 return getEffect_l(sessionId, effectId);
1796}
1797
Andy Hungee58e4a2023-07-07 13:47:37 -07001798sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001799 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001800{
Andy Hung116bc262023-06-20 18:56:17 -07001801 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001802 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1803}
1804
Andy Hungee58e4a2023-07-07 13:47:37 -07001805std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001806{
Andy Hung116bc262023-06-20 18:56:17 -07001807 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001808 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001809}
1810
Andy Hung972bec12023-08-31 16:13:39 -07001811// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1812// ThreadBase::mutex() held
1813status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001814{
1815 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001816 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001817 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001818 bool chainCreated = false;
1819
Eric Laurent5baf2af2013-09-12 17:37:00 -07001820 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001821 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1822 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001823
Eric Laurent81784c32012-11-19 14:55:58 -08001824 if (chain == 0) {
1825 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001826 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001827 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001828 addEffectChain_l(chain);
1829 chain->setStrategy(getStrategyForSession_l(sessionId));
1830 chainCreated = true;
1831 }
Andy Hung972bec12023-08-31 16:13:39 -07001832 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001833
1834 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001835 ALOGW("%s: %p effect %s already present in chain %p",
1836 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001837 return BAD_VALUE;
1838 }
1839
Shunkai Yaod125e402024-01-20 03:19:06 +00001840 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001841
Shunkai Yao29d10572024-03-19 04:31:47 +00001842 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001843 if (status != NO_ERROR) {
1844 if (chainCreated) {
1845 removeEffectChain_l(chain);
1846 }
1847 return status;
1848 }
1849
jiabin8f278ee2019-11-11 12:16:27 -08001850 effect->setDevices(outDeviceTypeAddrs());
1851 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001852 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001853 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001854
Eric Laurent81784c32012-11-19 14:55:58 -08001855 return NO_ERROR;
1856}
1857
Andy Hungee58e4a2023-07-07 13:47:37 -07001858void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001859
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001860 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001861 effect_descriptor_t desc = effect->desc();
1862 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1863 detachAuxEffect_l(effect->id());
1864 }
1865
Andy Hung116bc262023-06-20 18:56:17 -07001866 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001867 if (chain != 0) {
1868 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001869 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001870 removeEffectChain_l(chain);
1871 }
1872 } else {
1873 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1874 }
1875}
1876
Shunkai Yaof4847652024-01-12 00:25:20 +00001877void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1878 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001879{
1880 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001881 for (const auto& effectChain : effectChains) {
1882 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001883 }
1884}
1885
Shunkai Yaof4847652024-01-12 00:25:20 +00001886void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1887 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001888{
Shunkai Yaof4847652024-01-12 00:25:20 +00001889 for (const auto& effectChain : effectChains) {
1890 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001891 }
1892}
1893
Andy Hungee58e4a2023-07-07 13:47:37 -07001894sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001895{
Andy Hung972bec12023-08-31 16:13:39 -07001896 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001897 return getEffectChain_l(sessionId);
1898}
1899
Andy Hungee58e4a2023-07-07 13:47:37 -07001900sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001901 const
Eric Laurent81784c32012-11-19 14:55:58 -08001902{
1903 size_t size = mEffectChains.size();
1904 for (size_t i = 0; i < size; i++) {
1905 if (mEffectChains[i]->sessionId() == sessionId) {
1906 return mEffectChains[i];
1907 }
1908 }
1909 return 0;
1910}
1911
Andy Hungee58e4a2023-07-07 13:47:37 -07001912void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001913{
Andy Hung972bec12023-08-31 16:13:39 -07001914 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001915 size_t size = mEffectChains.size();
1916 for (size_t i = 0; i < size; i++) {
1917 mEffectChains[i]->setMode_l(mode);
1918 }
1919}
1920
Andy Hungee58e4a2023-07-07 13:47:37 -07001921void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001922{
1923 config->type = AUDIO_PORT_TYPE_MIX;
1924 config->ext.mix.handle = mId;
1925 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001926 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001927 config->channel_mask = mChannelMask;
1928 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1929 AUDIO_PORT_CONFIG_FORMAT;
1930}
1931
Andy Hungee58e4a2023-07-07 13:47:37 -07001932void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001933{
Andy Hung972bec12023-08-31 16:13:39 -07001934 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001935 if (mSystemReady) {
1936 return;
1937 }
1938 mSystemReady = true;
1939
1940 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1941 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1942 }
1943 mPendingConfigEvents.clear();
1944}
1945
Andy Hungdae27702016-10-31 14:01:16 -07001946template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001947ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001948 ssize_t index = mActiveTracks.indexOf(track);
1949 if (index >= 0) {
1950 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1951 return index;
1952 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001953 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001954 mActiveTracksGeneration++;
1955 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001956 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001957 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001958 return mActiveTracks.add(track);
1959}
1960
1961template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001962ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001963 ssize_t index = mActiveTracks.remove(track);
1964 if (index < 0) {
1965 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1966 return index;
1967 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001968 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001969 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001970 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001971 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001972 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001973#ifdef TEE_SINK
1974 track->dumpTee(-1 /* fd */, "_REMOVE");
1975#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001976 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001977 return index;
1978}
1979
1980template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001981void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001982 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001983 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001984 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001985 }
1986 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001987 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001988 mActiveTracks.clear();
1989 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001990}
1991
1992template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001993void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001994 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001995 // Updates ActiveTracks client uids to the thread wakelock.
1996 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1997 thread->updateWakeLockUids_l(getWakeLockUids());
1998 mLastActiveTracksGeneration = mActiveTracksGeneration;
1999 }
Andy Hungdae27702016-10-31 14:01:16 -07002000}
Eric Laurent83b88082014-06-20 18:31:16 -07002001
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002002template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002003bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002004 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002005 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002006
2007 for (const sp<T> &track : mActiveTracks) {
2008 // Do not short-circuit as all hasChanged states must be reset
2009 // as all the metadata are going to be sent
2010 hasChanged |= track->readAndClearHasChanged();
2011 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002012 return hasChanged;
2013}
2014
2015template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002016void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002017 const char *funcName, const sp<T> &track) const {
2018 if (mLocalLog != nullptr) {
2019 String8 result;
2020 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002021 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002022 }
2023}
2024
Andy Hungee58e4a2023-07-07 13:47:37 -07002025void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002026{
2027 // Thread could be blocked waiting for async
2028 // so signal it to handle state changes immediately
2029 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2030 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2031 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002032 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002033}
2034
Andy Hungd0979812019-02-21 15:51:44 -08002035// Call only from threadLoop() or when it is idle.
2036// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002037void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002038NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002039{
2040 // Do not log if we have no stats.
2041 // We choose the timestamp verifier because it is the most likely item to be present.
2042 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2043 if (nstats == 0) {
2044 return;
2045 }
2046
2047 // Don't log more frequently than once per 12 hours.
2048 // We use BOOTTIME to include suspend time.
2049 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2050 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2051 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2052 return;
2053 }
2054
2055 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2056 mLastRecordedTimeNs = timeNs;
2057
Ray Essickf27e9872019-12-07 06:28:46 -08002058 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002059
2060#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2061
2062 // thread configuration
2063 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2064 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2065 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2066 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2067 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2068 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2069 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002070 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2071 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002072
2073 // thread statistics
2074 if (mIoJitterMs.getN() > 0) {
2075 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2076 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2077 }
2078 if (mProcessTimeMs.getN() > 0) {
2079 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2080 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2081 }
2082 const auto tsjitter = mTimestampVerifier.getJitterMs();
2083 if (tsjitter.getN() > 0) {
2084 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2085 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2086 }
2087 if (mLatencyMs.getN() > 0) {
2088 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2089 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2090 }
Robert Wu06db0a32021-08-10 19:05:34 +00002091 if (mMonopipePipeDepthStats.getN() > 0) {
2092 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2093 mMonopipePipeDepthStats.getMean());
2094 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2095 mMonopipePipeDepthStats.getStdDev());
2096 }
Andy Hungd0979812019-02-21 15:51:44 -08002097
2098 item->selfrecord();
2099}
2100
Andy Hungee58e4a2023-07-07 13:47:37 -07002101product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002102{
Andy Hung583043b2023-07-17 17:05:00 -07002103 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002104 return PRODUCT_STRATEGY_NONE;
2105 }
2106 return AudioSystem::getStrategyForStream(stream);
2107}
2108
Andy Hungc5007f82023-08-29 14:26:09 -07002109// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002110void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002111 const sp<audio_utils::MelProcessor>& /*processor*/)
2112{
2113 // Do nothing
2114 ALOGW("%s: ThreadBase does not support CSD", __func__);
2115}
2116
Andy Hungc5007f82023-08-29 14:26:09 -07002117// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002118void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002119{
2120 // Do nothing
2121 ALOGW("%s: ThreadBase does not support CSD", __func__);
2122}
2123
Eric Laurent81784c32012-11-19 14:55:58 -08002124// ----------------------------------------------------------------------------
2125// Playback
2126// ----------------------------------------------------------------------------
2127
Andy Hung583043b2023-07-17 17:05:00 -07002128PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002129 AudioStreamOut* output,
2130 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002131 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002132 bool systemReady,
2133 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002134 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002135 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002136 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002137 mMixerBuffer(NULL),
2138 mMixerBufferSize(0),
2139 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2140 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002141 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002142 mEffectBuffer(NULL),
2143 mEffectBufferSize(0),
2144 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2145 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002146 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002147 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002148 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002149 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002150 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002151 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002152 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002153 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002154 mMixerStatus(MIXER_IDLE),
2155 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002156 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 mBytesRemaining(0),
2158 mCurrentWriteLength(0),
2159 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002160 mWriteAckSequence(0),
2161 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002162 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002163 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002164 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002165 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002166 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002167 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002168 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002169{
Glenn Kastend7dca052015-03-05 16:05:54 -08002170 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002171 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002172
Andy Hungc5007f82023-08-29 14:26:09 -07002173 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002174 // it would be safer to explicitly pass initial masterVolume/masterMute as
2175 // parameter.
2176 //
2177 // If the HAL we are using has support for master volume or master mute,
2178 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2179 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002180 mMasterVolume = afThreadCallback->masterVolume_l();
2181 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002182 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002183 if (mOutput->audioHwDev->canSetMasterVolume()) {
2184 mMasterVolume = 1.0;
2185 }
2186
2187 if (mOutput->audioHwDev->canSetMasterMute()) {
2188 mMasterMute = false;
2189 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002190 mIsMsdDevice = strcmp(
2191 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002192 }
2193
Eric Laurentf1f22e72021-07-13 14:04:14 +02002194 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2195 mMixerChannelMask = mixerConfig->channel_mask;
2196 }
2197
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002198 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002199
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002200 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002201 && mMixerChannelMask != mChannelMask) {
2202 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2203 mChannelMask, mMixerChannelMask);
2204 }
2205
Andy Hungc8fddf32018-08-08 18:32:37 -07002206 // TODO: We may also match on address as well as device type for
2207 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002208 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002209 // TODO: This property should be ensure that only contains one single device type.
2210 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2211 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002212 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2213 : AUDIO_DEVICE_NONE));
2214 }
Eric Laurent277a37e2024-07-29 18:37:52 +00002215
2216 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2217 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2218 mStreamTypes[stream].volume = 0.0f;
2219 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002220 }
Eric Laurent277a37e2024-07-29 18:37:52 +00002221 // Audio patch and call assistant volume are always max
2222 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2223 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2224 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2225 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002226}
2227
Andy Hungee58e4a2023-07-07 13:47:37 -07002228PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002229{
Andy Hung583043b2023-07-17 17:05:00 -07002230 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002231 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002232 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002233 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002234 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002235}
2236
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002237// Thread virtuals
2238
Andy Hungee58e4a2023-07-07 13:47:37 -07002239void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002240{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002241 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002242 ALOGE("The stream is not open yet"); // This should not happen.
2243 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002244 // Callbacks take strong or weak pointers as a parameter.
2245 // Since PlaybackThread passes itself as a callback handler, it can only
2246 // be done outside of the constructor. Creating weak and especially strong
2247 // pointers to a refcounted object in its own constructor is strongly
2248 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2249 // Even if a function takes a weak pointer, it is possible that it will
2250 // need to convert it to a strong pointer down the line.
2251 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2252 mOutput->stream->setCallback(this) == OK) {
2253 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002254 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002255 }
2256
jiabinf6eb4c32020-02-25 14:06:25 -08002257 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002258 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002259 }
2260 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002261 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002262 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002263}
2264
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002265// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002266void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002267{
2268 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002269 status_t result = mOutput->stream->exit();
2270 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002271}
2272
Andy Hungee58e4a2023-07-07 13:47:37 -07002273void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002274{
Eric Laurent81784c32012-11-19 14:55:58 -08002275 String8 result;
Eric Laurent277a37e2024-07-29 18:37:52 +00002276
2277 result.appendFormat(" Stream volumes in dB: ");
2278 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2279 const stream_type_t *st = &mStreamTypes[i];
2280 if (i > 0) {
2281 result.appendFormat(", ");
2282 }
2283 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2284 if (st->mute) {
2285 result.append("M");
Eric Laurent81784c32012-11-19 14:55:58 -08002286 }
2287 }
2288 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002289 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002290 result.clear();
2291
Eric Laurent81784c32012-11-19 14:55:58 -08002292 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2293 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002294 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002295 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002296
2297 size_t numtracks = mTracks.size();
2298 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002299 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002300 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002301 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002302 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002303 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002304 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002305 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002306 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002307 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002308 if (track != 0) {
2309 bool active = mActiveTracks.indexOf(track) >= 0;
2310 if (active) {
2311 numactiveseen++;
2312 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002313 result.append(prefix);
2314 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002315 }
2316 }
2317 } else {
2318 result.append("\n");
2319 }
2320 if (numactiveseen != numactive) {
2321 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002322 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002323 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002324 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002325 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002326 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002327 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002328 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002329 result.append(prefix);
2330 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002331 }
2332 }
2333 }
2334
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002335 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002336}
2337
Andy Hungee58e4a2023-07-07 13:47:37 -07002338void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002339{
Andy Hung04cb8f72020-03-20 13:44:33 -07002340 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002341 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002342 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2343 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002344 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2345 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2346 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2347 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002348 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002349 dprintf(fd, " Total writes: %d\n", mNumWrites);
2350 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2351 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002352 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002353 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002354 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002355 AudioStreamOut *output = mOutput;
2356 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002357 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002358 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002359 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2360 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2361 if (mPipeSink.get() != nullptr) {
2362 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2363 }
2364 if (output != nullptr) {
2365 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002366 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002367 }
Eric Laurent81784c32012-11-19 14:55:58 -08002368}
2369
Andy Hungc5007f82023-08-29 14:26:09 -07002370// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002371sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002372 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002373 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002374 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002375 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002376 audio_format_t format,
2377 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002378 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002379 size_t *pNotificationFrameCount,
2380 uint32_t notificationsPerBuffer,
2381 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002382 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002383 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002384 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002385 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002386 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002387 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002388 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002389 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002390 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002391 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002392 bool isBitPerfect,
Eric Laurent277a37e2024-07-29 18:37:52 +00002393 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002394{
Glenn Kasten74935e42013-12-19 08:56:45 -08002395 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002396 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002397 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002398 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002399 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002400 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002401 uint32_t sampleRate;
2402
2403 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2404 lStatus = BAD_VALUE;
2405 goto Exit;
2406 }
Eric Laurent21da6472017-11-09 16:29:26 -08002407
2408 if (*pSampleRate == 0) {
2409 *pSampleRate = mSampleRate;
2410 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002411 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002412
2413 // special case for FAST flag considered OK if fast mixer is present
2414 if (hasFastMixer()) {
2415 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2416 }
2417
2418 // Check if requested flags are compatible with output stream flags
2419 if ((*flags & outputFlags) != *flags) {
2420 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2421 *flags, outputFlags);
2422 *flags = (audio_output_flags_t)(*flags & outputFlags);
2423 }
Eric Laurent81784c32012-11-19 14:55:58 -08002424
jiabinc658e452022-10-21 20:52:21 +00002425 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002426 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002427 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002428 if (chain.get() != nullptr) {
2429 // Bit-perfect is required according to the configuration and preferred mixer
2430 // attributes, but it is not in the output flag from the client's request. Explicitly
2431 // adding bit-perfect flag to check the compatibility
2432 audio_output_flags_t flagsToCheck =
2433 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2434 chain->checkOutputFlagCompatibility(&flagsToCheck);
2435 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2436 ALOGE("%s cannot create track as there is data-processing effect attached to "
2437 "given session id(%d)", __func__, sessionId);
2438 lStatus = BAD_VALUE;
2439 goto Exit;
2440 }
2441 *flags = flagsToCheck;
2442 }
2443 }
2444
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002446 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002447 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // PCM data
2449 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002450 // TODO: extract as a data library function that checks that a computationally
2451 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002452 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002453 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2454 (channelMask == AUDIO_CHANNEL_OUT_MONO
2455 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002456 // hardware sample rate
2457 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002458 // normal mixer has an associated fast mixer
2459 hasFastMixer() &&
2460 // there are sufficient fast track slots available
2461 (mFastTrackAvailMask != 0)
2462 // FIXME test that MixerThread for this fast track has a capable output HAL
2463 // FIXME add a permission test also?
2464 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002465 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2466 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002467 // read the fast track multiplier property the first time it is needed
2468 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2469 if (ok != 0) {
2470 ALOGE("%s pthread_once failed: %d", __func__, ok);
2471 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002472 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002473 }
Eric Laurent4c415062016-06-17 16:14:16 -07002474
2475 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002476 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002477 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002478 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002479 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002480 AUDIO_SESSION_OUTPUT_STAGE,
2481 AUDIO_SESSION_OUTPUT_MIX,
2482 sessionId,
2483 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002484 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002485 if (chain.get() != nullptr) {
2486 audio_output_flags_t old = *flags;
2487 chain->checkOutputFlagCompatibility(flags);
2488 if (old != *flags) {
2489 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2490 (int)session, (int)old, (int)*flags);
2491 }
Eric Laurent4c415062016-06-17 16:14:16 -07002492 }
2493 }
2494 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002495 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002496 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2497 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002498 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002499 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002500 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002501 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002502 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002503 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002504 audio_is_linear_pcm(format), channelMask, sampleRate,
2505 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002506 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002507 }
2508 }
Eric Laurent21da6472017-11-09 16:29:26 -08002509
2510 if (!audio_has_proportional_frames(format)) {
2511 if (sharedBuffer != 0) {
2512 // Same comment as below about ignoring frameCount parameter for set()
2513 frameCount = sharedBuffer->size();
2514 } else if (frameCount == 0) {
2515 frameCount = mNormalFrameCount;
2516 }
2517 if (notificationFrameCount != frameCount) {
2518 notificationFrameCount = frameCount;
2519 }
2520 } else if (sharedBuffer != 0) {
2521 // FIXME: Ensure client side memory buffers need
2522 // not have additional alignment beyond sample
2523 // (e.g. 16 bit stereo accessed as 32 bit frame).
2524 size_t alignment = audio_bytes_per_sample(format);
2525 if (alignment & 1) {
2526 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2527 alignment = 1;
2528 }
2529 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2530 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2531 if (channelCount > 1) {
2532 // More than 2 channels does not require stronger alignment than stereo
2533 alignment <<= 1;
2534 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002535 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002536 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002537 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002538 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002539 goto Exit;
2540 }
Eric Laurent21da6472017-11-09 16:29:26 -08002541
2542 // When initializing a shared buffer AudioTrack via constructors,
2543 // there's no frameCount parameter.
2544 // But when initializing a shared buffer AudioTrack via set(),
2545 // there _is_ a frameCount parameter. We silently ignore it.
2546 frameCount = sharedBuffer->size() / frameSize;
2547 } else {
2548 size_t minFrameCount = 0;
2549 // For fast tracks we try to respect the application's request for notifications per buffer.
2550 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2551 if (notificationsPerBuffer > 0) {
2552 // Avoid possible arithmetic overflow during multiplication.
2553 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2554 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2555 notificationsPerBuffer, mFrameCount);
2556 } else {
2557 minFrameCount = mFrameCount * notificationsPerBuffer;
2558 }
2559 }
2560 } else {
2561 // For normal PCM streaming tracks, update minimum frame count.
2562 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2563 // cover audio hardware latency.
2564 // This is probably too conservative, but legacy application code may depend on it.
2565 // If you change this calculation, also review the start threshold which is related.
2566 uint32_t latencyMs = latency_l();
2567 if (latencyMs == 0) {
2568 ALOGE("Error when retrieving output stream latency");
2569 lStatus = UNKNOWN_ERROR;
2570 goto Exit;
2571 }
2572
2573 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2574 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2575
Eric Laurent81784c32012-11-19 14:55:58 -08002576 }
Eric Laurent21da6472017-11-09 16:29:26 -08002577 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002578 frameCount = minFrameCount;
2579 }
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
Eric Laurent21da6472017-11-09 16:29:26 -08002581
2582 // Make sure that application is notified with sufficient margin before underrun.
2583 // The client can divide the AudioTrack buffer into sub-buffers,
2584 // and expresses its desire to server as the notification frame count.
2585 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2586 size_t maxNotificationFrames;
2587 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2588 // notify every HAL buffer, regardless of the size of the track buffer
2589 maxNotificationFrames = mFrameCount;
2590 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002591 // Triple buffer the notification period for a triple buffered mixer period;
2592 // otherwise, double buffering for the notification period is fine.
2593 //
2594 // TODO: This should be moved to AudioTrack to modify the notification period
2595 // on AudioTrack::setBufferSizeInFrames() changes.
2596 const int nBuffering =
2597 (uint64_t{frameCount} * mSampleRate)
2598 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2599
Eric Laurent21da6472017-11-09 16:29:26 -08002600 maxNotificationFrames = frameCount / nBuffering;
2601 // If client requested a fast track but this was denied, then use the smaller maximum.
2602 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2603 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2604 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2605 maxNotificationFrames = maxNotificationFramesFastDenied;
2606 }
2607 }
2608 }
2609 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2610 if (notificationFrameCount == 0) {
2611 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2612 maxNotificationFrames, frameCount);
2613 } else {
2614 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2615 notificationFrameCount, maxNotificationFrames, frameCount);
2616 }
2617 notificationFrameCount = maxNotificationFrames;
2618 }
2619 }
2620
Glenn Kasten74935e42013-12-19 08:56:45 -08002621 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002622 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002623
Glenn Kastenc3df8382014-03-13 15:05:25 -07002624 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002625 case BIT_PERFECT:
2626 if (isBitPerfect) {
2627 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2628 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2629 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2630 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2631 mChannelMask);
2632 lStatus = BAD_VALUE;
2633 goto Exit;
2634 }
2635 }
2636 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002637
2638 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002639 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002640 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002641 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2642 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002643 sampleRate, format, channelMask, mOutput, mFormat);
2644 lStatus = BAD_VALUE;
2645 goto Exit;
2646 }
2647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002648 break;
2649
2650 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002652 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2653 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 sampleRate, format, channelMask, mOutput, mFormat);
2655 lStatus = BAD_VALUE;
2656 goto Exit;
2657 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002658 break;
2659
2660 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002661 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002662 ALOGE("createTrack_l() Bad parameter: format %#x \""
2663 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 format, mOutput, mFormat);
2665 lStatus = BAD_VALUE;
2666 goto Exit;
2667 }
Andy Hungcd044842014-08-07 11:04:34 -07002668 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002669 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2670 lStatus = BAD_VALUE;
2671 goto Exit;
2672 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002673 break;
2674
Eric Laurent81784c32012-11-19 14:55:58 -08002675 }
2676
2677 lStatus = initCheck();
2678 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002679 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002680 goto Exit;
2681 }
2682
Andy Hungc5007f82023-08-29 14:26:09 -07002683 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002684 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002685
2686 // all tracks in same audio session must share the same routing strategy otherwise
2687 // conflicts will happen when tracks are moved from one output to another by audio policy
2688 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002689 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002690 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002691 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002692 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002693 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002694 if (sessionId == t->sessionId() && strategy != actual) {
2695 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2696 strategy, actual);
2697 lStatus = BAD_VALUE;
2698 goto Exit;
2699 }
2700 }
2701 }
2702
Deeraj Soman2b515232024-05-14 12:58:24 +05302703 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2704 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002705 // dynamic audio policy.
2706 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302707 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002708 audio_output_flags_t trackFlags = *flags;
2709 if (mType == DIRECT) {
2710 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302711 } else if (mType == OFFLOAD) {
2712 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2713 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002714 }
jiabin94ed47c2023-07-27 23:34:20 +00002715 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002716
Andy Hung8d31fd22023-06-26 19:20:57 -07002717 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002718 channelMask, frameCount,
2719 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002720 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002721 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Eric Laurent277a37e2024-07-29 18:37:52 +00002722 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002723
Glenn Kasten03003332013-08-06 15:40:54 -07002724 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2725 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002726 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002727 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002728 goto Exit;
2729 }
2730 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002731 {
Andy Hung972bec12023-08-31 16:13:39 -07002732 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002733 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002734 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002735 }
2736 }
Eric Laurent81784c32012-11-19 14:55:58 -08002737
Andy Hung116bc262023-06-20 18:56:17 -07002738 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002739 if (chain != 0) {
2740 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2741 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002742 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002743 chain->incTrackCnt();
2744 }
2745
Eric Laurent05067782016-06-01 18:27:28 -07002746 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002747 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2748 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2749 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002750 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002751 }
2752 }
2753
2754 lStatus = NO_ERROR;
2755
2756Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002757 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002758 return track;
2759}
2760
Andy Hung1bc088a2018-02-09 15:57:31 -08002761template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002762ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002763{
Andy Hungc0691382018-09-12 18:01:57 -07002764 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002765 const ssize_t index = mTracks.remove(track);
2766 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002767 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002768 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002769 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002770 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002771 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002772 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002773 }
2774 return index;
2775}
2776
Andy Hungee58e4a2023-07-07 13:47:37 -07002777uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002778{
2779 return latency;
2780}
2781
Andy Hungee58e4a2023-07-07 13:47:37 -07002782uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002783{
Andy Hung972bec12023-08-31 16:13:39 -07002784 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002785 return latency_l();
2786}
Andy Hungee58e4a2023-07-07 13:47:37 -07002787uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002788NO_THREAD_SAFETY_ANALYSIS
2789// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002790{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002791 uint32_t latency;
2792 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2793 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002794 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002795 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002796}
2797
Andy Hungee58e4a2023-07-07 13:47:37 -07002798void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002799{
Andy Hung972bec12023-08-31 16:13:39 -07002800 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002801 // Don't apply master volume in SW if our HAL can do it for us.
2802 if (mOutput && mOutput->audioHwDev &&
2803 mOutput->audioHwDev->canSetMasterVolume()) {
2804 mMasterVolume = 1.0;
2805 } else {
2806 mMasterVolume = value;
2807 }
2808}
2809
Andy Hungee58e4a2023-07-07 13:47:37 -07002810void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002811{
2812 mMasterBalance.store(balance);
2813}
2814
Andy Hungee58e4a2023-07-07 13:47:37 -07002815void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002816{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002817 if (isDuplicating()) {
2818 return;
2819 }
Andy Hung972bec12023-08-31 16:13:39 -07002820 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002821 // Don't apply master mute in SW if our HAL can do it for us.
2822 if (mOutput && mOutput->audioHwDev &&
2823 mOutput->audioHwDev->canSetMasterMute()) {
2824 mMasterMute = false;
2825 } else {
2826 mMasterMute = muted;
2827 }
2828}
2829
Andy Hungee58e4a2023-07-07 13:47:37 -07002830void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002831{
Andy Hung972bec12023-08-31 16:13:39 -07002832 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002833 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002834 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002835}
2836
Andy Hungee58e4a2023-07-07 13:47:37 -07002837void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002838{
Andy Hung972bec12023-08-31 16:13:39 -07002839 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002840 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002841 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002842}
2843
Andy Hungee58e4a2023-07-07 13:47:37 -07002844float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002845{
Andy Hung972bec12023-08-31 16:13:39 -07002846 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002847 return mStreamTypes[stream].volume;
2848}
2849
Andy Hungee58e4a2023-07-07 13:47:37 -07002850void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002851{
2852 mOutput->stream->setVolume(left, right);
2853}
2854
Andy Hungc5007f82023-08-29 14:26:09 -07002855// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002856status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002857{
2858 status_t status = ALREADY_EXISTS;
2859
Eric Laurent81784c32012-11-19 14:55:58 -08002860 if (mActiveTracks.indexOf(track) < 0) {
2861 // the track is newly added, make sure it fills up all its
2862 // buffers before playing. This is to ensure the client will
2863 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002864 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002865 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002866 // Because the track is not on the ActiveTracks,
2867 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002868 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002869 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002870 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002872 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002874 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002875 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002876 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 }
2878 return INVALID_OPERATION;
2879 }
2880 // abort if start is rejected by audio policy manager
2881 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002882 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2883 // current playback thread is reopened, which may happen when clients set preferred
2884 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2885 // immediately.
2886 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 }
2888#ifdef ADD_BATTERY_DATA
2889 // to track the speaker usage
2890 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2891#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002892 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 }
2894
Eric Laurent51716182016-02-29 18:00:56 -08002895 // set retry count for buffer fill
2896 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002897 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002898 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002899 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002900 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002901 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002902 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002903 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002904 track->retryCount() = kMaxTrackStartupRetries;
2905 track->fillingStatus() =
2906 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002907 }
2908
Andy Hung116bc262023-06-20 18:56:17 -07002909 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002910 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2911 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002912 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002913 // Unlock due to VibratorService will lock for this call and will
2914 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002915 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002916 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002917 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002918 std::optional<media::AudioVibratorInfo> vibratorInfo;
2919 {
2920 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2921 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002922 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002923 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002924 }
Andy Hungc5007f82023-08-29 14:26:09 -07002925 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002926 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002927 if (vibratorInfo) {
2928 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2929 }
2930
jiabin57303cc2018-12-18 15:45:57 -08002931 // Haptic playback should be enabled by vibrator service.
2932 if (track->getHapticPlaybackEnabled()) {
2933 // Disable haptic playback of all active track to ensure only
2934 // one track playing haptic if current track should play haptic.
2935 for (const auto &t : mActiveTracks) {
2936 t->setHapticPlaybackEnabled(false);
2937 }
jiabin245cdd92018-12-07 17:55:15 -08002938 }
jiabine70bc7f2020-06-30 22:07:55 -07002939
2940 // Set haptic intensity for effect
2941 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002942 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002943 }
jiabin245cdd92018-12-07 17:55:15 -08002944 }
2945
Andy Hung8d31fd22023-06-26 19:20:57 -07002946 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002947 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002948
2949 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2950 // all key changes are complete. It is possible that the threadLoop will begin
2951 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002952 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002953
Eric Laurentd0107bc2013-06-11 14:38:48 -07002954 if (chain != 0) {
2955 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2956 track->sessionId());
2957 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002958 }
2959
Andy Hungc2b11cb2020-04-22 09:04:01 -07002960 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002961 status = NO_ERROR;
2962 }
2963
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002964 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002965 return status;
2966}
2967
Andy Hungee58e4a2023-07-07 13:47:37 -07002968bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002969{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002971 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002972 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002973 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002974 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002975 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002976 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002977 if (track->isPausePending()) {
2978 track->pauseAck();
2979 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002980 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982
2983 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002984}
2985
Andy Hungee58e4a2023-07-07 13:47:37 -07002986void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002987{
2988 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002989
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002990 String8 result;
2991 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002992 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002993
Eric Laurent81784c32012-11-19 14:55:58 -08002994 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002995 {
Andy Hung972bec12023-08-31 16:13:39 -07002996 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002997 mAudioTrackCallbacks.erase(track);
2998 }
Eric Laurent81784c32012-11-19 14:55:58 -08002999 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003000 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003001 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003002 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3003 mFastTrackAvailMask |= 1 << index;
3004 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003005 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003006 }
Andy Hung116bc262023-06-20 18:56:17 -07003007 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003008 if (chain != 0) {
3009 chain->decTrackCnt();
3010 }
3011}
3012
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003013std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3014{
3015 std::set<int32_t> result;
3016 for (const auto& t : mTracks) {
3017 if (t->isExternalTrack()) {
3018 result.insert(t->portId());
3019 }
3020 }
3021 return result;
3022}
3023
3024std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3025{
3026 audio_utils::lock_guard _l(mutex());
3027 return getTrackPortIds_l();
3028}
3029
Andy Hungee58e4a2023-07-07 13:47:37 -07003030String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003031{
Andy Hung972bec12023-08-31 16:13:39 -07003032 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003033 String8 out_s8;
3034 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3035 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003036 }
Andy Hung920f6572022-10-06 12:09:49 -07003037 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003038}
3039
Andy Hungee58e4a2023-07-07 13:47:37 -07003040status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003041 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003042 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003043 return NO_INIT;
3044 }
3045 return mOutput->stream->selectPresentation(presentationId, programId);
3046}
3047
Andy Hungab65b182023-09-06 19:41:47 -07003048void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003049 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003050 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003051 sp<AudioIoDescriptor> desc;
3052 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003053 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003054 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003055 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003056 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003057 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3058 mSampleRate, mFormat, mChannelMask,
3059 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3060 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003061 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003062 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003063 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003064 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003065 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003066 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003067 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003068 break;
3069 }
Andy Hungab65b182023-09-06 19:41:47 -07003070 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003071}
3072
Andy Hungee58e4a2023-07-07 13:47:37 -07003073void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003074{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003075 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003076}
3077
Andy Hungee58e4a2023-07-07 13:47:37 -07003078void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003079{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003080 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081}
3082
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003083void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003084{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003085 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003086}
3087
Andy Hungee58e4a2023-07-07 13:47:37 -07003088void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003089 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003090{
Andy Hungee58e4a2023-07-07 13:47:37 -07003091 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003092 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003093 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003094 if (playbackThread == nullptr) {
3095 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3096 return;
3097 }
3098
jiabinf6eb4c32020-02-25 14:06:25 -08003099 audio_utils::metadata::Data metadata =
3100 audio_utils::metadata::dataFromByteString(metadataBs);
3101 if (metadata.empty()) {
3102 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3103 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3104 (int)metadataBs.size());
3105 return;
3106 }
3107
3108 audio_utils::metadata::ByteString metaDataStr =
3109 audio_utils::metadata::byteStringFromData(metadata);
3110 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003111 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003112 for (const auto& callbackPair : mAudioTrackCallbacks) {
3113 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003114 }
3115 }).detach();
3116}
3117
Andy Hungee58e4a2023-07-07 13:47:37 -07003118void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119{
Andy Hung972bec12023-08-31 16:13:39 -07003120 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003121 // reject out of sequence requests
3122 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3123 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003124 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003125 }
3126}
3127
Andy Hungee58e4a2023-07-07 13:47:37 -07003128void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003129{
Andy Hung972bec12023-08-31 16:13:39 -07003130 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003131 // reject out of sequence requests
3132 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003133 // Register discontinuity when HW drain is completed because that can cause
3134 // the timestamp frame position to reset to 0 for direct and offload threads.
3135 // (Out of sequence requests are ignored, since the discontinuity would be handled
3136 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003137 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003138 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003139 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003140 }
3141}
3142
Andy Hungee58e4a2023-07-07 13:47:37 -07003143void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003144NO_THREAD_SAFETY_ANALYSIS
3145// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003146{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003147 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003148 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3149 mSampleRate = audioConfig.sample_rate;
3150 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003151 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003152 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003153 }
Andy Hung81994d62023-07-20 21:44:14 -07003154 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003155 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3156 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003157 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003158
3159 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3160 mMixerChannelMask = mChannelMask;
3161 }
3162
Andy Hunge5412692014-05-16 11:25:07 -07003163 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003164 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003165
Eric Laurentf1f22e72021-07-13 14:04:14 +02003166 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3167
Phil Burkca5e6142015-07-14 09:42:29 -07003168 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003169 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003170 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003171 // Get format from the shim, which will be different than the HAL format
3172 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003173 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003174 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003175 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003176 }
Andy Hung81994d62023-07-20 21:44:14 -07003177 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003178 LOG_FATAL("HAL format %#x not supported for mixed output",
3179 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003180 }
Phil Burk062e67a2015-02-11 13:40:50 -08003181 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003182 result = mOutput->stream->getBufferSize(&mBufferSize);
3183 LOG_ALWAYS_FATAL_IF(result != OK,
3184 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003185 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003186 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003187 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003188 mFrameCount);
3189 }
3190
Eric Laurentd1f69b02014-12-15 14:33:13 -08003191 mHwSupportsPause = false;
3192 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003193 bool supportsPause = false, supportsResume = false;
3194 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3195 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003196 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003197 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003198 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003199 } else if (supportsResume) {
3200 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003201 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003202 }
3203 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003204 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3205 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3206 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003207
Andy Hungfbfc3952015-01-15 13:33:51 -08003208 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3209 // For best precision, we use float instead of the associated output
3210 // device format (typically PCM 16 bit).
3211
3212 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3213 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3214 mBufferSize = mFrameSize * mFrameCount;
3215
3216 // TODO: We currently use the associated output device channel mask and sample rate.
3217 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3218 // (if a valid mask) to avoid premature downmix.
3219 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3220 // instead of the output device sample rate to avoid loss of high frequency information.
3221 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3222 }
3223
Andy Hung09a50072014-02-27 14:30:47 -08003224 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003225 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003226 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003227 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3228 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003229 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3230 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003231
Eric Laurent81784c32012-11-19 14:55:58 -08003232 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3233 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3234 maxNormalFrameCount = maxNormalFrameCount & ~15;
3235 if (maxNormalFrameCount < minNormalFrameCount) {
3236 maxNormalFrameCount = minNormalFrameCount;
3237 }
3238 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3239 if (multiplier <= 1.0) {
3240 multiplier = 1.0;
3241 } else if (multiplier <= 2.0) {
3242 if (2 * mFrameCount <= maxNormalFrameCount) {
3243 multiplier = 2.0;
3244 } else {
3245 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3246 }
3247 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003248 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003249 }
3250 }
3251 mNormalFrameCount = multiplier * mFrameCount;
3252 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003253 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003254 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3255 }
Andy Hungab65b182023-09-06 19:41:47 -07003256 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3257 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003258
Andy Hung08fb1742015-05-31 23:22:10 -07003259 // Check if we want to throttle the processing to no more than 2x normal rate
3260 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003261 mThreadThrottleTimeMs = 0;
3262 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003263 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3264
Andy Hung010a1a12014-03-13 13:57:33 -07003265 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3266 // Originally this was int16_t[] array, need to remove legacy implications.
3267 free(mSinkBuffer);
3268 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003269
Andy Hung5b10a202014-03-13 13:59:29 -07003270 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3271 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3272 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003273 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003274
Andy Hung69aed5f2014-02-25 17:24:40 -08003275 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3276 // drives the output.
3277 free(mMixerBuffer);
3278 mMixerBuffer = NULL;
3279 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003280 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003281 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003282 * audio_bytes_per_sample(mMixerBufferFormat);
3283 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3284 }
Andy Hung98ef9782014-03-04 14:46:50 -08003285 free(mEffectBuffer);
3286 mEffectBuffer = NULL;
3287 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003288 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003289 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003290 * audio_bytes_per_sample(mEffectBufferFormat);
3291 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3292 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003293
Eric Laurentb62d0362021-10-26 17:40:18 +02003294 if (mType == SPATIALIZER) {
3295 free(mPostSpatializerBuffer);
3296 mPostSpatializerBuffer = nullptr;
3297 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3298 * audio_bytes_per_sample(mEffectBufferFormat);
3299 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3300 }
3301
Mikhail Naganov55773032020-10-01 15:08:13 -07003302 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3303 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003304 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3305 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003306 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003307
Eric Laurent81784c32012-11-19 14:55:58 -08003308 // force reconfiguration of effect chains and engines to take new buffer size and audio
3309 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003310 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003311 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3312 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003313 // create a copy of mEffectChains as calling moveEffectChain_ll()
3314 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003315 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003316 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003317 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003318 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003319 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003320
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003321 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003322 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003323 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003324 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003325 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3326 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3327 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3328 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3329 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3330 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3331 (int32_t)mHapticChannelMask)
3332 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3333 (int32_t)mHapticChannelCount)
3334 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003335 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003336 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3337 (int32_t)mFrameCount) // sic - added HAL
3338 ;
3339 uint32_t latencyMs;
3340 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3341 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3342 }
3343 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003344}
3345
Andy Hungee58e4a2023-07-07 13:47:37 -07003346ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003347{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003348 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003349 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003350 }
3351 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003352 static const bool stereo_spatialization_property =
3353 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3354 const bool stereo_spatialization_enabled =
3355 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3356 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003357 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3358 for (const sp<IAfTrack>& track : mActiveTracks) {
3359 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3360 allSessionsMetadata[track->sessionId()];
3361 auto backInserter = std::back_inserter(sessionMetadata);
3362 // No track is invalid as this is called after prepareTrack_l in the same
3363 // critical section
3364 track->copyMetadataTo(backInserter);
3365 }
3366 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3367 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3368 metadata.tracks.insert(metadata.tracks.end(),
3369 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3370 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3371 chain->sendMetadata_l(sessionTrackMetadata, {});
3372 }
3373 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3374 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3375 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3376 }
3377 }
3378 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3379 chain->sendMetadata_l(metadata.tracks, {});
3380 }
3381 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3382 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3383 }
3384 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3385 chain->sendMetadata_l(metadata.tracks, {});
3386 }
3387 } else {
3388 auto backInserter = std::back_inserter(metadata.tracks);
3389 for (const sp<IAfTrack>& track : mActiveTracks) {
3390 // No track is invalid as this is called after prepareTrack_l in the same
3391 // critical section
3392 track->copyMetadataTo(backInserter);
3393 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003394 }
Kevin Rocard12381092018-04-11 09:19:59 -07003395 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003396 MetadataUpdate change;
3397 change.playbackMetadataUpdate = metadata.tracks;
3398 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003399}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003400
Andy Hungee58e4a2023-07-07 13:47:37 -07003401void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003402 const StreamOutHalInterface::SourceMetadata& metadata)
3403{
3404 mOutput->stream->updateSourceMetadata(metadata);
3405};
3406
Andy Hungee58e4a2023-07-07 13:47:37 -07003407status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003408 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003409{
3410 if (halFrames == NULL || dspFrames == NULL) {
3411 return BAD_VALUE;
3412 }
Andy Hung972bec12023-08-31 16:13:39 -07003413 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003414 if (initCheck() != NO_ERROR) {
3415 return INVALID_OPERATION;
3416 }
Andy Hung818e7a32016-02-16 18:08:07 -08003417 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003418 *halFrames = framesWritten;
3419
3420 if (isSuspended()) {
3421 // return an estimation of rendered frames when the output is suspended
3422 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003423 *dspFrames = (uint32_t)
3424 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003425 return NO_ERROR;
3426 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003427 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003428 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003429 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003430 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003431 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003432 }
3433}
3434
Andy Hungee58e4a2023-07-07 13:47:37 -07003435product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003436{
3437 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3438 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3439 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003440 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003441 }
3442 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003443 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003444 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003445 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003446 }
3447 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003448 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003449}
3450
3451
Andy Hungee58e4a2023-07-07 13:47:37 -07003452AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003453{
Andy Hung972bec12023-08-31 16:13:39 -07003454 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003455 return mOutput;
3456}
3457
Andy Hungee58e4a2023-07-07 13:47:37 -07003458AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003459{
Andy Hung972bec12023-08-31 16:13:39 -07003460 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003461 AudioStreamOut *output = mOutput;
3462 mOutput = NULL;
3463 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3464 // must push a NULL and wait for ack
3465 mOutputSink.clear();
3466 mPipeSink.clear();
3467 mNormalSink.clear();
3468 return output;
3469}
3470
Andy Hungc5007f82023-08-29 14:26:09 -07003471// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003472sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003473{
3474 if (mOutput == NULL) {
3475 return NULL;
3476 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003477 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003478}
3479
Andy Hungee58e4a2023-07-07 13:47:37 -07003480uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003481{
3482 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3483}
3484
Andy Hungee58e4a2023-07-07 13:47:37 -07003485status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003486{
3487 if (!isValidSyncEvent(event)) {
3488 return BAD_VALUE;
3489 }
3490
Andy Hung972bec12023-08-31 16:13:39 -07003491 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003492
3493 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003494 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003495 if (event->triggerSession() == track->sessionId()) {
3496 (void) track->setSyncEvent(event);
3497 return NO_ERROR;
3498 }
3499 }
3500
3501 return NAME_NOT_FOUND;
3502}
3503
Andy Hungee58e4a2023-07-07 13:47:37 -07003504bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003505{
3506 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3507}
3508
Andy Hungee58e4a2023-07-07 13:47:37 -07003509void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003510 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003511{
Andy Hungfe726a62018-09-27 15:17:25 -07003512 // Miscellaneous track cleanup when removed from the active list,
3513 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003515 for (const auto& track : tracksToRemove) {
3516 if (track->isExternalTrack()) {
3517 // to track the speaker usage
3518 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003519 }
3520 }
Andy Hungfe726a62018-09-27 15:17:25 -07003521#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003522}
3523
Andy Hungee58e4a2023-07-07 13:47:37 -07003524void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003525{
3526 if (!mMasterMute) {
3527 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003528 if (mOutDeviceTypeAddrs.empty()) {
3529 ALOGD("ro.audio.silent is ignored since no output device is set");
3530 return;
3531 }
Andy Hungab65b182023-09-06 19:41:47 -07003532 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003533 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3534 return;
3535 }
Eric Laurent81784c32012-11-19 14:55:58 -08003536 if (property_get("ro.audio.silent", value, "0") > 0) {
3537 char *endptr;
3538 unsigned long ul = strtoul(value, &endptr, 0);
3539 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003540 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // The setprop command will not allow a property to be changed after
3542 // the first time it is set, so we don't have to worry about un-muting.
3543 setMasterMute_l(true);
3544 }
3545 }
3546 }
3547}
3548
3549// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003550ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003551{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003552 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003553 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003555 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003556
3557 // If an NBAIO sink is present, use it to write the normal mixer's submix
3558 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003559
Andy Hung010a1a12014-03-13 13:57:33 -07003560 const size_t count = mBytesRemaining / mFrameSize;
3561
Simon Wilson2d590962012-11-29 15:18:50 -08003562 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003563 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003564 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003565 if (screenState != mScreenState) {
3566 mScreenState = screenState;
3567 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3568 if (pipe != NULL) {
3569 pipe->setAvgFrames((mScreenState & 1) ?
3570 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3571 }
3572 }
Andy Hung010a1a12014-03-13 13:57:33 -07003573 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003574 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003575
Eric Laurent81784c32012-11-19 14:55:58 -08003576 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003577 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003578
Andy Hung8946a282018-04-19 20:04:56 -07003579#ifdef TEE_SINK
3580 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3581#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003582 } else {
3583 bytesWritten = framesWritten;
3584 }
3585 // otherwise use the HAL / AudioStreamOut directly
3586 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003588
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003590 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3591 mWriteAckSequence += 2;
3592 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003593 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003594 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003596 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003597 // FIXME We should have an implementation of timestamps for direct output threads.
3598 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003599 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003600 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003601
Eric Laurentbfb1b832013-01-07 09:53:42 -08003602 if (mUseAsyncWrite &&
3603 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3604 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003605 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003606 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003607 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003608 }
Eric Laurent81784c32012-11-19 14:55:58 -08003609 }
3610
Eric Laurent81784c32012-11-19 14:55:58 -08003611 mNumWrites++;
3612 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003613 if (mStandby) {
3614 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003615 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003616 mStandby = false;
3617 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 return bytesWritten;
3619}
3620
Andy Hungc5007f82023-08-29 14:26:09 -07003621// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003622void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003623 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003624{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003625 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003626 if (outputSink != nullptr) {
3627 outputSink->startMelComputation(processor);
3628 }
Vlad Popab042ee62022-10-20 18:05:00 +02003629}
3630
Andy Hungc5007f82023-08-29 14:26:09 -07003631// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003632void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003633{
3634 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003635 if (outputSink != nullptr) {
3636 outputSink->stopMelComputation();
3637 }
Vlad Popab042ee62022-10-20 18:05:00 +02003638}
3639
Andy Hungee58e4a2023-07-07 13:47:37 -07003640void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003641{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003642 bool supportsDrain = false;
3643 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3645 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003646 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3647 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003648 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003649 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003650 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003651 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003652 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003653 }
3654}
3655
Andy Hungee58e4a2023-07-07 13:47:37 -07003656void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003657{
Eric Laurent275e8e92014-11-30 15:14:47 -08003658 {
Andy Hung972bec12023-08-31 16:13:39 -07003659 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003660 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003661 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003662 track->invalidate();
3663 }
Andy Hungdae27702016-10-31 14:01:16 -07003664 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3665 // After we exit there are no more track changes sent to BatteryNotifier
3666 // because that requires an active threadLoop.
3667 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3668 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003669 }
Eric Laurent81784c32012-11-19 14:55:58 -08003670}
3671
3672/*
3673The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003674 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003675 - mActiveSleepTimeUs from activeSleepTimeUs()
3676 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003677 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3678 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003679 - maxPeriod from frame count and sample rate (MIXER only)
3680
3681The parameters that affect these derived values are:
3682 - frame count
3683 - frame size
3684 - sample rate
3685 - device type: A2DP or not
3686 - device latency
3687 - format: PCM or not
3688 - active sleep time
3689 - idle sleep time
3690*/
3691
Andy Hungee58e4a2023-07-07 13:47:37 -07003692void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003693{
Andy Hung25c2dac2014-02-27 14:56:00 -08003694 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003695 mActiveSleepTimeUs = activeSleepTimeUs();
3696 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003697
Andy Hung8fe87eb2023-07-20 21:31:38 -07003698 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003699
Eric Laurent42537be2016-01-08 17:16:42 -08003700 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3701 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003702 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003703 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3704 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3705 }
3706 }
Eric Laurent81784c32012-11-19 14:55:58 -08003707}
3708
Andy Hungee58e4a2023-07-07 13:47:37 -07003709bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003710{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003711 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003712 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003713 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003714 size_t size = mTracks.size();
3715 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003716 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003717 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003718 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003719 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003720 }
3721 }
Eric Laurent13084622016-05-17 10:51:49 -07003722 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003723}
3724
Andy Hungee58e4a2023-07-07 13:47:37 -07003725void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003726{
Andy Hung972bec12023-08-31 16:13:39 -07003727 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003728 invalidateTracks_l(streamType);
3729}
3730
Andy Hungee58e4a2023-07-07 13:47:37 -07003731void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003732 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003733 invalidateTracks_l(portIds);
3734}
3735
Andy Hungee58e4a2023-07-07 13:47:37 -07003736bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003737 bool trackMatch = false;
3738 const size_t size = mTracks.size();
3739 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003740 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003741 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3742 t->invalidate();
3743 portIds.erase(t->portId());
3744 trackMatch = true;
3745 }
3746 if (portIds.empty()) {
3747 break;
3748 }
3749 }
3750 return trackMatch;
3751}
3752
jiabinf042b9b2021-05-07 23:46:28 +00003753// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003754IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003755 audio_port_handle_t trackPortId) {
3756 for (size_t i = 0; i < mTracks.size(); i++) {
3757 if (mTracks[i]->portId() == trackPortId) {
3758 return mTracks[i].get();
3759 }
3760 }
3761 return nullptr;
3762}
3763
Andy Hungee58e4a2023-07-07 13:47:37 -07003764status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003765{
Glenn Kastend848eb42016-03-08 13:42:11 -08003766 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003767 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003768 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003769
Andy Hungd3639922022-04-28 18:00:49 -07003770 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003771 if (!audio_is_global_session(session)) {
3772 // player sessions on a spatializer output will use a dedicated input buffer and
3773 // will either output multi channel to mEffectBuffer if the track is spatilaized
3774 // or stereo to mPostSpatializerBuffer if not spatialized.
3775 uint32_t channelMask;
3776 bool isSessionSpatialized =
3777 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3778 if (isSessionSpatialized) {
3779 channelMask = mMixerChannelMask;
3780 } else {
3781 channelMask = mChannelMask;
3782 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003783 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003784 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003785 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003786 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003787 &halInBuffer);
3788 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003789
Andy Hung583043b2023-07-17 17:05:00 -07003790 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003791 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3792 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3793 &halOutBuffer);
3794 if (result != OK) return result;
3795
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003796 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003797
Mikhail Naganov022b9952017-01-04 16:36:51 -08003798 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3799 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003800 } else {
3801 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3802 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3803 // mPostSpatializerBuffer as output buffer
3804 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003805 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003806 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3807 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003808 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003809 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3810 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003811
Eric Laurentb62d0362021-10-26 17:40:18 +02003812 if (session == AUDIO_SESSION_DEVICE) {
3813 halInBuffer = halOutBuffer;
3814 }
3815 }
3816 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003817 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003818 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3819 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3820 &halInBuffer);
3821 if (result != OK) return result;
3822 halOutBuffer = halInBuffer;
3823 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3824 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003825 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003826 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003827 // Only one effect chain can be present in direct output thread and it uses
3828 // the sink buffer as input
3829 if (mType != DIRECT) {
3830 size_t numSamples = mNormalFrameCount
3831 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3832 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003833 const status_t allocateStatus =
3834 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003835 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003836 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003837 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003838
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003839 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003840 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3841 buffer, session);
3842 }
3843 }
3844 }
3845
3846 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003847 // Attach all tracks with same session ID to this chain.
3848 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003849 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003850 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003851 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3852 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003853 track->setMainBuffer(buffer);
3854 chain->incTrackCnt();
3855 }
3856 }
3857
3858 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003859 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003860 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003861 ALOGV("addEffectChain_l() activating track %p on session %d",
3862 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003863 chain->incActiveTrackCnt();
3864 }
3865 }
3866 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003867
Eric Laurentaaa44472014-09-12 17:41:50 -07003868 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003869 chain->setInBuffer(halInBuffer);
3870 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003871 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3872 // chains list in order to be processed last as it contains output device effects.
3873 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3874 // processing effects specific to an output stream before effects applied to all streams
3875 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003876 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3877 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003878 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003879 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003880 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003881 // Effect chain for other sessions are inserted at beginning of effect
3882 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003883 // sessions is not important.
3884 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003885 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3886 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003887 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003888 size_t size = mEffectChains.size();
3889 size_t i = 0;
3890 for (i = 0; i < size; i++) {
3891 if (mEffectChains[i]->sessionId() < session) {
3892 break;
3893 }
3894 }
3895 mEffectChains.insertAt(chain, i);
3896 checkSuspendOnAddEffectChain_l(chain);
3897
3898 return NO_ERROR;
3899}
3900
Andy Hungee58e4a2023-07-07 13:47:37 -07003901size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003902{
Glenn Kastend848eb42016-03-08 13:42:11 -08003903 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003904
3905 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3906
3907 for (size_t i = 0; i < mEffectChains.size(); i++) {
3908 if (chain == mEffectChains[i]) {
3909 mEffectChains.removeAt(i);
3910 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003911 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003912 if (session == track->sessionId()) {
3913 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3914 chain.get(), session);
3915 chain->decActiveTrackCnt();
3916 }
3917 }
3918
3919 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003920 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003921 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003922 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003923 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003924 chain->decTrackCnt();
3925 }
3926 }
3927 break;
3928 }
3929 }
3930 return mEffectChains.size();
3931}
3932
Andy Hungee58e4a2023-07-07 13:47:37 -07003933status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003934 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003935{
Andy Hung972bec12023-08-31 16:13:39 -07003936 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003937 return attachAuxEffect_l(track, EffectId);
3938}
3939
Andy Hungee58e4a2023-07-07 13:47:37 -07003940status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003941 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003942{
3943 status_t status = NO_ERROR;
3944
3945 if (EffectId == 0) {
3946 track->setAuxBuffer(0, NULL);
3947 } else {
3948 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003949 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003950 if (effect != 0) {
3951 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3952 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3953 } else {
3954 status = INVALID_OPERATION;
3955 }
3956 } else {
3957 status = BAD_VALUE;
3958 }
3959 }
3960 return status;
3961}
3962
Andy Hungee58e4a2023-07-07 13:47:37 -07003963void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003964{
3965 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003966 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003967 if (track->auxEffectId() == effectId) {
3968 attachAuxEffect_l(track, 0);
3969 }
3970 }
3971}
3972
Andy Hungee58e4a2023-07-07 13:47:37 -07003973bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003974NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003975{
Andy Hung78d8d952023-05-30 18:10:23 -07003976 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003977
Andy Hung077d62e2023-10-03 10:49:34 -07003978 if (mType == SPATIALIZER) {
3979 const pid_t tid = getTid();
3980 if (tid == -1) { // odd: we are here, we must be a running thread.
3981 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3982 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003983 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3984 if (priorityBoost > 0) {
3985 stream()->setHalThreadPriority(priorityBoost);
3986 }
Andy Hung077d62e2023-10-03 10:49:34 -07003987 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003988 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3989 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3990 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3991 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3992 // only on ARC.
3993 const pid_t tid = getTid();
3994 if (tid == -1) {
3995 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3996 } else {
3997 const status_t status = requestPriority(getpid(),
3998 tid,
3999 kPriorityPlaybackThreadArc,
4000 false /* isForApp */,
4001 true /* asynchronous */);
4002 if (status != OK) {
4003 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4004 status);
4005 } else {
4006 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4007 }
4008 }
Andy Hung077d62e2023-10-03 10:49:34 -07004009 }
4010
Andy Hung8d31fd22023-06-26 19:20:57 -07004011 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004012
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004013 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004014 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004015
4016 // MIXER
4017 nsecs_t lastWarning = 0;
4018
4019 // DUPLICATING
4020 // FIXME could this be made local to while loop?
4021 writeFrames = 0;
4022
4023 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004024 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004025
Andy Hungd3639922022-04-28 18:00:49 -07004026 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004027 sleepTimeShift = 0;
4028 }
4029
4030 CpuStats cpuStats;
4031 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4032
4033 acquireWakeLock();
4034
Glenn Kasteneef598c2017-04-03 14:41:13 -07004035 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4036 // thread associated with this PlaybackThread.
4037 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4038 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004039 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4040 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004041 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004042 const char *logString = NULL;
4043
rago1bb90822017-05-02 18:31:48 -07004044 // Estimated time for next buffer to be written to hal. This is used only on
4045 // suspended mode (for now) to help schedule the wait time until next iteration.
4046 nsecs_t timeLoopNextNs = 0;
4047
Eric Laurent664539d2013-09-23 18:24:31 -07004048 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004049
Andy Hung2dbffc22018-08-08 18:50:41 -07004050 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004051
Eric Laurentb3f315a2021-07-13 15:09:05 +02004052 sendCheckOutputStageEffectsEvent();
4053
Andy Hung446f4df2019-02-21 12:26:41 -08004054 // loopCount is used for statistics and diagnostics.
4055 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004056 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004057 // Log merge requests are performed during AudioFlinger binder transactions, but
4058 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004059 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004060
Eric Laurent81784c32012-11-19 14:55:58 -08004061 cpuStats.sample(myName);
4062
Andy Hung116bc262023-06-20 18:56:17 -07004063 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004064 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004065 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004066 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004067
Andy Hung2dbffc22018-08-08 18:50:41 -07004068 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4069 //
Andy Hungc5007f82023-08-29 14:26:09 -07004070 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004071 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004072 // Here, we try for the AF lock, but do not block on it as the latency
4073 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004074 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004075 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004076 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004077 status_t status = INVALID_OPERATION;
4078 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004079 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004080 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004081 && swPatches.size() > 0) {
4082 status = swPatches[0].getLatencyMs_l(&latencyMs);
4083 downstreamPatchHandle = swPatches[0].getPatchHandle();
4084 }
4085 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004086 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004087 lastDownstreamPatchHandle = downstreamPatchHandle;
4088 }
4089 if (status == OK) {
4090 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004091 // latency of 5 seconds).
4092 const double minLatency = 0., maxLatency = 5000.;
4093 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004094 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004095 } else {
4096 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004097 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004098 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004099 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004100 }
Andy Hung583043b2023-07-17 17:05:00 -07004101 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004102 }
4103 } else {
4104 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4105 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004106 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004107 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4108 }
4109 }
4110
Eric Laurentb3f315a2021-07-13 15:09:05 +02004111 if (mCheckOutputStageEffects.exchange(false)) {
4112 checkOutputStageEffects();
4113 }
4114
Vlad Popa7e81cea2023-01-19 16:34:16 +01004115 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004116 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004117
Andy Hungc5007f82023-08-29 14:26:09 -07004118 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004119
Eric Laurent021cf962014-05-13 10:18:14 -07004120 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004121 if (mCheckOutputStageEffects.load()) {
4122 continue;
4123 }
Eric Laurent10351942014-05-08 18:49:52 -07004124
Andy Hungc5007f82023-08-29 14:26:09 -07004125 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004126 if (logString != NULL) {
4127 mNBLogWriter->logTimestamp();
4128 mNBLogWriter->log(logString);
4129 logString = NULL;
4130 }
4131
Dean Wheatley12473e92021-03-18 23:00:55 +11004132 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004133
Eric Laurent81784c32012-11-19 14:55:58 -08004134 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004135 if (mSignalPending) {
4136 // A signal was raised while we were unlocked
4137 mSignalPending = false;
4138 } else if (waitingAsyncCallback_l()) {
4139 if (exitPending()) {
4140 break;
4141 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004142 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004143 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004144 releaseWakeLock_l();
4145 released = true;
4146 }
Andy Hung10cbff12017-02-21 17:30:14 -08004147
4148 const int64_t waitNs = computeWaitTimeNs_l();
4149 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004150 std::cv_status cvstatus =
4151 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4152 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004153 mSignalPending = true; // if timeout recheck everything
4154 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004156 if (released) {
4157 acquireWakeLock_l();
4158 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004159 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4160 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004161
4162 continue;
4163 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004164 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 isSuspended()) {
4166 // put audio hardware into standby after short delay
4167 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004168
4169 threadLoop_standby();
4170
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004171 // This is where we go into standby
4172 if (!mStandby) {
4173 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004174 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004175 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004176 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004177 }
Andy Hungd0979812019-02-21 15:51:44 -08004178 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004179 }
4180
Eric Tan39ec8d62018-07-24 09:49:29 -07004181 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004182 // we're about to wait, flush the binder command buffer
4183 IPCThreadState::self()->flushCommands();
4184
4185 clearOutputTracks();
4186
4187 if (exitPending()) {
4188 break;
4189 }
4190
4191 releaseWakeLock_l();
4192 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004193 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004194 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004195 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004196 acquireWakeLock_l();
4197
4198 mMixerStatus = MIXER_IDLE;
4199 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4200 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004201 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004202 checkSilentMode_l();
4203
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004204 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4205 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004206 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004207 sleepTimeShift = 0;
4208 }
4209
4210 continue;
4211 }
4212 }
Eric Laurent81784c32012-11-19 14:55:58 -08004213 // mMixerStatusIgnoringFastTracks is also updated internally
4214 mMixerStatus = prepareTracks_l(&tracksToRemove);
4215
Andy Hungab65b182023-09-06 19:41:47 -07004216 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004217
Vlad Popa7e81cea2023-01-19 16:34:16 +01004218 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004219
Andy Hungf302e812024-01-26 11:55:15 -08004220 // Acquire a local copy of active tracks with lock (release w/o lock).
4221 //
4222 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4223 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4224 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4225 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4226
4227 setHalLatencyMode_l();
4228
4229 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4230 // so this is done before we lock our effect chains.
4231 for (const auto& track : mActiveTracks) {
4232 track->updateTeePatches_l();
4233 }
4234
4235 // signal actual start of output stream when the render position reported by
4236 // the kernel starts moving.
4237 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4238 && (mKernelPositionOnStandby
4239 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4240 mHalStarted = true;
4241 mWaitHalStartCV.notify_all();
4242 }
4243
Eric Laurent81784c32012-11-19 14:55:58 -08004244 // prevent any changes in effect chain list and in each effect chain
4245 // during mixing and effect process as the audio buffers could be deleted
4246 // or modified if an effect is created or deleted
4247 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004248
4249 // Determine which session to pick up haptic data.
4250 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004251 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004252 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004253 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004254 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004255 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004256 if (effectChain != nullptr
4257 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004258 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004259 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004260 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004261 break;
4262 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004263 if (activeHapticSessionId == AUDIO_SESSION_NONE
4264 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004265 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004266 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004267 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004268 }
4269 }
4270 }
Andy Hungc5007f82023-08-29 14:26:09 -07004271 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004272
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 if (mBytesRemaining == 0) {
4274 mCurrentWriteLength = 0;
4275 if (mMixerStatus == MIXER_TRACKS_READY) {
4276 // threadLoop_mix() sets mCurrentWriteLength
4277 threadLoop_mix();
4278 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4279 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004280 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004281 // must be written to HAL
4282 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004283 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004284 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004285
4286 // Tally underrun frames as we are inserting 0s here.
4287 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004288 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004289 && !track->isStopped()
4290 && !track->isPaused()
4291 && !track->isTerminated()) {
4292 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4293 __func__, track->id(), track->getTrackStateAsString(),
4294 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004295 track->audioTrackServerProxy()->tallyUnderrunFrames(
4296 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004297 }
4298 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004299 }
4300 }
Andy Hung98ef9782014-03-04 14:46:50 -08004301 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004302 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004303 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004304 // or mSinkBuffer (if there are no effects and there is no data already copied to
4305 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004306 //
4307 // This is done pre-effects computation; if effects change to
4308 // support higher precision, this needs to move.
4309 //
4310 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004311 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004312 uint32_t mixerChannelCount = mEffectBufferValid ?
4313 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004314 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004315 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4316 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4317
David Li88ee0902022-06-22 10:01:21 +08004318 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4319 // do these processes after effects are applied.
4320 if (!mEffectBufferValid) {
4321 // mono blend occurs for mixer threads only (not direct or offloaded)
4322 // and is handled here if we're going directly to the sink.
4323 if (requireMonoBlend()) {
4324 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4325 mNormalFrameCount, true /*limit*/);
4326 }
Andy Hung2ddee192015-12-18 17:34:44 -08004327
David Li88ee0902022-06-22 10:01:21 +08004328 if (!hasFastMixer()) {
4329 // Balance must take effect after mono conversion.
4330 // We do it here if there is no FastMixer.
4331 // mBalance detects zero balance within the class for speed
4332 // (not needed here).
4333 mBalance.setBalance(mMasterBalance.load());
4334 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4335 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004336 }
4337
Andy Hung98ef9782014-03-04 14:46:50 -08004338 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004339 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004340
4341 // If we're going directly to the sink and there are haptic channels,
4342 // we should adjust channels as the sample data is partially interleaved
4343 // in this case.
4344 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4345 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4346 mChannelCount + mHapticChannelCount,
4347 audio_bytes_per_sample(format),
4348 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4349 }
Andy Hung98ef9782014-03-04 14:46:50 -08004350 }
4351
Eric Laurentbfb1b832013-01-07 09:53:42 -08004352 mBytesRemaining = mCurrentWriteLength;
4353 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004354 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4355 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4356 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4357 mBytesWritten += mBytesRemaining;
4358 mFramesWritten += framesRemaining;
4359 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004360 mBytesRemaining = 0;
4361 }
Eric Laurent81784c32012-11-19 14:55:58 -08004362
Eric Laurentbfb1b832013-01-07 09:53:42 -08004363 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004364 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004365 for (size_t i = 0; i < effectChains.size(); i ++) {
4366 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004367 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004368 if (activeHapticSessionId != AUDIO_SESSION_NONE
4369 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004370 // Haptic data is active in this case, copy it directly from
4371 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004372 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4373 audio_channel_count_from_out_mask(mMixerChannelMask) :
4374 mChannelCount;
4375 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4376 hapticSessionChannelCount = mChannelCount;
4377 }
4378
jiabin47affe52019-04-04 18:02:07 -07004379 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004380 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004381 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004382 memcpy_by_audio_format(
4383 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004384 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004385 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004386 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004387 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004388 }
Eric Laurent81784c32012-11-19 14:55:58 -08004389 }
4390 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004391 // Process effect chains for offloaded thread even if no audio
4392 // was read from audio track: process only updates effect state
4393 // and thus does have to be synchronized with audio writes but may have
4394 // to be called while waiting for async write callback
4395 if (mType == OFFLOAD) {
4396 for (size_t i = 0; i < effectChains.size(); i ++) {
4397 effectChains[i]->process_l();
4398 }
4399 }
Eric Laurent81784c32012-11-19 14:55:58 -08004400
Andy Hung98ef9782014-03-04 14:46:50 -08004401 // Only if the Effects buffer is enabled and there is data in the
4402 // Effects buffer (buffer valid), we need to
4403 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004404 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004405 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004406 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004407 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004408 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004409 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004410 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004411 }
4412
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004413 if (!hasFastMixer()) {
4414 // Balance must take effect after mono conversion.
4415 // We do it here if there is no FastMixer.
4416 // mBalance detects zero balance within the class for speed (not needed here).
4417 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004418 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004419 }
4420
Eric Laurentb62d0362021-10-26 17:40:18 +02004421 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4422 // mPostSpatializerBuffer if the haptics track is spatialized.
4423 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4424 // For other thread types, the haptics channels are already in mEffectBuffer.
4425 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4426 const size_t srcBufferSize = mNormalFrameCount *
4427 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4428 mEffectBufferFormat);
4429 const size_t dstBufferSize = mNormalFrameCount
4430 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4431
4432 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4433 mEffectBufferFormat,
4434 (uint8_t*)mEffectBuffer + srcBufferSize,
4435 mEffectBufferFormat,
4436 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004437 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004438 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4439 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4440 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4441 // Clamp PCM float values more than this distance from 0 to insulate
4442 // a HAL which doesn't handle NaN correctly.
4443 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4444 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4445 static_cast<const float*>(effectBuffer),
4446 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4447 } else {
4448 memcpy_by_audio_format(mSinkBuffer, mFormat,
4449 effectBuffer, mEffectBufferFormat, framesToCopy);
4450 }
jiabin245cdd92018-12-07 17:55:15 -08004451 // The sample data is partially interleaved when haptic channels exist,
4452 // we need to adjust channels here.
4453 if (mHapticChannelCount > 0) {
4454 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4455 mChannelCount + mHapticChannelCount,
4456 audio_bytes_per_sample(mFormat),
4457 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4458 }
Andy Hung98ef9782014-03-04 14:46:50 -08004459 }
4460
Eric Laurent81784c32012-11-19 14:55:58 -08004461 // enable changes in effect chain
4462 unlockEffectChains(effectChains);
4463
Vlad Popafce10862023-02-03 10:37:07 +01004464 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004465 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004466 metadataUpdate.playbackMetadataUpdate);
4467 }
4468
Eric Laurentbfb1b832013-01-07 09:53:42 -08004469 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004470 // mSleepTimeUs == 0 means we must write to audio hardware
4471 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004472 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004473 // writePeriodNs is updated >= 0 when ret > 0.
4474 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004476 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004477 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004478 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004479 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480 if (ret < 0) {
4481 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004482 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004483 mBytesWritten += ret;
4484 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004485 const int64_t frames = ret / mFrameSize;
4486 mFramesWritten += frames;
4487
4488 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4489 // process information relating to write time.
4490 if (audio_has_proportional_frames(mFormat)) {
4491 // we are in a continuous mixing cycle
4492 if (mMixerStatus == MIXER_TRACKS_READY &&
4493 loopCount == lastLoopCountWritten + 1) {
4494
4495 const double jitterMs =
4496 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4497 {frames, writePeriodNs},
4498 {0, 0} /* lastTimestamp */, mSampleRate);
4499 const double processMs =
4500 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4501
Andy Hung972bec12023-08-31 16:13:39 -07004502 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004503 mIoJitterMs.add(jitterMs);
4504 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004505
4506 if (mPipeSink.get() != nullptr) {
4507 // Using the Monopipe availableToWrite, we estimate the current
4508 // buffer size.
4509 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4510 const ssize_t
4511 availableToWrite = mPipeSink->availableToWrite();
4512 const size_t pipeFrames = monoPipe->maxFrames();
4513 const size_t
4514 remainingFrames = pipeFrames - max(availableToWrite, 0);
4515 mMonopipePipeDepthStats.add(remainingFrames);
4516 }
Andy Hung446f4df2019-02-21 12:26:41 -08004517 }
4518
4519 // write blocked detection
4520 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004521 if ((mType == MIXER || mType == SPATIALIZER)
4522 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004523 mNumDelayedWrites++;
4524 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4525 ATRACE_NAME("underrun");
4526 ALOGW("write blocked for %lld msecs, "
4527 "%d delayed writes, thread %d",
4528 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4529 mNumDelayedWrites, mId);
4530 lastWarning = lastIoEndNs;
4531 }
4532 }
4533 }
4534 // update timing info.
4535 mLastIoBeginNs = lastIoBeginNs;
4536 mLastIoEndNs = lastIoEndNs;
4537 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004538 }
4539 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4540 (mMixerStatus == MIXER_DRAIN_ALL)) {
4541 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004542 }
Andy Hungd3639922022-04-28 18:00:49 -07004543 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004544
4545 if (mThreadThrottle
4546 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004547 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004548 // Limit MixerThread data processing to no more than twice the
4549 // expected processing rate.
4550 //
4551 // This helps prevent underruns with NuPlayer and other applications
4552 // which may set up buffers that are close to the minimum size, or use
4553 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4554 //
4555 // The throttle smooths out sudden large data drains from the device,
4556 // e.g. when it comes out of standby, which often causes problems with
4557 // (1) mixer threads without a fast mixer (which has its own warm-up)
4558 // (2) minimum buffer sized tracks (even if the track is full,
4559 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004560 //
4561 // Total time spent in last processing cycle equals time spent in
4562 // 1. threadLoop_write, as well as time spent in
4563 // 2. threadLoop_mix (significant for heavy mixing, especially
4564 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004565
Andy Hung446f4df2019-02-21 12:26:41 -08004566 // it's OK if deltaMs is an overestimate.
4567
4568 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004569
Ivan Lozanoea04d392017-11-07 14:37:07 -08004570 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004571 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004572 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004573
Andy Hung08fb1742015-05-31 23:22:10 -07004574 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004575 // notify of throttle start on verbose log
4576 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4577 "mixer(%p) throttle begin:"
4578 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004579 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004580 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004581 // Throttle must be attributed to the previous mixer loop's write time
4582 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004583 // This also ensures proper timing statistics.
4584 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004585 } else {
4586 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4587 if (diff > 0) {
4588 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004589 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004590 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004591 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004592 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004593 outDeviceTypes_l(),
4594 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004595 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004596 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4597 }
Andy Hung08fb1742015-05-31 23:22:10 -07004598 }
4599 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004600 }
Eric Laurent81784c32012-11-19 14:55:58 -08004601
Eric Laurentbfb1b832013-01-07 09:53:42 -08004602 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004603 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004604 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004605 // suspended requires accurate metering of sleep time.
4606 if (isSuspended()) {
4607 // advance by expected sleepTime
4608 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4609 const nsecs_t nowNs = systemTime();
4610
4611 // compute expected next time vs current time.
4612 // (negative deltas are treated as delays).
4613 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4614 if (deltaNs < -kMaxNextBufferDelayNs) {
4615 // Delays longer than the max allowed trigger a reset.
4616 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4617 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4618 timeLoopNextNs = nowNs + deltaNs;
4619 } else if (deltaNs < 0) {
4620 // Delays within the max delay allowed: zero the delta/sleepTime
4621 // to help the system catch up in the next iteration(s)
4622 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4623 deltaNs = 0;
4624 }
4625 // update sleep time (which is >= 0)
4626 mSleepTimeUs = deltaNs / 1000;
4627 }
Eric Laurente93cc032016-05-05 10:15:10 -07004628 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004629 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004630 }
Glenn Kastene7754022014-10-31 12:11:26 -07004631 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004632 }
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
4634
4635 // Finally let go of removed track(s), without the lock held
4636 // since we can't guarantee the destructors won't acquire that
4637 // same lock. This will also mutate and push a new fast mixer state.
4638 threadLoop_removeTracks(tracksToRemove);
4639 tracksToRemove.clear();
4640
4641 // FIXME I don't understand the need for this here;
4642 // it was in the original code but maybe the
4643 // assignment in saveOutputTracks() makes this unnecessary?
4644 clearOutputTracks();
4645
4646 // Effect chains will be actually deleted here if they were removed from
4647 // mEffectChains list during mixing or effects processing
4648 effectChains.clear();
4649
4650 // FIXME Note that the above .clear() is no longer necessary since effectChains
4651 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004652
4653 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004654 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004655 mThreadloopExecutor.process(); // process any remaining deferred actions.
4656 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004657
Eric Laurentbfb1b832013-01-07 09:53:42 -08004658 threadLoop_exit();
4659
Eric Laurentcf817a22014-08-04 20:36:31 -07004660 if (!mStandby) {
4661 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004662 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004663 }
4664
4665 releaseWakeLock();
4666
4667 ALOGV("Thread %p type %d exiting", this, mType);
4668 return false;
4669}
4670
Andy Hungee58e4a2023-07-07 13:47:37 -07004671void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004672{
Dean Wheatley12473e92021-03-18 23:00:55 +11004673 if (mStandby) {
4674 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4675 return;
4676 } else if (mHwPaused) {
4677 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4678 return;
4679 }
4680
4681 // Gather the framesReleased counters for all active tracks,
4682 // and associate with the sink frames written out. We need
4683 // this to convert the sink timestamp to the track timestamp.
4684 bool kernelLocationUpdate = false;
4685 ExtendedTimestamp timestamp; // use private copy to fetch
4686
4687 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4688 // HAL may be draining some small duration buffered data for fade out.
4689 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4690 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4691 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4692 mSampleRate);
4693
Andy Hungab65b182023-09-06 19:41:47 -07004694 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004695 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4696 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4697 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4698 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4699 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4700 = correctedTimestamp.mFrames;
4701 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4702 = correctedTimestamp.mTimeNs;
4703 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4704 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4705 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4706
4707 // Note: Downstream latency only added if timestamp correction enabled.
4708 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4709 const int64_t newPosition =
4710 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4711 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4712 // prevent retrograde
4713 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4714 newPosition,
4715 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4716 - mSuspendedFrames));
4717 }
4718 }
4719
4720 // We always fetch the timestamp here because often the downstream
4721 // sink will block while writing.
4722
4723 // We keep track of the last valid kernel position in case we are in underrun
4724 // and the normal mixer period is the same as the fast mixer period, or there
4725 // is some error from the HAL.
4726 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4727 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4728 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4729 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4730 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4731
4732 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4733 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4734 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4735 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4736 }
4737
4738 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4739 kernelLocationUpdate = true;
4740 } else {
4741 ALOGVV("getTimestamp error - no valid kernel position");
4742 }
4743
4744 // copy over kernel info
4745 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4746 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4747 + mSuspendedFrames; // add frames discarded when suspended
4748 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4749 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4750 } else {
4751 mTimestampVerifier.error();
4752 }
4753
4754 // mFramesWritten for non-offloaded tracks are contiguous
4755 // even after standby() is called. This is useful for the track frame
4756 // to sink frame mapping.
4757 bool serverLocationUpdate = false;
4758 if (mFramesWritten != mLastFramesWritten) {
4759 serverLocationUpdate = true;
4760 mLastFramesWritten = mFramesWritten;
4761 }
4762 // Only update timestamps if there is a meaningful change.
4763 // Either the kernel timestamp must be valid or we have written something.
4764 if (kernelLocationUpdate || serverLocationUpdate) {
4765 if (serverLocationUpdate) {
4766 // use the time before we called the HAL write - it is a bit more accurate
4767 // to when the server last read data than the current time here.
4768 //
4769 // If we haven't written anything, mLastIoBeginNs will be -1
4770 // and we use systemTime().
4771 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4772 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004773 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004774 }
4775
Andy Hung8d31fd22023-06-26 19:20:57 -07004776 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004777 if (!t->isFastTrack()) {
4778 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004779 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004780 mFramesWritten,
4781 mSampleRate,
4782 mTimestamp);
4783 }
4784 }
4785 }
4786
4787 if (audio_has_proportional_frames(mFormat)) {
4788 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4789 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4790 mLatencyMs.add(latencyMs);
4791 }
4792 }
4793#if 0
4794 // logFormat example
4795 if (z % 100 == 0) {
4796 timespec ts;
4797 clock_gettime(CLOCK_MONOTONIC, &ts);
4798 LOGT("This is an integer %d, this is a float %f, this is my "
4799 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4800 LOGT("A deceptive null-terminated string %\0");
4801 }
4802 ++z;
4803#endif
4804}
4805
Andy Hungc5007f82023-08-29 14:26:09 -07004806// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004807void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004808NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004809{
Andy Hung6c498e92023-12-05 17:28:17 -08004810 if (tracksToRemove.empty()) return;
4811
4812 // Block all incoming TrackHandle requests until we are finished with the release.
4813 setThreadBusy_l(true);
4814
Andy Hungfe726a62018-09-27 15:17:25 -07004815 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004816 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004817 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004818 if (chain != 0) {
4819 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4820 __func__, track->id(), chain.get(), track->sessionId());
4821 chain->decActiveTrackCnt();
4822 }
Andy Hung6c498e92023-12-05 17:28:17 -08004823
Andy Hungfe726a62018-09-27 15:17:25 -07004824 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004825 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004826 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004827 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004828 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004829 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004830 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831 }
Andy Hung6c498e92023-12-05 17:28:17 -08004832 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004833 }
jiabineb3bda02020-06-30 14:07:03 -07004834 if (mHapticChannelCount > 0 &&
4835 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004836 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004837 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004838 // Unlock due to VibratorService will lock for this call and will
4839 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004840 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004841 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004842
4843 // When the track is stop, set the haptic intensity as MUTE
4844 // for the HapticGenerator effect.
4845 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004846 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004847 }
jiabin245cdd92018-12-07 17:55:15 -08004848 }
Andy Hung6c498e92023-12-05 17:28:17 -08004849
4850 // Under lock, the track is removed from the active tracks list.
4851 //
4852 // Once the track is no longer active, the TrackHandle may directly
4853 // modify it as the threadLoop() is no longer responsible for its maintenance.
4854 // Do not modify the track from threadLoop after the mutex is unlocked
4855 // if it is not active.
4856 mActiveTracks.remove(track);
4857
4858 if (track->isTerminated()) {
4859 // remove from our tracks vector
4860 removeTrack_l(track);
4861 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004862 }
Andy Hung6c498e92023-12-05 17:28:17 -08004863
4864 // Allow incoming TrackHandle requests. We still hold the mutex,
4865 // so pending TrackHandle requests will occur after we unlock it.
4866 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867}
Eric Laurent81784c32012-11-19 14:55:58 -08004868
Andy Hungee58e4a2023-07-07 13:47:37 -07004869status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004870{
4871 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004872 ExtendedTimestamp ets;
4873 status_t status = mNormalSink->getTimestamp(ets);
4874 if (status == NO_ERROR) {
4875 status = ets.getBestTimestamp(&timestamp);
4876 }
4877 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004878 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004879 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004880 collectTimestamps_l();
4881 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4882 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004883 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004884 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4885 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4886 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4887 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4888 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004889 }
4890 return INVALID_OPERATION;
4891}
Eric Laurent1c333e22014-05-20 10:48:17 -07004892
Eric Laurenteab90452019-06-24 15:17:46 -07004893// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4894// still applied by the mixer.
4895// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4896// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4897// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004898status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004899{
4900 status_t result = NO_ERROR;
4901 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4902 if (*volume != mLeftVolFloat) {
4903 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004904 // HAL can return INVALID_OPERATION if operation is not supported.
4905 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004906 "Error when setting output stream volume: %d", result);
4907 if (result == NO_ERROR) {
4908 mLeftVolFloat = *volume;
4909 }
4910 }
4911 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4912 // remove stream volume contribution from software volume.
4913 if (mLeftVolFloat == *volume) {
4914 *volume = 1.0f;
4915 }
4916 }
4917 return result;
4918}
4919
Andy Hungee58e4a2023-07-07 13:47:37 -07004920status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004921 audio_patch_handle_t *handle)
4922{
Andy Hungf60abce2016-08-26 11:37:54 -07004923 status_t status;
4924 if (property_get_bool("af.patch_park", false /* default_value */)) {
4925 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4926 // or if HAL does not properly lock against access.
4927 AutoPark<FastMixer> park(mFastMixer);
4928 status = PlaybackThread::createAudioPatch_l(patch, handle);
4929 } else {
4930 status = PlaybackThread::createAudioPatch_l(patch, handle);
4931 }
Eric Laurentb0463942022-12-20 16:31:10 +01004932
4933 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004934 return status;
4935}
4936
Andy Hungee58e4a2023-07-07 13:47:37 -07004937status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 audio_patch_handle_t *handle)
4939{
4940 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004941
4942 // store new device and send to effects
4943 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004944 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004945 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004946 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4947 && !mOutput->audioHwDev->supportsAudioPatches(),
4948 "Enumerated device type(%#x) must not be used "
4949 "as it does not support audio patches",
4950 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004951 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004952 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4953 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004954 }
4955
François Gaffie0c280aa2018-07-25 10:02:15 +02004956 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004957#ifdef ADD_BATTERY_DATA
4958 // when changing the audio output device, call addBatteryData to notify
4959 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004960 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004961 uint32_t params = 0;
4962 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004963 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004964 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004965 }
4966
Eric Laurent054d9d32015-04-24 08:48:48 -07004967 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004968 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004969 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4970 }
4971
4972 if (params != 0) {
4973 addBatteryData(params);
4974 }
4975 }
4976#endif
4977
4978 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004979 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004980 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004981
jiabinc52b1ff2019-10-31 17:20:42 -07004982 // mPatch.num_sinks is not set when the thread is created so that
4983 // the first patch creation triggers an ioConfigChanged callback
4984 bool configChanged = (mPatch.num_sinks == 0) ||
4985 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004986 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004987 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004988 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004989
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004990 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004991 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4992 status = hwDevice->createAudioPatch(patch->num_sources,
4993 patch->sources,
4994 patch->num_sinks,
4995 patch->sinks,
4996 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004997 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004998 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004999 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005000 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005001 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005002
5003 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005004 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005005 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005006 // also dispatch to active AudioTracks for MediaMetrics
5007 for (const auto &track : mActiveTracks) {
5008 track->logEndInterval();
5009 track->logBeginInterval(patchSinksAsString);
5010 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005011
Eric Laurente8726fe2015-06-26 09:39:24 -07005012 if (configChanged) {
5013 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5014 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005015 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005016 mActiveTracks.setHasChanged();
5017
Eric Laurent1c333e22014-05-20 10:48:17 -07005018 return status;
5019}
5020
Andy Hungee58e4a2023-07-07 13:47:37 -07005021status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005022{
Andy Hungf60abce2016-08-26 11:37:54 -07005023 status_t status;
5024 if (property_get_bool("af.patch_park", false /* default_value */)) {
5025 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5026 // or if HAL does not properly lock against access.
5027 AutoPark<FastMixer> park(mFastMixer);
5028 status = PlaybackThread::releaseAudioPatch_l(handle);
5029 } else {
5030 status = PlaybackThread::releaseAudioPatch_l(handle);
5031 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005032 return status;
5033}
5034
Andy Hungee58e4a2023-07-07 13:47:37 -07005035status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005036{
5037 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005038
jiabinc52b1ff2019-10-31 17:20:42 -07005039 mPatch = audio_patch{};
5040 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005041
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005042 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005043 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5044 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005045 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005046 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005047 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005048 // Force meteadata update after a route change
5049 mActiveTracks.setHasChanged();
5050
Eric Laurent1c333e22014-05-20 10:48:17 -07005051 return status;
5052}
5053
Andy Hungee58e4a2023-07-07 13:47:37 -07005054void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005055{
Andy Hung972bec12023-08-31 16:13:39 -07005056 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005057 mTracks.add(track);
5058}
5059
Andy Hungee58e4a2023-07-07 13:47:37 -07005060void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005061{
Andy Hung972bec12023-08-31 16:13:39 -07005062 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005063 destroyTrack_l(track);
5064}
5065
Andy Hungee58e4a2023-07-07 13:47:37 -07005066void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005067{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005068 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005069 config->role = AUDIO_PORT_ROLE_SOURCE;
5070 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5071 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005072 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5073 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5074 config->flags.output = mOutput->flags;
5075 }
Eric Laurent83b88082014-06-20 18:31:16 -07005076}
5077
Eric Laurent81784c32012-11-19 14:55:58 -08005078// ----------------------------------------------------------------------------
5079
Andy Hungee58e4a2023-07-07 13:47:37 -07005080/* static */
5081sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005082 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005083 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005084 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005085}
5086
Andy Hung583043b2023-07-17 17:05:00 -07005087MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005088 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005089 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005090 // mAudioMixer below
5091 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005092 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005093 mFastMixerFutex(0),
5094 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005095 // mOutputSink below
5096 // mPipeSink below
5097 // mNormalSink below
5098{
jiabinc52b1ff2019-10-31 17:20:42 -07005099 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005100 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005101 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005102 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5103 mNormalFrameCount);
5104 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5105
Andy Hungfbfc3952015-01-15 13:33:51 -08005106 if (type == DUPLICATING) {
5107 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5108 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5109 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005110 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5111 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005112 return;
5113 }
Eric Laurent81784c32012-11-19 14:55:58 -08005114 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005115 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005116 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005117 const NBAIO_Format offers[1] = {Format_from_SR_C(
5118 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005119#if !LOG_NDEBUG
5120 ssize_t index =
5121#else
5122 (void)
5123#endif
5124 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005125 ALOG_ASSERT(index == 0);
5126
5127 // initialize fast mixer depending on configuration
5128 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005129 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005130 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005131 } else {
5132 switch (kUseFastMixer) {
5133 case FastMixer_Never:
5134 initFastMixer = false;
5135 break;
5136 case FastMixer_Always:
5137 initFastMixer = true;
5138 break;
5139 case FastMixer_Static:
5140 case FastMixer_Dynamic:
5141 initFastMixer = mFrameCount < mNormalFrameCount;
5142 break;
5143 }
5144 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5145 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5146 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005147 }
5148 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005149 audio_format_t fastMixerFormat;
5150 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5151 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5152 } else {
5153 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5154 }
5155 if (mFormat != fastMixerFormat) {
5156 // change our Sink format to accept our intermediate precision
5157 mFormat = fastMixerFormat;
5158 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005159 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005160 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5161 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5162 }
Eric Laurent81784c32012-11-19 14:55:58 -08005163
5164 // create a MonoPipe to connect our submix to FastMixer
5165 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005166
Andy Hung1258c1a2014-05-23 21:22:17 -07005167 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005168 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005169 format.mFormat = fastMixerFormat;
5170 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5171
Eric Laurent81784c32012-11-19 14:55:58 -08005172 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5173 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5174 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5175 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005176 const NBAIO_Format offersFast[1] = {format};
5177 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005178#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005179 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005180#else
5181 (void)
5182#endif
Andy Hung920f6572022-10-06 12:09:49 -07005183 monoPipe->negotiate(offersFast, std::size(offersFast),
5184 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005185 ALOG_ASSERT(index == 0);
5186 monoPipe->setAvgFrames((mScreenState & 1) ?
5187 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5188 mPipeSink = monoPipe;
5189
Eric Laurent81784c32012-11-19 14:55:58 -08005190 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005191 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005192 FastMixerStateQueue *sq = mFastMixer->sq();
5193#ifdef STATE_QUEUE_DUMP
5194 sq->setObserverDump(&mStateQueueObserverDump);
5195 sq->setMutatorDump(&mStateQueueMutatorDump);
5196#endif
5197 FastMixerState *state = sq->begin();
5198 FastTrack *fastTrack = &state->mFastTracks[0];
5199 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5200 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5201 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005202 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5203 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5204 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005205 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005206 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005207 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005208 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005209 fastTrack->mGeneration++;
5210 state->mFastTracksGen++;
5211 state->mTrackMask = 1;
5212 // fast mixer will use the HAL output sink
5213 state->mOutputSink = mOutputSink.get();
5214 state->mOutputSinkGen++;
5215 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005216 // specify sink channel mask when haptic channel mask present as it can not
5217 // be calculated directly from channel count
5218 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005219 ? AUDIO_CHANNEL_NONE
5220 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005221 state->mCommand = FastMixerState::COLD_IDLE;
5222 // already done in constructor initialization list
5223 //mFastMixerFutex = 0;
5224 state->mColdFutexAddr = &mFastMixerFutex;
5225 state->mColdGen++;
5226 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005227 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005228 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005229 sq->end();
5230 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5231
Eric Tan0513b5d2018-09-17 10:32:48 -07005232 NBLog::thread_info_t info;
5233 info.id = mId;
5234 info.type = NBLog::FASTMIXER;
5235 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5236
Eric Laurent81784c32012-11-19 14:55:58 -08005237 // start the fast mixer
5238 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5239 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005240 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005241 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005242
5243#ifdef AUDIO_WATCHDOG
5244 // create and start the watchdog
5245 mAudioWatchdog = new AudioWatchdog();
5246 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5247 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5248 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005249 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005250#endif
Andy Hung8946a282018-04-19 20:04:56 -07005251 } else {
5252#ifdef TEE_SINK
5253 // Only use the MixerThread tee if there is no FastMixer.
5254 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5255 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5256#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005257 }
5258
5259 switch (kUseFastMixer) {
5260 case FastMixer_Never:
5261 case FastMixer_Dynamic:
5262 mNormalSink = mOutputSink;
5263 break;
5264 case FastMixer_Always:
5265 mNormalSink = mPipeSink;
5266 break;
5267 case FastMixer_Static:
5268 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5269 break;
5270 }
Andy Hung922617c2024-06-25 17:07:58 -07005271 // setMasterBalance needs to be called after the FastMixer
5272 // (if any) is set up, in order to deliver the balance settings to it.
5273 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005274}
5275
Andy Hungee58e4a2023-07-07 13:47:37 -07005276MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005277{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005278 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005279 FastMixerStateQueue *sq = mFastMixer->sq();
5280 FastMixerState *state = sq->begin();
5281 if (state->mCommand == FastMixerState::COLD_IDLE) {
5282 int32_t old = android_atomic_inc(&mFastMixerFutex);
5283 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005284 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005285 }
5286 }
5287 state->mCommand = FastMixerState::EXIT;
5288 sq->end();
5289 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5290 mFastMixer->join();
5291 // Though the fast mixer thread has exited, it's state queue is still valid.
5292 // We'll use that extract the final state which contains one remaining fast track
5293 // corresponding to our sub-mix.
5294 state = sq->begin();
5295 ALOG_ASSERT(state->mTrackMask == 1);
5296 FastTrack *fastTrack = &state->mFastTracks[0];
5297 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5298 delete fastTrack->mBufferProvider;
5299 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005300 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005301#ifdef AUDIO_WATCHDOG
5302 if (mAudioWatchdog != 0) {
5303 mAudioWatchdog->requestExit();
5304 mAudioWatchdog->requestExitAndWait();
5305 mAudioWatchdog.clear();
5306 }
5307#endif
5308 }
Andy Hung583043b2023-07-17 17:05:00 -07005309 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005310 delete mAudioMixer;
5311}
5312
Andy Hungee58e4a2023-07-07 13:47:37 -07005313void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005314 PlaybackThread::onFirstRef();
5315
Andy Hung972bec12023-08-31 16:13:39 -07005316 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005317 if (mOutput != nullptr && mOutput->stream != nullptr) {
5318 status_t status = mOutput->stream->setLatencyModeCallback(this);
5319 if (status != INVALID_OPERATION) {
5320 updateHalSupportedLatencyModes_l();
5321 }
5322 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5323 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5324 mBluetoothLatencyModesEnabled.store(
5325 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5326 }
5327}
Eric Laurent81784c32012-11-19 14:55:58 -08005328
Andy Hungee58e4a2023-07-07 13:47:37 -07005329uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005330{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005331 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005332 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5333 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5334 }
5335 return latency;
5336}
5337
Andy Hungee58e4a2023-07-07 13:47:37 -07005338ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005339{
5340 // FIXME we should only do one push per cycle; confirm this is true
5341 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005342 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005343 FastMixerStateQueue *sq = mFastMixer->sq();
5344 FastMixerState *state = sq->begin();
5345 if (state->mCommand != FastMixerState::MIX_WRITE &&
5346 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5347 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005348
5349 // FIXME workaround for first HAL write being CPU bound on some devices
5350 ATRACE_BEGIN("write");
5351 mOutput->write((char *)mSinkBuffer, 0);
5352 ATRACE_END();
5353
Eric Laurent81784c32012-11-19 14:55:58 -08005354 int32_t old = android_atomic_inc(&mFastMixerFutex);
5355 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005356 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005357 }
5358#ifdef AUDIO_WATCHDOG
5359 if (mAudioWatchdog != 0) {
5360 mAudioWatchdog->resume();
5361 }
5362#endif
5363 }
5364 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005365#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005366 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005367 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005368#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005369 sq->end();
5370 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5371 if (kUseFastMixer == FastMixer_Dynamic) {
5372 mNormalSink = mPipeSink;
5373 }
5374 } else {
5375 sq->end(false /*didModify*/);
5376 }
5377 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005378 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005379}
5380
Andy Hungee58e4a2023-07-07 13:47:37 -07005381void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005382{
5383 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005384 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005385 FastMixerStateQueue *sq = mFastMixer->sq();
5386 FastMixerState *state = sq->begin();
5387 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005388 // Report any frames trapped in the Monopipe
5389 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5390 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5391 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5392 "monoPipeWritten:%lld monoPipeLeft:%lld",
5393 (long long)mFramesWritten, (long long)mSuspendedFrames,
5394 (long long)mPipeSink->framesWritten(), pipeFrames);
5395 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5396
Eric Laurent81784c32012-11-19 14:55:58 -08005397 state->mCommand = FastMixerState::COLD_IDLE;
5398 state->mColdFutexAddr = &mFastMixerFutex;
5399 state->mColdGen++;
5400 mFastMixerFutex = 0;
5401 sq->end();
5402 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5403 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5404 if (kUseFastMixer == FastMixer_Dynamic) {
5405 mNormalSink = mOutputSink;
5406 }
5407#ifdef AUDIO_WATCHDOG
5408 if (mAudioWatchdog != 0) {
5409 mAudioWatchdog->pause();
5410 }
5411#endif
5412 } else {
5413 sq->end(false /*didModify*/);
5414 }
5415 }
5416 PlaybackThread::threadLoop_standby();
5417}
5418
Andy Hungee58e4a2023-07-07 13:47:37 -07005419bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420{
5421 return false;
5422}
5423
Andy Hungee58e4a2023-07-07 13:47:37 -07005424bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005425{
5426 return !mStandby;
5427}
5428
Andy Hungee58e4a2023-07-07 13:47:37 -07005429bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430{
Andy Hung972bec12023-08-31 16:13:39 -07005431 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005432 return waitingAsyncCallback_l();
5433}
5434
Eric Laurent81784c32012-11-19 14:55:58 -08005435// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005436void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005437{
Andy Hung8d672e02023-09-15 18:19:28 -07005438 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5439 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005440 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005442 // discard any pending drain or write ack by incrementing sequence
5443 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5444 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005445 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005446 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5447 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005449 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005450 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005451}
5452
Andy Hungee58e4a2023-07-07 13:47:37 -07005453void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005454{
5455 ALOGV("signal playback thread");
5456 broadcast_l();
5457}
5458
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005459void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005460{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005461 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005462 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5463 invalidateTracks((audio_stream_type_t)i);
5464 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005465 if (isHardError) {
5466 mAfThreadCallback->onHardError(allTrackPortIds);
5467 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005468}
5469
Andy Hungee58e4a2023-07-07 13:47:37 -07005470void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005471{
Eric Laurent81784c32012-11-19 14:55:58 -08005472 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005473 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005474 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005475 // increase sleep time progressively when application underrun condition clears.
5476 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5477 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5478 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005479 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005480 sleepTimeShift--;
5481 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005482 mSleepTimeUs = 0;
5483 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005484 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005485
Eric Laurent81784c32012-11-19 14:55:58 -08005486}
5487
Andy Hungee58e4a2023-07-07 13:47:37 -07005488void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005489{
5490 // If no tracks are ready, sleep once for the duration of an output
5491 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005492 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005493 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005494 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5495 // Using the Monopipe availableToWrite, we estimate the
5496 // sleep time to retry for more data (before we underrun).
5497 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5498 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5499 const size_t pipeFrames = monoPipe->maxFrames();
5500 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5501 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5502 const size_t framesDelay = std::min(
5503 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5504 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5505 pipeFrames, framesLeft, framesDelay);
5506 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5507 } else {
5508 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5509 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5510 mSleepTimeUs = kMinThreadSleepTimeUs;
5511 }
5512 // reduce sleep time in case of consecutive application underruns to avoid
5513 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5514 // duration we would end up writing less data than needed by the audio HAL if
5515 // the condition persists.
5516 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5517 sleepTimeShift++;
5518 }
Eric Laurent81784c32012-11-19 14:55:58 -08005519 }
5520 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005521 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005522 }
5523 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005524 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5525 // before effects processing or output.
5526 if (mMixerBufferValid) {
5527 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005528 if (mType == SPATIALIZER) {
5529 memset(mSinkBuffer, 0, mSinkBufferSize);
5530 }
Andy Hung98ef9782014-03-04 14:46:50 -08005531 } else {
5532 memset(mSinkBuffer, 0, mSinkBufferSize);
5533 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005534 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005535 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5536 "anticipated start");
5537 }
5538 // TODO add standby time extension fct of effect tail
5539}
5540
Andy Hungc5007f82023-08-29 14:26:09 -07005541// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005542PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005543 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005544{
Andy Hungc0691382018-09-12 18:01:57 -07005545 // clean up deleted track ids in AudioMixer before allocating new tracks
5546 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5547 // for each trackId, destroy it in the AudioMixer
5548 if (mAudioMixer->exists(trackId)) {
5549 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005550 }
5551 });
Andy Hungc0691382018-09-12 18:01:57 -07005552 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005553
5554 mixer_state mixerStatus = MIXER_IDLE;
5555 // find out which tracks need to be processed
5556 size_t count = mActiveTracks.size();
5557 size_t mixedTracks = 0;
5558 size_t tracksWithEffect = 0;
5559 // counts only _active_ fast tracks
5560 size_t fastTracks = 0;
5561 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5562
5563 float masterVolume = mMasterVolume;
5564 bool masterMute = mMasterMute;
5565
5566 if (masterMute) {
5567 masterVolume = 0;
5568 }
5569 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005570 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005571 if (chain != 0) {
5572 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005573 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005574 masterVolume = (float)((v + (1 << 23)) >> 24);
5575 chain.clear();
5576 }
5577
5578 // prepare a new state to push
5579 FastMixerStateQueue *sq = NULL;
5580 FastMixerState *state = NULL;
5581 bool didModify = false;
5582 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005583 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005584 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005585 sq = mFastMixer->sq();
5586 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005587 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
5589
Andy Hung69aed5f2014-02-25 17:24:40 -08005590 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005591 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005592
Andy Hungbd3b2b02018-05-21 10:53:11 -07005593 // DeferredOperations handles statistics after setting mixerStatus.
5594 class DeferredOperations {
5595 public:
Andy Hungea840382020-05-05 21:50:17 -07005596 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5597 : mMixerStatus(mixerStatus)
5598 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005599
5600 // when leaving scope, tally frames properly.
5601 ~DeferredOperations() {
5602 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5603 // because that is when the underrun occurs.
5604 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005605 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005606 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005607 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005608 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005609 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005610 }
5611 }
Andy Hungea840382020-05-05 21:50:17 -07005612 // send the max underrun frames for this mixer period
5613 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005614 }
5615
5616 // tallyUnderrunFrames() is called to update the track counters
5617 // with the number of underrun frames for a particular mixer period.
5618 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005619 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005620 mUnderrunFrames.emplace_back(track, underrunFrames);
5621 }
5622
5623 private:
5624 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005625 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005626 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005627 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005628 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005629
jiabin245cdd92018-12-07 17:55:15 -08005630 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005631 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005632 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005633
5634 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005635 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005636
5637 // process fast tracks
5638 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005639 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5640 "%s(%d): FastTrack(%d) present without FastMixer",
5641 __func__, id(), track->id());
5642
jiabin245cdd92018-12-07 17:55:15 -08005643 if (track->getHapticPlaybackEnabled()) {
5644 noFastHapticTrack = false;
5645 }
Eric Laurent81784c32012-11-19 14:55:58 -08005646
5647 // It's theoretically possible (though unlikely) for a fast track to be created
5648 // and then removed within the same normal mix cycle. This is not a problem, as
5649 // the track never becomes active so it's fast mixer slot is never touched.
5650 // The converse, of removing an (active) track and then creating a new track
5651 // at the identical fast mixer slot within the same normal mix cycle,
5652 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005653 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005654 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005655 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5656 FastTrack *fastTrack = &state->mFastTracks[j];
5657
5658 // Determine whether the track is currently in underrun condition,
5659 // and whether it had a recent underrun.
5660 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5661 FastTrackUnderruns underruns = ftDump->mUnderruns;
5662 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005663 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005664 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005665 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005666 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005667 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005668 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005669 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005670 // don't count underruns that occur while stopping or pausing
5671 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005672 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005673 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5674 recentUnderruns > 0) {
5675 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005676 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005677 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005678 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005679 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005680
5681 // This is similar to the state machine for normal tracks,
5682 // with a few modifications for fast tracks.
5683 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005684 switch (track->state()) {
5685 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005686 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005687 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005688 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005689 }
5690 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005691 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005692 // ramp down is not yet implemented
5693 track->setPaused();
5694 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005695 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005696 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005697 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005698 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005699 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005700 if (recentFull > 0 || recentPartial > 0) {
5701 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005702 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005703 }
5704 if (recentUnderruns == 0) {
5705 // no recent underruns: stay active
5706 break;
5707 }
5708 // there has recently been an underrun of some kind
5709 if (track->sharedBuffer() == 0) {
5710 // were any of the recent underruns "empty" (no frames available)?
5711 if (recentEmpty == 0) {
5712 // no, then ignore the partial underruns as they are allowed indefinitely
5713 break;
5714 }
5715 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005716 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005717 break;
5718 }
5719 // indicate to client process that the track was disabled because of underrun;
5720 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005721 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005722 // remove from active list, but state remains ACTIVE [confusing but true]
5723 isActive = false;
5724 break;
5725 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005726 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005727 case IAfTrackBase::STOPPING_2:
5728 case IAfTrackBase::PAUSED:
5729 case IAfTrackBase::STOPPED:
5730 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005731 // Check for presentation complete if track is inactive
5732 // We have consumed all the buffers of this track.
5733 // This would be incomplete if we auto-paused on underrun
5734 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005735 uint32_t latency = 0;
5736 status_t result = mOutput->stream->getLatency(&latency);
5737 ALOGE_IF(result != OK,
5738 "Error when retrieving output stream latency: %d", result);
5739 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005740 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005741 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5742 // track stays in active list until presentation is complete
5743 break;
5744 }
5745 }
5746 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005747 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005748 }
5749 if (track->isStopped()) {
5750 // Can't reset directly, as fast mixer is still polling this track
5751 // track->reset();
5752 // So instead mark this track as needing to be reset after push with ack
5753 resetMask |= 1 << i;
5754 }
5755 isActive = false;
5756 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005757 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005758 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005759 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005760 }
5761
5762 if (isActive) {
5763 // was it previously inactive?
5764 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005765 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5766 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005767 fastTrack->mBufferProvider = eabp;
5768 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005769 fastTrack->mChannelMask = track->channelMask();
5770 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005771 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005772 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005773 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005774 fastTrack->mGeneration++;
5775 state->mTrackMask |= 1 << j;
5776 didModify = true;
5777 // no acknowledgement required for newly active tracks
5778 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005779 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005780 float volume;
Eric Laurent277a37e2024-07-29 18:37:52 +00005781 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5782 volume = 0.f;
Eric Laurenteab90452019-06-24 15:17:46 -07005783 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +00005784 volume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005785 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005786
Eric Laurenteab90452019-06-24 15:17:46 -07005787 handleVoipVolume_l(&volume);
5788
Eric Laurent81784c32012-11-19 14:55:58 -08005789 // cache the combined master volume and stream type volume for fast mixer; this
5790 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005791 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005792 proxy->framesReleased()).first;
5793 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005794 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005795 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005796 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5797 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent277a37e2024-07-29 18:37:52 +00005798
5799 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5800 /*muteState=*/{masterVolume == 0.f,
5801 mStreamTypes[track->streamType()].volume == 0.f,
5802 mStreamTypes[track->streamType()].mute,
5803 track->isPlaybackRestricted(),
5804 vlf == 0.f && vrf == 0.f,
5805 vh == 0.f});
5806
Vlad Popae2f5aef2022-07-25 16:00:20 +02005807 vlf *= volume;
5808 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005809
jiabin220eea12024-05-17 17:55:20 +00005810 if (track->getInternalMute()) {
5811 vlf = 0.f;
5812 vrf = 0.f;
5813 }
5814
jiabin76d94692022-12-15 21:51:21 +00005815 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005816 ++fastTracks;
5817 } else {
5818 // was it previously active?
5819 if (state->mTrackMask & (1 << j)) {
5820 fastTrack->mBufferProvider = NULL;
5821 fastTrack->mGeneration++;
5822 state->mTrackMask &= ~(1 << j);
5823 didModify = true;
5824 // If any fast tracks were removed, we must wait for acknowledgement
5825 // because we're about to decrement the last sp<> on those tracks.
5826 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5827 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005828 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5829 // AudioTrack may start (which may not be with a start() but with a write()
5830 // after underrun) and immediately paused or released. In that case the
5831 // FastTrack state hasn't had time to update.
5832 // TODO Remove the ALOGW when this theory is confirmed.
5833 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005834 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005835 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005836 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005837 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005838 }
5839 tracksToRemove->add(track);
5840 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005841 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005842 }
jiabin245cdd92018-12-07 17:55:15 -08005843 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5844 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5845 didModify = true;
5846 }
Eric Laurent81784c32012-11-19 14:55:58 -08005847 continue;
5848 }
5849
5850 { // local variable scope to avoid goto warning
5851
5852 audio_track_cblk_t* cblk = track->cblk();
5853
5854 // The first time a track is added we wait
5855 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005856 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005857
5858 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005859 // use the trackId as the AudioMixer name.
5860 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005861 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005862 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005863 track->channelMask(),
5864 track->format(),
5865 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005866 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005867 ALOGW("%s(): AudioMixer cannot create track(%d)"
5868 " mask %#x, format %#x, sessionId %d",
5869 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005870 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005871 tracksToRemove->add(track);
5872 track->invalidate(); // consider it dead.
5873 continue;
5874 }
5875 }
5876
Eric Laurent81784c32012-11-19 14:55:58 -08005877 // make sure that we have enough frames to mix one full buffer.
5878 // enforce this condition only once to enable draining the buffer in case the client
5879 // app does not call stop() and relies on underrun to stop:
5880 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5881 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005882 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005883 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5884 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005885
5886 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005887 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005888 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5889 // add frames already consumed but not yet released by the resampler
5890 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005891 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005892
Eric Laurent81784c32012-11-19 14:55:58 -08005893 uint32_t minFrames = 1;
5894 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5895 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005896 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005897 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005898
5899 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005900 if (ATRACE_ENABLED()) {
5901 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005902 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005903 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005904 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005905 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005906 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005907 !track->isPaused() && !track->isTerminated())
5908 {
Andy Hungc0691382018-09-12 18:01:57 -07005909 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005910
5911 mixedTracks++;
5912
Shunkai Yaof4847652024-01-12 00:25:20 +00005913 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005914 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005915 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005916 if (track->mainBuffer() != mSinkBuffer &&
5917 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005918 if (mEffectBufferEnabled) {
5919 mEffectBufferValid = true; // Later can set directly.
5920 }
Eric Laurent81784c32012-11-19 14:55:58 -08005921 chain = getEffectChain_l(track->sessionId());
5922 // Delegate volume control to effect in track effect chain if needed
5923 if (chain != 0) {
5924 tracksWithEffect++;
5925 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005926 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005927 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005928 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005929 }
5930 }
5931
5932
5933 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005934 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005935 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005936 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5937 if (track->state() == IAfTrackBase::RESUMING) {
5938 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005939 // If a new track is paused immediately after start, do not ramp on resume.
5940 if (cblk->mServer != 0) {
5941 param = AudioMixer::RAMP_VOLUME;
5942 }
Eric Laurent81784c32012-11-19 14:55:58 -08005943 }
Andy Hungc0691382018-09-12 18:01:57 -07005944 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005945 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005946 // FIXME should not make a decision based on mServer
5947 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005948 // If the track is stopped before the first frame was mixed,
5949 // do not apply ramp
5950 param = AudioMixer::RAMP_VOLUME;
5951 }
5952
5953 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005954 uint32_t vl, vr; // in U8.24 integer format
5955 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005956 // read original volumes with volume control
Eric Laurent277a37e2024-07-29 18:37:52 +00005957 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005958 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005959 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005960 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005961 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent277a37e2024-07-29 18:37:52 +00005962
5963 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5964 v = 0;
Eric Laurenteab90452019-06-24 15:17:46 -07005965 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005966
Eric Laurenteab90452019-06-24 15:17:46 -07005967 handleVoipVolume_l(&v);
5968
5969 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005970 vl = vr = 0;
5971 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005972 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005973 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005974 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005975 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5976 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005977 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005978 if (vlf > GAIN_FLOAT_UNITY) {
5979 ALOGV("Track left volume out of range: %.3g", vlf);
5980 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005981 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005982 if (vrf > GAIN_FLOAT_UNITY) {
5983 ALOGV("Track right volume out of range: %.3g", vrf);
5984 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005985 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005986
5987 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5988 /*muteState=*/{masterVolume == 0.f,
5989 mStreamTypes[track->streamType()].volume == 0.f,
5990 mStreamTypes[track->streamType()].mute,
5991 track->isPlaybackRestricted(),
5992 vlf == 0.f && vrf == 0.f,
5993 vh == 0.f});
5994
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005995 // now apply the master volume and stream type volume and shaper volume
5996 vlf *= v * vh;
5997 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005998 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005999 // then derive vl and vr as U8.24 versions for the effect chain
6000 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6001 vl = (uint32_t) (scaleto8_24 * vlf);
6002 vr = (uint32_t) (scaleto8_24 * vrf);
6003 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006004 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006005 // send level comes from shared memory and so may be corrupt
6006 if (sendLevel > MAX_GAIN_INT) {
6007 ALOGV("Track send level out of range: %04X", sendLevel);
6008 sendLevel = MAX_GAIN_INT;
6009 }
Andy Hung6be49402014-05-30 10:42:03 -07006010 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6011 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006012 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006013
jiabin220eea12024-05-17 17:55:20 +00006014 if (track->getInternalMute()) {
6015 vrf = 0.f;
6016 vlf = 0.f;
6017 }
6018
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006019 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006020
Eric Laurent81784c32012-11-19 14:55:58 -08006021 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006022 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006023 // Do not ramp volume if volume is controlled by effect
6024 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006025 // Update remaining floating point volume levels
6026 vlf = (float)vl / (1 << 24);
6027 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006028 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006029 } else {
6030 // force no volume ramp when volume controller was just disabled or removed
6031 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006032 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006033 param = AudioMixer::VOLUME;
6034 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006035 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006036 }
6037
Eric Laurent81784c32012-11-19 14:55:58 -08006038 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006039 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006040 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006041
Andy Hungc0691382018-09-12 18:01:57 -07006042 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6043 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6044 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006045 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006046 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006047 AudioMixer::TRACK,
6048 AudioMixer::FORMAT, (void *)track->format());
6049 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006050 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006051 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006052 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006053
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006054 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006055 mAudioMixer->setParameter(
6056 trackId,
6057 AudioMixer::TRACK,
6058 AudioMixer::MIXER_CHANNEL_MASK,
6059 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6060 } else {
6061 mAudioMixer->setParameter(
6062 trackId,
6063 AudioMixer::TRACK,
6064 AudioMixer::MIXER_CHANNEL_MASK,
6065 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6066 }
6067
Glenn Kastene3aa6592012-12-04 12:22:46 -08006068 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006069 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006070 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006071 if (reqSampleRate == 0) {
6072 reqSampleRate = mSampleRate;
6073 } else if (reqSampleRate > maxSampleRate) {
6074 reqSampleRate = maxSampleRate;
6075 }
Eric Laurent81784c32012-11-19 14:55:58 -08006076 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006077 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006078 AudioMixer::RESAMPLE,
6079 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006080 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006081
Andy Hung8edb8dc2015-03-26 19:13:55 -07006082 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006083 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006084 AudioMixer::TIMESTRETCH,
6085 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006086 // cast away constness for this generic API.
6087 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006088
Andy Hung69aed5f2014-02-25 17:24:40 -08006089 /*
6090 * Select the appropriate output buffer for the track.
6091 *
Andy Hung98ef9782014-03-04 14:46:50 -08006092 * Tracks with effects go into their own effects chain buffer
6093 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006094 *
6095 * Other tracks can use mMixerBuffer for higher precision
6096 * channel accumulation. If this buffer is enabled
6097 * (mMixerBufferEnabled true), then selected tracks will accumulate
6098 * into it.
6099 *
6100 */
6101 if (mMixerBufferEnabled
6102 && (track->mainBuffer() == mSinkBuffer
6103 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006104 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006105 mAudioMixer->setParameter(
6106 trackId,
6107 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006108 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006109 mAudioMixer->setParameter(
6110 trackId,
6111 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006112 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006113 } else {
6114 mAudioMixer->setParameter(
6115 trackId,
6116 AudioMixer::TRACK,
6117 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6118 mAudioMixer->setParameter(
6119 trackId,
6120 AudioMixer::TRACK,
6121 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6122 // TODO: override track->mainBuffer()?
6123 mMixerBufferValid = true;
6124 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006125 } else {
6126 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006127 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006128 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006129 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006130 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006131 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006132 AudioMixer::TRACK,
6133 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6134 }
Eric Laurent81784c32012-11-19 14:55:58 -08006135 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006136 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006137 AudioMixer::TRACK,
6138 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006139 mAudioMixer->setParameter(
6140 trackId,
6141 AudioMixer::TRACK,
6142 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006143 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006144 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006145 trackId,
6146 AudioMixer::TRACK,
6147 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006148 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006149 mAudioMixer->setParameter(
6150 trackId,
6151 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006152 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006153
6154 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006155 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006156
6157 // If one track is ready, set the mixer ready if:
6158 // - the mixer was not ready during previous round OR
6159 // - no other track is not ready
6160 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6161 mixerStatus != MIXER_TRACKS_ENABLED) {
6162 mixerStatus = MIXER_TRACKS_READY;
6163 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006164
6165 // Enable the next few lines to instrument a test for underrun log handling.
6166 // TODO: Remove when we have a better way of testing the underrun log.
6167#if 0
6168 static int i;
6169 if ((++i & 0xf) == 0) {
6170 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6171 }
6172#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006173 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006174 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006175 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006176 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6177 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006178 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006179 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006180 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006181
Eric Laurent81784c32012-11-19 14:55:58 -08006182 // clear effect chain input buffer if an active track underruns to avoid sending
6183 // previous audio buffer again to effects
6184 chain = getEffectChain_l(track->sessionId());
6185 if (chain != 0) {
6186 chain->clearInputBuffer();
6187 }
6188
Andy Hungc0691382018-09-12 18:01:57 -07006189 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006190 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6191 track->isStopped() || track->isPaused()) {
6192 // We have consumed all the buffers of this track.
6193 // Remove it from the list of active tracks.
6194 // TODO: use actual buffer filling status instead of latency when available from
6195 // audio HAL
6196 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006197 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006198 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6199 if (track->isStopped()) {
6200 track->reset();
6201 }
6202 tracksToRemove->add(track);
6203 }
6204 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006205 // No buffers for this track. Give it a few chances to
6206 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006207 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006208 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6209 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006210 tracksToRemove->add(track);
6211 // indicate to client process that the track was disabled because of underrun;
6212 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006213 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006214 // If one track is not ready, mark the mixer also not ready if:
6215 // - the mixer was ready during previous round OR
6216 // - no other track is ready
6217 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6218 mixerStatus != MIXER_TRACKS_READY) {
6219 mixerStatus = MIXER_TRACKS_ENABLED;
6220 }
6221 }
Andy Hungc0691382018-09-12 18:01:57 -07006222 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006223 }
6224
6225 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006226
6227 }
6228
jiabin245cdd92018-12-07 17:55:15 -08006229 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6230 // When there is no fast track playing haptic and FastMixer exists,
6231 // enabling the first FastTrack, which provides mixed data from normal
6232 // tracks, to play haptic data.
6233 FastTrack *fastTrack = &state->mFastTracks[0];
6234 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6235 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6236 didModify = true;
6237 }
6238 }
6239
Eric Laurent81784c32012-11-19 14:55:58 -08006240 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006241 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006242 if (didModify) {
6243 state->mFastTracksGen++;
6244 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6245 if (kUseFastMixer == FastMixer_Dynamic &&
6246 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6247 state->mCommand = FastMixerState::COLD_IDLE;
6248 state->mColdFutexAddr = &mFastMixerFutex;
6249 state->mColdGen++;
6250 mFastMixerFutex = 0;
6251 if (kUseFastMixer == FastMixer_Dynamic) {
6252 mNormalSink = mOutputSink;
6253 }
6254 // If we go into cold idle, need to wait for acknowledgement
6255 // so that fast mixer stops doing I/O.
6256 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6257 pauseAudioWatchdog = true;
6258 }
Eric Laurent81784c32012-11-19 14:55:58 -08006259 }
6260 if (sq != NULL) {
6261 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006262 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6263 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6264 // when bringing the output sink into standby.)
6265 //
6266 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6267 //
6268 // This occurs with BT suspend when we idle the FastMixer with
6269 // active tracks, which may be added or removed.
6270 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006271 }
6272#ifdef AUDIO_WATCHDOG
6273 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6274 mAudioWatchdog->pause();
6275 }
6276#endif
6277
6278 // Now perform the deferred reset on fast tracks that have stopped
6279 while (resetMask != 0) {
6280 size_t i = __builtin_ctz(resetMask);
6281 ALOG_ASSERT(i < count);
6282 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006283 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006284 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6285 track->reset();
6286 }
6287
Andy Hung80d03d22018-04-10 10:32:11 -07006288 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6289 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6290 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6291 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6292 // See also the implementation of destroyTrack_l().
6293 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006294 const int trackId = track->id();
6295 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6296 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006297 }
6298 }
6299
Eric Laurent81784c32012-11-19 14:55:58 -08006300 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006301 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006302
Eric Laurentb3f315a2021-07-13 15:09:05 +02006303 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6304 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006305 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006306 }
6307
6308 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006309 // as long as there are effects we should clear the effects buffer, to avoid
6310 // passing a non-clean buffer to the effect chain
6311 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006312 if (mType == SPATIALIZER) {
6313 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6314 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006315 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006316 // sink or mix buffer must be cleared if all tracks are connected to an
6317 // effect chain as in this case the mixer will not write to the sink or mix buffer
6318 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006319 // always clear sink buffer for spatializer output as the output of the spatializer
6320 // effect will be accumulated into it
6321 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6322 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006323 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006324 if (mMixerBufferValid) {
6325 memset(mMixerBuffer, 0, mMixerBufferSize);
6326 // TODO: In testing, mSinkBuffer below need not be cleared because
6327 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6328 // after mixing.
6329 //
6330 // To enforce this guarantee:
6331 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6332 // (mixedTracks == 0 && fastTracks > 0))
6333 // must imply MIXER_TRACKS_READY.
6334 // Later, we may clear buffers regardless, and skip much of this logic.
6335 }
Andy Hung98ef9782014-03-04 14:46:50 -08006336 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006337 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006338 }
6339
6340 // if any fast tracks, then status is ready
6341 mMixerStatusIgnoringFastTracks = mixerStatus;
6342 if (fastTracks > 0) {
6343 mixerStatus = MIXER_TRACKS_READY;
6344 }
6345 return mixerStatus;
6346}
6347
Andy Hungc5007f82023-08-29 14:26:09 -07006348// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006349uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006350{
6351 uint32_t trackCount = 0;
6352 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006353 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006354 trackCount++;
6355 }
6356 }
6357 return trackCount;
6358}
6359
Andy Hungee58e4a2023-07-07 13:47:37 -07006360bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006361{
Brian Lindahl65e90012022-07-27 18:01:07 +02006362 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6363 // could falsely detect that the frame position has stalled due to underrun because we haven't
6364 // given the Audio HAL enough time to update.
6365 const nsecs_t nowNs = systemTime();
6366 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6367 return mLatchedValue;
6368 }
6369 mPreviousNs = nowNs;
6370 mLatchedValue = false;
6371 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006372 uint64_t position = 0;
6373 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006374 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006375 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006376 if (position != mPreviousPosition) {
6377 mPreviousPosition = position;
6378 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006379 }
6380 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006381 return mLatchedValue;
6382}
6383
Andy Hungee58e4a2023-07-07 13:47:37 -07006384void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006385{
6386 mLatchedValue = true;
6387 mPreviousPosition = 0;
6388 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006389}
6390
Andy Hungc5007f82023-08-29 14:26:09 -07006391// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006392bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006393 audio_channel_mask_t channelMask, audio_format_t format,
6394 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006395{
Andy Hung1bc088a2018-02-09 15:57:31 -08006396 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6397 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006398 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006399 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006400 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006401 ALOGW("%s: invalid format: %#x", __func__, format);
6402 return false;
6403 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006404 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006405 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6406 return false;
6407 }
6408 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006409}
6410
Andy Hungc5007f82023-08-29 14:26:09 -07006411// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006412bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006413 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006414{
Eric Laurent81784c32012-11-19 14:55:58 -08006415 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006416 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006417
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006418 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006419
Eric Laurent10351942014-05-08 18:49:52 -07006420 AudioParameter param = AudioParameter(keyValuePair);
6421 int value;
6422 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6423 reconfig = true;
6424 }
6425 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006426 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006427 status = BAD_VALUE;
6428 } else {
6429 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006430 reconfig = true;
6431 }
Eric Laurent10351942014-05-08 18:49:52 -07006432 }
6433 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006434 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006435 status = BAD_VALUE;
6436 } else {
6437 // no need to save value, since it's constant
6438 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006439 }
Eric Laurent10351942014-05-08 18:49:52 -07006440 }
6441 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6442 // do not accept frame count changes if tracks are open as the track buffer
6443 // size depends on frame count and correct behavior would not be guaranteed
6444 // if frame count is changed after track creation
6445 if (!mTracks.isEmpty()) {
6446 status = INVALID_OPERATION;
6447 } else {
6448 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006449 }
Eric Laurent10351942014-05-08 18:49:52 -07006450 }
6451 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006452 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006453 }
Eric Laurent81784c32012-11-19 14:55:58 -08006454
Eric Laurent10351942014-05-08 18:49:52 -07006455 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006456 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006457 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006458 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6459 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006460 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006461 mThreadMetrics.logEndInterval();
6462 mThreadSnapshot.onEnd();
6463 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006464 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006465 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006466 }
Eric Laurent10351942014-05-08 18:49:52 -07006467 if (status == NO_ERROR && reconfig) {
6468 readOutputParameters_l();
6469 delete mAudioMixer;
6470 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006471 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006472 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006473 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006474 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006475 track->channelMask(),
6476 track->format(),
6477 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006478 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006479 "%s(): AudioMixer cannot create track(%d)"
6480 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006481 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006482 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006483 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006484 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006485 }
Eric Laurent81784c32012-11-19 14:55:58 -08006486 }
6487
Dean Wheatley68918102021-03-19 22:09:19 +11006488 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006489}
6490
6491
Andy Hungee58e4a2023-07-07 13:47:37 -07006492void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006493{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006494 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006495 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006496 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006497 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006498 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6499 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6500 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006501 if (hasFastMixer()) {
6502 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6503
6504 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6505 // while we are dumping it. It may be inconsistent, but it won't mutate!
6506 // This is a large object so we place it on the heap.
6507 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006508 const std::unique_ptr<FastMixerDumpState> copy =
6509 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006510 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006511
6512#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006513 // Similar for state queue
6514 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6515 observerCopy.dump(fd);
6516 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6517 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006518#endif
6519
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006520#ifdef AUDIO_WATCHDOG
6521 if (mAudioWatchdog != 0) {
6522 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6523 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6524 wdCopy.dump(fd);
6525 }
6526#endif
6527
6528 } else {
6529 dprintf(fd, " No FastMixer\n");
6530 }
Eric Laurent90cea102023-05-15 15:08:27 +02006531
6532 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6533 mBluetoothLatencyModesEnabled ? "" : "not ");
6534 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6535 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6536 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006537}
6538
Andy Hungee58e4a2023-07-07 13:47:37 -07006539uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006540{
6541 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6542}
6543
Andy Hungee58e4a2023-07-07 13:47:37 -07006544uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006545{
6546 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6547}
6548
Andy Hungee58e4a2023-07-07 13:47:37 -07006549void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006550{
6551 PlaybackThread::cacheParameters_l();
6552
6553 // FIXME: Relaxed timing because of a certain device that can't meet latency
6554 // Should be reduced to 2x after the vendor fixes the driver issue
6555 // increase threshold again due to low power audio mode. The way this warning
6556 // threshold is calculated and its usefulness should be reconsidered anyway.
6557 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6558}
6559
Andy Hungee58e4a2023-07-07 13:47:37 -07006560void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006561 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006562}
6563
Andy Hungee58e4a2023-07-07 13:47:37 -07006564void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006565 // Only handle latency mode if:
6566 // - mBluetoothLatencyModesEnabled is true
6567 // - the HAL supports latency modes
6568 // - the selected device is Bluetooth LE or A2DP
6569 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6570 return;
6571 }
6572 if (mOutDeviceTypeAddrs.size() != 1
6573 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6574 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6575 return;
6576 }
6577
6578 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6579 if (mSupportedLatencyModes.size() == 1) {
6580 // If the HAL only support one latency mode currently, confirm the choice
6581 latencyMode = mSupportedLatencyModes[0];
6582 } else if (mSupportedLatencyModes.size() > 1) {
6583 // Request low latency if:
6584 // - At least one active track is either:
6585 // - a fast track with gaming usage or
6586 // - a track with acessibility usage
6587 for (const auto& track : mActiveTracks) {
6588 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6589 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6590 latencyMode = AUDIO_LATENCY_MODE_LOW;
6591 break;
6592 }
6593 }
6594 }
6595
6596 if (latencyMode != mSetLatencyMode) {
6597 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6598 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6599 __func__, mId, toString(latencyMode).c_str(), status);
6600 if (status == NO_ERROR) {
6601 mSetLatencyMode = latencyMode;
6602 }
6603 }
6604}
6605
Andy Hungee58e4a2023-07-07 13:47:37 -07006606void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006607
6608 if (mOutput == nullptr || mOutput->stream == nullptr) {
6609 return;
6610 }
6611 std::vector<audio_latency_mode_t> latencyModes;
6612 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6613 if (status != NO_ERROR) {
6614 latencyModes.clear();
6615 }
6616 if (latencyModes != mSupportedLatencyModes) {
6617 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6618 __func__, mId, status, toString(latencyModes).c_str());
6619 mSupportedLatencyModes.swap(latencyModes);
6620 sendHalLatencyModesChangedEvent_l();
6621 }
6622}
6623
Andy Hungee58e4a2023-07-07 13:47:37 -07006624status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006625 std::vector<audio_latency_mode_t>* modes) {
6626 if (modes == nullptr) {
6627 return BAD_VALUE;
6628 }
Andy Hung972bec12023-08-31 16:13:39 -07006629 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006630 *modes = mSupportedLatencyModes;
6631 return NO_ERROR;
6632}
6633
Andy Hungee58e4a2023-07-07 13:47:37 -07006634void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006635 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006636 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006637 if (modes != mSupportedLatencyModes) {
6638 ALOGD("%s: thread(%d) supported latency modes: %s",
6639 __func__, mId, toString(modes).c_str());
6640 mSupportedLatencyModes.swap(modes);
6641 sendHalLatencyModesChangedEvent_l();
6642 }
6643}
6644
Andy Hungee58e4a2023-07-07 13:47:37 -07006645status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006646 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6647 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6648 return INVALID_OPERATION;
6649 }
6650 mBluetoothLatencyModesEnabled.store(enabled);
6651 return NO_ERROR;
6652}
6653
Eric Laurent81784c32012-11-19 14:55:58 -08006654// ----------------------------------------------------------------------------
6655
Andy Hungee58e4a2023-07-07 13:47:37 -07006656/* static */
6657sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006658 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006659 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6660 const audio_offload_info_t& offloadInfo) {
6661 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006662 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006663}
6664
Andy Hung583043b2023-07-17 17:05:00 -07006665DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006666 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6667 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006668 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006669 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006670{
Andy Hung583043b2023-07-17 17:05:00 -07006671 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006672}
6673
Andy Hungee58e4a2023-07-07 13:47:37 -07006674DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006675{
6676}
6677
Andy Hungee58e4a2023-07-07 13:47:37 -07006678void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006679{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006680 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006681 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6682 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6683}
6684
Andy Hungee58e4a2023-07-07 13:47:37 -07006685void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006686{
Andy Hung972bec12023-08-31 16:13:39 -07006687 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006688 if (mMasterBalance != balance) {
6689 mMasterBalance.store(balance);
6690 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6691 broadcast_l();
6692 }
6693}
6694
Andy Hungee58e4a2023-07-07 13:47:37 -07006695void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006696{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006697 float left, right;
6698
Andy Hung333ab962019-05-28 20:23:35 -07006699 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006700 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006701
Andy Hung398ffa22022-12-13 19:19:53 -08006702 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6703 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6704
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006705 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6706 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006707
6708 const int64_t volumeShaperFrames =
6709 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6710 const auto [shaperVolume, shaperActive] =
6711 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006712 mVolumeShaperActive = shaperActive;
6713
Vlad Popae2f5aef2022-07-25 16:00:20 +02006714 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6715 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6716 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6717
6718 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6719
Eric Laurent277a37e2024-07-29 18:37:52 +00006720 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6721 left = right = 0;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006722 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +00006723 float typeVolume = mStreamTypes[track->streamType()].volume;
6724 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725
Eric Laurent277a37e2024-07-29 18:37:52 +00006726 if (left > GAIN_FLOAT_UNITY) {
6727 left = GAIN_FLOAT_UNITY;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006728 }
Eric Laurent277a37e2024-07-29 18:37:52 +00006729 if (right > GAIN_FLOAT_UNITY) {
6730 right = GAIN_FLOAT_UNITY;
6731 }
6732 left *= v;
6733 right *= v;
6734 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6735 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6736 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6737 right *= mMasterBalanceRight;
6738 }
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006739 }
Vlad Popae8d99472022-06-30 16:02:48 +02006740
Eric Laurent277a37e2024-07-29 18:37:52 +00006741 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6742 /*muteState=*/{mMasterMute,
6743 mStreamTypes[track->streamType()].volume == 0.f,
6744 mStreamTypes[track->streamType()].mute,
6745 track->isPlaybackRestricted(),
6746 clientVolumeMute,
6747 shaperVolume == 0.f});
6748
Eric Laurentbfb1b832013-01-07 09:53:42 -08006749 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006750 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006751 if (left != mLeftVolFloat || right != mRightVolFloat) {
6752 mLeftVolFloat = left;
6753 mRightVolFloat = right;
6754
Eric Laurentbfb1b832013-01-07 09:53:42 -08006755 // Delegate volume control to effect in track effect chain if needed
6756 // only one effect chain can be present on DirectOutputThread, so if
6757 // there is one, the track is connected to it
6758 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006759 // if effect chain exists, volume is handled by it.
6760 // Convert volumes from float to 8.24
6761 uint32_t vl = (uint32_t)(left * (1 << 24));
6762 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006763 // Direct/Offload effect chains set output volume in setVolume().
6764 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006765 } else {
6766 // otherwise we directly set the volume.
6767 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006768 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006769 }
6770 }
6771}
6772
Andy Hungee58e4a2023-07-07 13:47:37 -07006773void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006774{
Andy Hung8d31fd22023-06-26 19:20:57 -07006775 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6776 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006777
Eric Laurent0f0631e2015-07-06 18:01:25 -07006778 if (previousTrack != 0 && latestTrack != 0) {
6779 if (mType == DIRECT) {
6780 if (previousTrack.get() != latestTrack.get()) {
6781 mFlushPending = true;
6782 }
6783 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006784 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6785 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006786 mFlushPending = true;
6787 }
6788 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006789 } else if (previousTrack == 0) {
6790 // there could be an old track added back during track transition for direct
6791 // output, so always issues flush to flush data of the previous track if it
6792 // was already destroyed with HAL paused, then flush can resume the playback
6793 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006794 }
6795 PlaybackThread::onAddNewTrack_l();
6796}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006797
Andy Hungee58e4a2023-07-07 13:47:37 -07006798PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006799 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006800)
6801{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006802 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006803 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006804 bool doHwPause = false;
6805 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006806
6807 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006808 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006809 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006810 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006811 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006812 continue;
6813 }
6814
Andy Hung8d31fd22023-06-26 19:20:57 -07006815 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006816#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006817 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006818#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006819 // Only consider last track started for volume and mixer state control.
6820 // In theory an older track could underrun and restart after the new one starts
6821 // but as we only care about the transition phase between two tracks on a
6822 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006823 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006824 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006825
Kuowei Li23666472021-01-20 10:23:25 +08006826 if (track->isPausePending()) {
6827 track->pauseAck();
6828 // It is possible a track might have been flushed or stopped.
6829 // Other operations such as flush pending might occur on the next prepare.
6830 if (track->isPausing()) {
6831 track->setPaused();
6832 }
6833 // Always perform pause, as an immediate flush will change
6834 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006835 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006836 doHwPause = true;
6837 mHwPaused = true;
6838 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006839 } else if (track->isFlushPending()) {
6840 track->flushAck();
6841 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006842 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006843 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006844 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006845 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006846 if (last) {
6847 mLeftVolFloat = mRightVolFloat = -1.0;
6848 if (mHwPaused) {
6849 doHwResume = true;
6850 mHwPaused = false;
6851 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006852 }
6853 }
6854
Eric Laurent81784c32012-11-19 14:55:58 -08006855 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006856 // for all its buffers to be filled before processing it.
6857 // Allow draining the buffer in case the client
6858 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006859 // hence the test on (track->retryCount() > 1).
6860 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006861 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6862 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006863 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006864
6865 // target retry count that we will use is based on the time we wait for retries.
6866 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6867 // the retry threshold is when we accept any size for PCM data. This is slightly
6868 // smaller than the retry count so we can push small bits of data without a glitch.
6869 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006870 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006871 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006872 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006873 minFrames = mNormalFrameCount;
6874 } else {
6875 minFrames = 1;
6876 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006877
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006878 const size_t framesReady = track->framesReady();
6879 const int trackId = track->id();
6880 if (ATRACE_ENABLED()) {
6881 std::string traceName("nRdy");
6882 traceName += std::to_string(trackId);
6883 ATRACE_INT(traceName.c_str(), framesReady);
6884 }
6885 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006886 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006887 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006888 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006889
Andy Hung8d31fd22023-06-26 19:20:57 -07006890 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6891 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006892 if (last) {
6893 // make sure processVolume_l() will apply new volume even if 0
6894 mLeftVolFloat = mRightVolFloat = -1.0;
6895 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006896 if (!mHwSupportsPause) {
6897 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006898 }
6899 }
6900
6901 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006902 processVolume_l(track, last);
6903 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006904 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006905 if (previousTrack != 0) {
6906 if (track != previousTrack.get()) {
6907 // Flush any data still being written from last track
6908 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006909 // Invalidate previous track to force a seek when resuming.
6910 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006911 }
6912 }
6913 mPreviousTrack = track;
6914
Eric Laurentd595b7c2013-04-03 17:27:56 -07006915 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006916 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006917 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006918 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006919 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006920 doHwResume = true;
6921 mHwPaused = false;
6922 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006923 }
Eric Laurent81784c32012-11-19 14:55:58 -08006924 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006925 // clear effect chain input buffer if the last active track started underruns
6926 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006927 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006928 mEffectChains[0]->clearInputBuffer();
6929 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006930 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006931 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006932 if (last && mHwPaused) {
6933 doHwResume = true;
6934 mHwPaused = false;
6935 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006936 }
6937 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6938 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006939 // We have consumed all the buffers of this track.
6940 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006941 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006942 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006943 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006944 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006945 if (presComplete) {
6946 mOutput->presentationComplete();
6947 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006948 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006949 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006950 }
Eric Laurent81784c32012-11-19 14:55:58 -08006951 if (track->isStopped()) {
6952 track->reset();
6953 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006954 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006955 }
6956 } else {
6957 // No buffers for this track. Give it a few chances to
6958 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006959 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006960 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006961 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006962 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006963 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006964 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006965 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00006966 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
6967 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08006968 tracksToRemove->add(track);
6969 // indicate to client process that the track was disabled because of
6970 // underrun; it will then automatically call start() when data is available
6971 track->disable();
6972 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6973 // unlike mixerthread, HAL can be paused for direct output
6974 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6975 "minFrames = %u, mFormat = %#x",
6976 framesReady, minFrames, mFormat);
6977 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6978 doHwPause = true;
6979 mHwPaused = true;
6980 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006981 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006982 } else if (last) {
6983 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006984 }
6985 }
6986 }
6987 }
6988
Eric Laurentd1f69b02014-12-15 14:33:13 -08006989 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006990 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006991 for (size_t i = 0; i < mTracks.size(); i++) {
6992 if (mTracks[i]->isFlushPending()) {
6993 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006994 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006995 }
6996 }
6997 }
6998
6999 // make sure the pause/flush/resume sequence is executed in the right order.
7000 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7001 // before flush and then resume HW. This can happen in case of pause/flush/resume
7002 // if resume is received before pause is executed.
7003 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007004 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007005 status_t result = mOutput->stream->pause();
7006 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007007 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007008 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007009 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007010 flushHw_l();
7011 }
7012 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007013 status_t result = mOutput->stream->resume();
7014 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007015 }
Eric Laurent81784c32012-11-19 14:55:58 -08007016 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007017 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007018
7019 return mixerStatus;
7020}
7021
Andy Hungee58e4a2023-07-07 13:47:37 -07007022void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007023{
Eric Laurent81784c32012-11-19 14:55:58 -08007024 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007025 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007026 // output audio to hardware
7027 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007028 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007029 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007030 status_t status = mActiveTrack->getNextBuffer(&buffer);
7031 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007032 // no need to pad with 0 for compressed audio
7033 if (audio_has_proportional_frames(mFormat)) {
7034 memset(curBuf, 0, frameCount * mFrameSize);
7035 }
Eric Laurent81784c32012-11-19 14:55:58 -08007036 break;
7037 }
7038 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7039 frameCount -= buffer.frameCount;
7040 curBuf += buffer.frameCount * mFrameSize;
7041 mActiveTrack->releaseBuffer(&buffer);
7042 }
Andy Hung2098f272014-02-27 14:00:06 -08007043 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007044 mSleepTimeUs = 0;
7045 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007046 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007047}
7048
Andy Hungee58e4a2023-07-07 13:47:37 -07007049void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007050{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007051 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007052 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007053 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007054 return;
7055 }
Andy Hung85ba3332021-04-27 17:40:26 -07007056 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7057 mSleepTimeUs = mActiveSleepTimeUs;
7058 } else {
7059 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007060 }
Andy Hung85ba3332021-04-27 17:40:26 -07007061 // Note: In S or later, we do not write zeroes for
7062 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007063}
7064
Andy Hungee58e4a2023-07-07 13:47:37 -07007065void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007066{
7067 {
Andy Hung972bec12023-08-31 16:13:39 -07007068 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007069 for (size_t i = 0; i < mTracks.size(); i++) {
7070 if (mTracks[i]->isFlushPending()) {
7071 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007072 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007073 }
7074 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007075 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007076 flushHw_l();
7077 }
7078 }
7079 PlaybackThread::threadLoop_exit();
7080}
7081
7082// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007083bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007084{
7085 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007086 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007087 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007088
Eric Laurent022a5132024-04-12 17:02:51 +00007089 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007090 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007091 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007092 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007093 const auto& mainTrack = mTracks[mTracks.size() - 1];
7094
7095 trackPaused = mainTrack->isPaused();
7096 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7097 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007098 }
7099
Eric Laurent022a5132024-04-12 17:02:51 +00007100 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007101}
7102
Andy Hungc5007f82023-08-29 14:26:09 -07007103// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007104bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007105 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007106{
7107 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007108 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007109
Eric Laurent10351942014-05-08 18:49:52 -07007110 AudioParameter param = AudioParameter(keyValuePair);
7111 int value;
7112 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007113 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007114 }
Eric Laurent10351942014-05-08 18:49:52 -07007115 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7116 // do not accept frame count changes if tracks are open as the track buffer
7117 // size depends on frame count and correct behavior would not be garantied
7118 // if frame count is changed after track creation
7119 if (!mTracks.isEmpty()) {
7120 status = INVALID_OPERATION;
7121 } else {
7122 reconfig = true;
7123 }
7124 }
7125 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007126 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007127 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007128 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007129 if (!mStandby) {
7130 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007131 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007132 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007133 }
Eric Laurent10351942014-05-08 18:49:52 -07007134 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007135 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007136 }
7137 if (status == NO_ERROR && reconfig) {
7138 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007139 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007140 }
7141 }
7142
Dean Wheatley68918102021-03-19 22:09:19 +11007143 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007144}
7145
Andy Hungee58e4a2023-07-07 13:47:37 -07007146uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007147{
7148 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007149 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007150 time = PlaybackThread::activeSleepTimeUs();
7151 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007152 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007153 }
7154 return time;
7155}
7156
Andy Hungee58e4a2023-07-07 13:47:37 -07007157uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007158{
7159 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007160 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007161 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7162 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007163 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007164 }
7165 return time;
7166}
7167
Andy Hungee58e4a2023-07-07 13:47:37 -07007168uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007169{
7170 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007171 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007172 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7173 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007174 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007175 }
7176 return time;
7177}
7178
Andy Hungee58e4a2023-07-07 13:47:37 -07007179void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007180{
7181 PlaybackThread::cacheParameters_l();
7182
7183 // use shorter standby delay as on normal output to release
7184 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007185 // no delay on outputs with HW A/V sync
7186 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007187 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007188 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007189 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007190 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007191 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007192 }
Eric Laurent81784c32012-11-19 14:55:58 -08007193}
7194
Andy Hungee58e4a2023-07-07 13:47:37 -07007195void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007196{
ziyangch8f194f12021-12-01 13:48:04 -08007197 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007198 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007199 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007200 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007201 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007202 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007203 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007204}
7205
Andy Hungee58e4a2023-07-07 13:47:37 -07007206int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007207 // If a VolumeShaper is active, we must wake up periodically to update volume.
7208 const int64_t NS_PER_MS = 1000000;
7209 return mVolumeShaperActive ?
7210 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7211}
7212
Eric Laurent81784c32012-11-19 14:55:58 -08007213// ----------------------------------------------------------------------------
7214
Andy Hungee58e4a2023-07-07 13:47:37 -07007215AsyncCallbackThread::AsyncCallbackThread(
7216 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007217 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007218 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007219 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007220 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007221 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007222{
7223}
7224
Andy Hungee58e4a2023-07-07 13:47:37 -07007225void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007226{
7227 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7228}
7229
Andy Hungee58e4a2023-07-07 13:47:37 -07007230bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007231{
7232 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007233 uint32_t writeAckSequence;
7234 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007235 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007236
7237 {
Andy Hungc5007f82023-08-29 14:26:09 -07007238 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007239 while (!((mWriteAckSequence & 1) ||
7240 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007241 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007242 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007243 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007244 }
7245
Eric Laurentbfb1b832013-01-07 09:53:42 -08007246 if (exitPending()) {
7247 break;
7248 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007249 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7250 mWriteAckSequence, mDrainSequence);
7251 writeAckSequence = mWriteAckSequence;
7252 mWriteAckSequence &= ~1;
7253 drainSequence = mDrainSequence;
7254 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007255 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007256 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007257 }
7258 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007259 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007260 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007261 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007262 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007263 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007264 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007265 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007266 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007267 if (asyncError != ASYNC_ERROR_NONE) {
7268 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007269 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007270 }
7271 }
7272 }
7273 return false;
7274}
7275
Andy Hungee58e4a2023-07-07 13:47:37 -07007276void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007277{
7278 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007279 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007280 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007281 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007282}
7283
Andy Hungee58e4a2023-07-07 13:47:37 -07007284void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007285{
Andy Hung972bec12023-08-31 16:13:39 -07007286 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007287 // bit 0 is cleared
7288 mWriteAckSequence = sequence << 1;
7289}
7290
Andy Hungee58e4a2023-07-07 13:47:37 -07007291void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007292{
Andy Hung972bec12023-08-31 16:13:39 -07007293 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007294 // ignore unexpected callbacks
7295 if (mWriteAckSequence & 2) {
7296 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007297 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007298 }
7299}
7300
Andy Hungee58e4a2023-07-07 13:47:37 -07007301void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007302{
Andy Hung972bec12023-08-31 16:13:39 -07007303 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007304 // bit 0 is cleared
7305 mDrainSequence = sequence << 1;
7306}
7307
Andy Hungee58e4a2023-07-07 13:47:37 -07007308void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007309{
Andy Hung972bec12023-08-31 16:13:39 -07007310 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007311 // ignore unexpected callbacks
7312 if (mDrainSequence & 2) {
7313 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007314 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007315 }
7316}
7317
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007318void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007319{
Andy Hung972bec12023-08-31 16:13:39 -07007320 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007321 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007322 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007323}
7324
Eric Laurentbfb1b832013-01-07 09:53:42 -08007325
7326// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007327
7328/* static */
7329sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007330 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007331 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7332 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007333 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007334}
7335
Andy Hung583043b2023-07-17 17:05:00 -07007336OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007337 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7338 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007339 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007340 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007341{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007342 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007343 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007344 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007345}
7346
Andy Hungee58e4a2023-07-07 13:47:37 -07007347void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348{
7349 if (mFlushPending || mHwPaused) {
7350 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007351 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007352 flushHw_l();
7353 } else {
7354 mMixerStatus = MIXER_DRAIN_ALL;
7355 threadLoop_drain();
7356 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007357 if (mUseAsyncWrite) {
7358 ALOG_ASSERT(mCallbackThread != 0);
7359 mCallbackThread->exit();
7360 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361 PlaybackThread::threadLoop_exit();
7362}
7363
Andy Hungee58e4a2023-07-07 13:47:37 -07007364PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007365 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007366)
7367{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007368 size_t count = mActiveTracks.size();
7369
7370 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007371 bool doHwPause = false;
7372 bool doHwResume = false;
7373
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007374 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007375
Eric Laurentbfb1b832013-01-07 09:53:42 -08007376 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007377 for (const sp<IAfTrack>& t : mActiveTracks) {
7378 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007379#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007380 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007381#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007382 // Only consider last track started for volume and mixer state control.
7383 // In theory an older track could underrun and restart after the new one starts
7384 // but as we only care about the transition phase between two tracks on a
7385 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007386 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007387 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007388
Haynes Mathew George7844f672014-01-15 12:32:55 -08007389 if (track->isInvalid()) {
7390 ALOGW("An invalidated track shouldn't be in active list");
7391 tracksToRemove->add(track);
7392 continue;
7393 }
7394
Andy Hung8d31fd22023-06-26 19:20:57 -07007395 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007396 ALOGW("An idle track shouldn't be in active list");
7397 continue;
7398 }
7399
Kuowei Li23666472021-01-20 10:23:25 +08007400 if (track->isPausePending()) {
7401 track->pauseAck();
7402 // It is possible a track might have been flushed or stopped.
7403 // Other operations such as flush pending might occur on the next prepare.
7404 if (track->isPausing()) {
7405 track->setPaused();
7406 }
7407 // Always perform pause if last, as an immediate flush will change
7408 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007409 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007410 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007411 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007412 mHwPaused = true;
7413 }
7414 // If we were part way through writing the mixbuffer to
7415 // the HAL we must save this until we resume
7416 // BUG - this will be wrong if a different track is made active,
7417 // in that case we want to discard the pending data in the
7418 // mixbuffer and tell the client to present it again when the
7419 // track is resumed
7420 mPausedWriteLength = mCurrentWriteLength;
7421 mPausedBytesRemaining = mBytesRemaining;
7422 mBytesRemaining = 0; // stop writing
7423 }
7424 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007425 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007426 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007427 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007428 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007429 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007430 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007431 track->flushAck();
7432 if (last) {
7433 mFlushPending = true;
7434 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007435 } else if (track->isResumePending()){
7436 track->resumeAck();
7437 if (last) {
7438 if (mPausedBytesRemaining) {
7439 // Need to continue write that was interrupted
7440 mCurrentWriteLength = mPausedWriteLength;
7441 mBytesRemaining = mPausedBytesRemaining;
7442 mPausedBytesRemaining = 0;
7443 }
7444 if (mHwPaused) {
7445 doHwResume = true;
7446 mHwPaused = false;
7447 // threadLoop_mix() will handle the case that we need to
7448 // resume an interrupted write
7449 }
7450 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007451 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007452
Eric Laurent3df841a2016-07-15 15:15:40 -07007453 mLeftVolFloat = mRightVolFloat = -1.0;
7454
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007455 // Do not handle new data in this iteration even if track->framesReady()
7456 mixerStatus = MIXER_TRACKS_ENABLED;
7457 }
7458 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007459 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007460 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007461 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7462 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007463 if (last) {
7464 // make sure processVolume_l() will apply new volume even if 0
7465 mLeftVolFloat = mRightVolFloat = -1.0;
7466 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007467 }
7468
7469 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007470 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007471 if (previousTrack != 0) {
7472 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007473 // Flush any data still being written from last track
7474 mBytesRemaining = 0;
7475 if (mPausedBytesRemaining) {
7476 // Last track was paused so we also need to flush saved
7477 // mixbuffer state and invalidate track so that it will
7478 // re-submit that unwritten data when it is next resumed
7479 mPausedBytesRemaining = 0;
7480 // Invalidate is a bit drastic - would be more efficient
7481 // to have a flag to tell client that some of the
7482 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007483 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007484 }
7485 // flush data already sent to the DSP if changing audio session as audio
7486 // comes from a different source. Also invalidate previous track to force a
7487 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007488 if (previousTrack->sessionId() != track->sessionId()) {
7489 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007490 }
7491 }
7492 }
7493 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007494 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007495 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007496 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007497 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007498 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007499 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007500 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007501 mixerStatus = MIXER_TRACKS_READY;
7502 }
7503 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007504 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007505 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007506 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007507 // Hardware buffer can hold a large amount of audio so we must
7508 // wait for all current track's data to drain before we say
7509 // that the track is stopped.
7510 if (mBytesRemaining == 0) {
7511 // Only start draining when all data in mixbuffer
7512 // has been written
7513 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007514 track->setState(IAfTrackBase::STOPPING_2);
7515 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007516 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7517 if (last && !mStandby) {
7518 // do not modify drain sequence if we are already draining. This happens
7519 // when resuming from pause after drain.
7520 if ((mDrainSequence & 1) == 0) {
7521 mSleepTimeUs = 0;
7522 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7523 mixerStatus = MIXER_DRAIN_TRACK;
7524 mDrainSequence += 2;
7525 }
7526 if (mHwPaused) {
7527 // It is possible to move from PAUSED to STOPPING_1 without
7528 // a resume so we must ensure hardware is running
7529 doHwResume = true;
7530 mHwPaused = false;
7531 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007532 }
7533 }
Eric Laurente93cc032016-05-05 10:15:10 -07007534 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007535 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007536 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007537 }
7538 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007539 // Drain has completed or we are in standby, signal presentation complete
7540 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007541 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007542 mOutput->presentationComplete();
7543 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007544 track->reset();
7545 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007546 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007547 if (!mUseAsyncWrite) {
7548 // If we don't get explicit drain notification we must
7549 // register discontinuity regardless of whether this is
7550 // the previous (!last) or the upcoming (last) track
7551 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007552 mTimestampVerifier.discontinuity(
7553 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007554 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007555 }
7556 } else {
7557 // No buffers for this track. Give it a few chances to
7558 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007559 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007560 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007561 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007562 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007563 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007564 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007565 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7566 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007567 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007568 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007569 // it will then automatically call start() when data is available
7570 track->disable();
7571 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007572 } else if (last){
7573 mixerStatus = MIXER_TRACKS_ENABLED;
7574 }
7575 }
7576 }
7577 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007578 if (track->isReady()) { // check ready to prevent premature start.
7579 processVolume_l(track, last);
7580 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007581 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007582
Eric Laurentea0fade2013-10-04 16:23:48 -07007583 // make sure the pause/flush/resume sequence is executed in the right order.
7584 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7585 // before flush and then resume HW. This can happen in case of pause/flush/resume
7586 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007587 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007588 status_t result = mOutput->stream->pause();
7589 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007590 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007591 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007592 if (mFlushPending) {
7593 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007594 }
Eric Laurentfd477972013-10-25 18:10:40 -07007595 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007596 status_t result = mOutput->stream->resume();
7597 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007598 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007599
Eric Laurentbfb1b832013-01-07 09:53:42 -08007600 // remove all the tracks that need to be...
7601 removeTracks_l(*tracksToRemove);
7602
7603 return mixerStatus;
7604}
7605
Eric Laurentbfb1b832013-01-07 09:53:42 -08007606// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007607bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007608{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007609 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7610 mWriteAckSequence, mDrainSequence);
7611 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007612 return true;
7613 }
7614 return false;
7615}
7616
Andy Hungee58e4a2023-07-07 13:47:37 -07007617bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007618{
Andy Hung972bec12023-08-31 16:13:39 -07007619 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007620 return waitingAsyncCallback_l();
7621}
7622
Andy Hungee58e4a2023-07-07 13:47:37 -07007623void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007624{
Eric Laurente659ef42014-09-29 13:06:46 -07007625 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007626 // Flush anything still waiting in the mixbuffer
7627 mCurrentWriteLength = 0;
7628 mBytesRemaining = 0;
7629 mPausedWriteLength = 0;
7630 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007631 // reset bytes written count to reflect that DSP buffers are empty after flush.
7632 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007633
Eric Laurentbfb1b832013-01-07 09:53:42 -08007634 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007635 // discard any pending drain or write ack by incrementing sequence
7636 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7637 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007638 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007639 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7640 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007641 }
7642}
7643
Andy Hungee58e4a2023-07-07 13:47:37 -07007644void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007645{
Andy Hung972bec12023-08-31 16:13:39 -07007646 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007647 if (PlaybackThread::invalidateTracks_l(streamType)) {
7648 mFlushPending = true;
7649 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007650}
7651
Andy Hungee58e4a2023-07-07 13:47:37 -07007652void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007653 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007654 if (PlaybackThread::invalidateTracks_l(portIds)) {
7655 mFlushPending = true;
7656 }
7657}
7658
Eric Laurentbfb1b832013-01-07 09:53:42 -08007659// ----------------------------------------------------------------------------
7660
Andy Hungee58e4a2023-07-07 13:47:37 -07007661/* static */
7662sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007663 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007664 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007665 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007666}
7667
Andy Hung583043b2023-07-17 17:05:00 -07007668DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007669 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007670 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007671 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007672 mWaitTimeMs(UINT_MAX)
7673{
7674 addOutputTrack(mainThread);
7675}
7676
Andy Hungee58e4a2023-07-07 13:47:37 -07007677DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007678{
7679 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7680 mOutputTracks[i]->destroy();
7681 }
7682}
7683
Andy Hungee58e4a2023-07-07 13:47:37 -07007684void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007685{
7686 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007687 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007688 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007689 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007690 if (mMixerBufferValid) {
7691 memset(mMixerBuffer, 0, mMixerBufferSize);
7692 } else {
7693 memset(mSinkBuffer, 0, mSinkBufferSize);
7694 }
Eric Laurent81784c32012-11-19 14:55:58 -08007695 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007696 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007697 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007698 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007699 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007700}
7701
Andy Hungee58e4a2023-07-07 13:47:37 -07007702void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007703{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007704 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007705 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007706 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007707 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007708 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007709 }
7710 } else if (mBytesWritten != 0) {
7711 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7712 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007713 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007714 } else {
7715 // flush remaining overflow buffers in output tracks
7716 writeFrames = 0;
7717 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007718 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007719 }
7720}
7721
Andy Hungee58e4a2023-07-07 13:47:37 -07007722ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007723{
7724 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007725 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7726
7727 // Consider the first OutputTrack for timestamp and frame counting.
7728
7729 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7730 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7731 // we always claim success.
7732 if (i == 0) {
7733 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7734 ALOGD_IF(correction != 0 && writeFrames != 0,
7735 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7736 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7737 mFramesWritten -= correction;
7738 }
7739
7740 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007741 }
Andy Hungcf10d742020-04-28 15:38:24 -07007742 if (mStandby) {
7743 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007744 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007745 mStandby = false;
7746 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007747 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007748}
7749
Andy Hungee58e4a2023-07-07 13:47:37 -07007750void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007751{
7752 // DuplicatingThread implements standby by stopping all tracks
7753 for (size_t i = 0; i < outputTracks.size(); i++) {
7754 outputTracks[i]->stop();
7755 }
7756}
7757
Andy Hung8a5abfd2023-12-07 19:35:12 -08007758void DuplicatingThread::threadLoop_exit()
7759{
7760 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7761 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7762 // Do so here in the threadLoop_exit().
7763
7764 SortedVector <sp<IAfOutputTrack>> localTracks;
7765 {
7766 audio_utils::lock_guard l(mutex());
7767 localTracks = std::move(mOutputTracks);
7768 mOutputTracks.clear();
7769 }
7770 localTracks.clear();
7771 outputTracks.clear();
7772 PlaybackThread::threadLoop_exit();
7773}
7774
Andy Hungee58e4a2023-07-07 13:47:37 -07007775void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007776{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007777 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007778
7779 std::stringstream ss;
7780 const size_t numTracks = mOutputTracks.size();
7781 ss << " " << numTracks << " OutputTracks";
7782 if (numTracks > 0) {
7783 ss << ":";
7784 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007785 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007786 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007787 if (thread.get() != nullptr) {
7788 ss << thread.get() << ", " << thread->id();
7789 } else {
7790 ss << "null";
7791 }
7792 ss << ")";
7793 }
7794 }
7795 ss << "\n";
7796 std::string result = ss.str();
7797 write(fd, result.c_str(), result.size());
7798}
7799
Andy Hungee58e4a2023-07-07 13:47:37 -07007800void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007801{
7802 outputTracks = mOutputTracks;
7803}
7804
Andy Hungee58e4a2023-07-07 13:47:37 -07007805void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007806{
7807 outputTracks.clear();
7808}
7809
Andy Hungee58e4a2023-07-07 13:47:37 -07007810void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007811{
Andy Hung972bec12023-08-31 16:13:39 -07007812 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007813 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7814 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7815 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7816 const size_t frameCount =
7817 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7818 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7819 // from different OutputTracks and their associated MixerThreads (e.g. one may
7820 // nearly empty and the other may be dropping data).
7821
Svet Ganov33761132021-05-13 22:51:08 +00007822 // TODO b/182392769: use attribution source util, move to server edge
7823 AttributionSourceState attributionSource = AttributionSourceState();
7824 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007825 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007826 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007827 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007828 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007829 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007830 this,
7831 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007832 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007833 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007834 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007835 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007836 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7837 if (status != NO_ERROR) {
7838 ALOGE("addOutputTrack() initCheck failed %d", status);
7839 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007840 }
Eric Laurent277a37e2024-07-29 18:37:52 +00007841 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007842 mOutputTracks.add(outputTrack);
7843 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7844 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007845}
7846
Andy Hungee58e4a2023-07-07 13:47:37 -07007847void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007848{
Andy Hung972bec12023-08-31 16:13:39 -07007849 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007850 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7851 if (mOutputTracks[i]->thread() == thread) {
7852 mOutputTracks[i]->destroy();
7853 mOutputTracks.removeAt(i);
7854 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007855 // NO_THREAD_SAFETY_ANALYSIS
7856 // Lambda workaround: as thread != this
7857 // we can safely call the remote thread getOutput.
7858 const bool equalOutput =
7859 [&](){ return thread->getOutput() == mOutput; }();
7860 if (equalOutput) {
7861 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007862 }
Eric Laurent81784c32012-11-19 14:55:58 -08007863 return;
7864 }
7865 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007866 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007867}
7868
Andy Hungc5007f82023-08-29 14:26:09 -07007869// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007870void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007871{
7872 mWaitTimeMs = UINT_MAX;
7873 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007874 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007875 if (strong != 0) {
7876 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7877 if (waitTimeMs < mWaitTimeMs) {
7878 mWaitTimeMs = waitTimeMs;
7879 }
7880 }
7881 }
7882}
7883
Andy Hungee58e4a2023-07-07 13:47:37 -07007884bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007885{
7886 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007887 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007888 if (thread == 0) {
7889 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7890 outputTracks[i].get());
7891 return false;
7892 }
Andy Hung87c693c2023-07-06 20:56:16 -07007893 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007894 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007895 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007896 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7897 thread.get());
7898 return false;
7899 }
7900 }
7901 return true;
7902}
7903
Andy Hungee58e4a2023-07-07 13:47:37 -07007904void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007905 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007906{
Kevin Rocard12381092018-04-11 09:19:59 -07007907 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7908 outputTrack->setMetadatas(metadata.tracks);
7909 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007910}
7911
Andy Hungee58e4a2023-07-07 13:47:37 -07007912uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007913{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007914 // return half the wait time in microseconds.
7915 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007916}
7917
Andy Hungee58e4a2023-07-07 13:47:37 -07007918void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007919{
7920 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7921 updateWaitTime_l();
7922
7923 MixerThread::cacheParameters_l();
7924}
7925
Eric Laurentb3f315a2021-07-13 15:09:05 +02007926// ----------------------------------------------------------------------------
7927
Andy Hungee58e4a2023-07-07 13:47:37 -07007928/* static */
7929sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007930 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007931 AudioStreamOut* output,
7932 audio_io_handle_t id,
7933 bool systemReady,
7934 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007935 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007936}
7937
Andy Hung583043b2023-07-17 17:05:00 -07007938SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007939 AudioStreamOut* output,
7940 audio_io_handle_t id,
7941 bool systemReady,
7942 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007943 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007944{
7945}
7946
Andy Hungee58e4a2023-07-07 13:47:37 -07007947void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007948 // if mSupportedLatencyModes is empty, the HAL stream does not support
7949 // latency mode control and we can exit.
7950 if (mSupportedLatencyModes.empty()) {
7951 return;
7952 }
Eric Laurent4c85e372024-02-23 16:50:06 +00007953 // Do not update the HAL latency mode if no track is active
7954 if (mActiveTracks.isEmpty()) {
7955 return;
7956 }
7957
Eric Laurent68a40a82022-05-03 18:15:04 +02007958 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7959 if (mSupportedLatencyModes.size() == 1) {
7960 // If the HAL only support one latency mode currently, confirm the choice
7961 latencyMode = mSupportedLatencyModes[0];
7962 } else if (mSupportedLatencyModes.size() > 1) {
7963 // Request low latency if:
7964 // - The low latency mode is requested by the spatializer controller
7965 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7966 // AND
7967 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007968 for (const auto& track : mActiveTracks) {
7969 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007970 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007971 break;
7972 }
7973 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007974 }
7975
7976 if (latencyMode != mSetLatencyMode) {
7977 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007978 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7979 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007980 if (status == NO_ERROR) {
7981 mSetLatencyMode = latencyMode;
7982 }
7983 }
7984}
7985
Andy Hungee58e4a2023-07-07 13:47:37 -07007986status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007987 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007988 return BAD_VALUE;
7989 }
Andy Hung972bec12023-08-31 16:13:39 -07007990 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007991 mRequestedLatencyMode = mode;
7992 return NO_ERROR;
7993}
7994
Andy Hungee58e4a2023-07-07 13:47:37 -07007995void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007996NO_THREAD_SAFETY_ANALYSIS
7997// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007998{
7999 bool hasVirtualizer = false;
8000 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008001 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008002 {
Andy Hung972bec12023-08-31 16:13:39 -07008003 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008004 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008005 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008006 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008007 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8008 }
8009
8010 finalDownMixer = mFinalDownMixer;
8011 mFinalDownMixer.clear();
8012 }
8013
8014 if (hasVirtualizer) {
8015 if (finalDownMixer != nullptr) {
8016 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008017 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008018 }
8019 finalDownMixer.clear();
8020 } else if (!hasDownMixer) {
8021 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008022 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008023 EFFECT_UIID_DOWNMIX, &descriptors);
8024 if (status != NO_ERROR) {
8025 return;
8026 }
8027 ALOG_ASSERT(!descriptors.empty(),
8028 "%s getDescriptors() returned no error but empty list", __func__);
8029
8030 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8031 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008032 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008033
8034 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8035 ALOGW("%s error creating downmixer %d", __func__, status);
8036 finalDownMixer.clear();
8037 } else {
8038 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008039 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008040 }
8041 }
8042
8043 {
Andy Hung972bec12023-08-31 16:13:39 -07008044 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008045 mFinalDownMixer = finalDownMixer;
8046 }
8047}
8048
Andy Hunge2514462023-12-06 14:59:24 -08008049void SpatializerThread::threadLoop_exit()
8050{
8051 // The Spatializer EffectHandle must be released on the PlaybackThread
8052 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8053 mFinalDownMixer.clear();
8054
8055 PlaybackThread::threadLoop_exit();
8056}
8057
Eric Laurent81784c32012-11-19 14:55:58 -08008058// ----------------------------------------------------------------------------
8059// Record
8060// ----------------------------------------------------------------------------
8061
Andy Hung583043b2023-07-17 17:05:00 -07008062sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008063 AudioStreamIn* input,
8064 audio_io_handle_t id,
8065 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008066 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008067}
8068
Andy Hung583043b2023-07-17 17:05:00 -07008069RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008070 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008071 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008072 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008073 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008074 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008075 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008076 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008077 mActiveTracks(&this->mLocalLog),
8078 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008079 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008080 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008081 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8082 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008083 // mFastCapture below
8084 , mFastCaptureFutex(0)
8085 // mInputSource
8086 // mPipeSink
8087 // mPipeSource
8088 , mPipeFramesP2(0)
8089 // mPipeMemory
8090 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008091 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008092 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008093{
Glenn Kastend7dca052015-03-05 16:05:54 -08008094 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008095 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008096
George Burgess IVa8f90c12020-05-14 11:27:19 -07008097 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008098 mIsMsdDevice = strcmp(
8099 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8100 }
8101
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008102 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008103
Andy Hungc8fddf32018-08-08 18:32:37 -07008104 // TODO: We may also match on address as well as device type for
8105 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008106 // TODO: This property should be ensure that only contains one single device type.
8107 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8108 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008109 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8110 : AUDIO_DEVICE_NONE));
8111
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008112 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008113 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008114 size_t numCounterOffers = 0;
8115 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008116#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008117 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008118#else
8119 (void)
8120#endif
8121 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008122 ALOG_ASSERT(index == 0);
8123
8124 // initialize fast capture depending on configuration
8125 bool initFastCapture;
8126 switch (kUseFastCapture) {
8127 case FastCapture_Never:
8128 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008129 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008130 break;
8131 case FastCapture_Always:
8132 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008133 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008134 break;
8135 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008136 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008137 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008138 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008139 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8140 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8141 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008142 break;
8143 // case FastCapture_Dynamic:
8144 }
8145
8146 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008147 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008148 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008149 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8150 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008151 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008152 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008153 const sp<MemoryDealer> roHeap(readOnlyHeap());
8154 sp<IMemory> pipeMemory;
8155 if ((roHeap == 0) ||
8156 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008157 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008158 ALOGE("not enough memory for pipe buffer size=%zu; "
8159 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8160 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8161 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008162 goto failed;
8163 }
8164 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8165 memset(pipeBuffer, 0, pipeSize);
8166 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008167 const NBAIO_Format offersFast[1] = {format};
8168 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008169 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008170 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008171 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008172 mPipeSink = pipe;
8173 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008174 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008175 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008176 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008177 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008178 mPipeSource = pipeReader;
8179 mPipeFramesP2 = pipeFramesP2;
8180 mPipeMemory = pipeMemory;
8181
8182 // create fast capture
8183 mFastCapture = new FastCapture();
8184 FastCaptureStateQueue *sq = mFastCapture->sq();
8185#ifdef STATE_QUEUE_DUMP
8186 // FIXME
8187#endif
8188 FastCaptureState *state = sq->begin();
8189 state->mCblk = NULL;
8190 state->mInputSource = mInputSource.get();
8191 state->mInputSourceGen++;
8192 state->mPipeSink = pipe;
8193 state->mPipeSinkGen++;
8194 state->mFrameCount = mFrameCount;
8195 state->mCommand = FastCaptureState::COLD_IDLE;
8196 // already done in constructor initialization list
8197 //mFastCaptureFutex = 0;
8198 state->mColdFutexAddr = &mFastCaptureFutex;
8199 state->mColdGen++;
8200 state->mDumpState = &mFastCaptureDumpState;
8201#ifdef TEE_SINK
8202 // FIXME
8203#endif
Andy Hung583043b2023-07-17 17:05:00 -07008204 mFastCaptureNBLogWriter =
8205 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008206 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8207 sq->end();
8208 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8209
8210 // start the fast capture
8211 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8212 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008213 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008214 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008215#ifdef AUDIO_WATCHDOG
8216 // FIXME
8217#endif
8218
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008219 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008220 }
Andy Hung8946a282018-04-19 20:04:56 -07008221#ifdef TEE_SINK
8222 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8223 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8224#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008225failed: ;
8226
8227 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008228}
8229
Andy Hungee58e4a2023-07-07 13:47:37 -07008230RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008231{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008232 if (mFastCapture != 0) {
8233 FastCaptureStateQueue *sq = mFastCapture->sq();
8234 FastCaptureState *state = sq->begin();
8235 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8236 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8237 if (old == -1) {
8238 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8239 }
8240 }
8241 state->mCommand = FastCaptureState::EXIT;
8242 sq->end();
8243 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8244 mFastCapture->join();
8245 mFastCapture.clear();
8246 }
Andy Hung583043b2023-07-17 17:05:00 -07008247 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8248 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008249 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008250}
8251
Andy Hungee58e4a2023-07-07 13:47:37 -07008252void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008253{
Glenn Kastend7dca052015-03-05 16:05:54 -08008254 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008255}
8256
Andy Hungee58e4a2023-07-07 13:47:37 -07008257void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008258{
8259 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008260 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008261 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008262 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008263 track->invalidate();
8264 }
8265 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008266 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008267}
8268
Andy Hungee58e4a2023-07-07 13:47:37 -07008269bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008270{
Eric Laurent81784c32012-11-19 14:55:58 -08008271 nsecs_t lastWarning = 0;
8272
8273 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008274
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008275reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008276 {
Andy Hung972bec12023-08-31 16:13:39 -07008277 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008278 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008279 }
8280
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008281 // used to request a deferred sleep, to be executed later while mutex is unlocked
8282 uint32_t sleepUs = 0;
8283
Andy Hung95c94a22023-10-20 16:41:18 -07008284 // timestamp correction enable is determined under lock, used in processing step.
8285 bool timestampCorrectionEnabled = false;
8286
Andy Hung446f4df2019-02-21 12:26:41 -08008287 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8288
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008289 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008290 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008291 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8292 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008293 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008294 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008295
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008296 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008297 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008298
Glenn Kasten735f45f2014-08-18 15:51:59 -07008299 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008300 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008301
Glenn Kasten735f45f2014-08-18 15:51:59 -07008302 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008303 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008304
Eric Laurent33403f02020-05-29 18:35:06 -07008305 bool silenceFastCapture = false;
8306
Andy Hungc5007f82023-08-29 14:26:09 -07008307 { // scope for mutex()
8308 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008309
Eric Laurent021cf962014-05-13 10:18:14 -07008310 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008311
Eric Laurent000a4192014-01-29 15:17:32 -08008312 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008313 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008314 if (exitPending()) {
8315 break;
8316 }
8317
Eric Laurent5c25d562016-07-13 17:17:45 -07008318 // sleep with mutex unlocked
8319 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008320 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008321 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008322 ATRACE_END();
8323 sleepUs = 0;
8324 continue;
8325 }
8326
Glenn Kasten2b806402013-11-20 16:37:38 -08008327 // if no active track(s), then standby and release wakelock
8328 size_t size = mActiveTracks.size();
8329 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008330 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008331 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008332 releaseWakeLock_l();
8333 ALOGV("RecordThread: loop stopping");
8334 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008335 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008336 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008337 goto reacquire_wakelock;
8338 }
8339
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008340 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008341 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008342 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008343 if (activeTrack) { // ensure track release is outside lock.
8344 oldActiveTracks.emplace_back(std::move(activeTrack));
8345 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008346 activeTrack = mActiveTracks[i];
8347 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008348 if (activeTrack->isFastTrack()) {
8349 ALOG_ASSERT(fastTrackToRemove == 0);
8350 fastTrackToRemove = activeTrack;
8351 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008352 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008353 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008354 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008355 continue;
8356 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008357
Andy Hung8d31fd22023-06-26 19:20:57 -07008358 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008359 switch (activeTrackState) {
8360
Andy Hung8d31fd22023-06-26 19:20:57 -07008361 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008362 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008363 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008364 if (activeTrack->isFastTrack()) {
8365 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8366 // Keep a ref on fast track to wait for FastCapture thread to get updated
8367 // state before potential track removal
8368 fastTrackToRemove = activeTrack;
8369 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008370 doBroadcast = true;
8371 size--;
8372 continue;
8373
Andy Hung8d31fd22023-06-26 19:20:57 -07008374 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008375 sleepUs = 10000;
8376 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008377 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008378 continue;
8379
Andy Hung8d31fd22023-06-26 19:20:57 -07008380 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008381 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008382 if (mStandby) {
8383 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008384 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008385 mStandby = false;
8386 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008387 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008388 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008389 break;
8390
Andy Hung8d31fd22023-06-26 19:20:57 -07008391 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008392 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008393 break;
8394
Andy Hung8d31fd22023-06-26 19:20:57 -07008395 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8396 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8397 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008398 default:
Andy Hungce685402018-10-05 17:23:27 -07008399 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8400 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008401 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008402
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008403 if (activeTrack->isFastTrack()) {
8404 ALOG_ASSERT(!mFastTrackAvail);
8405 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008406 // if the active fast track is silenced either:
8407 // 1) silence the whole capture from fast capture buffer if this is
8408 // the only active track
8409 // 2) invalidate this track: this will cause the client to reconnect and possibly
8410 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008411 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008412 if (activeTrack->isSilenced()) {
8413 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008414 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008415 } else {
8416 silenceFastCapture = true;
8417 }
8418 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008419 // Invalidate fast tracks if access to audio history is required as this is not
8420 // possible with fast tracks. Once the fast track has been invalidated, no new
8421 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8422 if (mMaxSharedAudioHistoryMs != 0) {
8423 invalidate = true;
8424 }
8425 if (invalidate) {
8426 activeTrack->invalidate();
8427 ALOG_ASSERT(fastTrackToRemove == 0);
8428 fastTrackToRemove = activeTrack;
8429 removeTrack_l(activeTrack);
8430 mActiveTracks.remove(activeTrack);
8431 size--;
8432 continue;
8433 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008434 fastTrack = activeTrack;
8435 }
Eric Laurent33403f02020-05-29 18:35:06 -07008436
8437 activeTracks.add(activeTrack);
8438 i++;
8439
Glenn Kasten9e982352013-08-14 14:39:50 -07008440 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008441
Andy Hungab65b182023-09-06 19:41:47 -07008442 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008443
Kevin Rocard069c2712018-03-29 19:09:14 -07008444 updateMetadata_l();
8445
Eric Laurent5c25d562016-07-13 17:17:45 -07008446 if (allStopped) {
8447 standbyIfNotAlreadyInStandby();
8448 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008449 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008450 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008451 }
8452
8453 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008454 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008455 if (sleepUs == 0) {
8456 sleepUs = kRecordThreadSleepUs;
8457 }
8458 continue;
8459 }
8460 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008461
Andy Hung95c94a22023-10-20 16:41:18 -07008462 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008463 lockEffectChains_l(effectChains);
8464 }
8465
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008466 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008467
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008468 size_t size = effectChains.size();
8469 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008470 // thread mutex is not locked, but effect chain is locked
8471 effectChains[i]->process_l();
8472 }
8473
Glenn Kasten735f45f2014-08-18 15:51:59 -07008474 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008475 if (mFastCapture != 0) {
8476 FastCaptureStateQueue *sq = mFastCapture->sq();
8477 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008478 bool didModify = false;
8479 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008480 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8481 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8482 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8483 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8484 if (old == -1) {
8485 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8486 }
8487 }
8488 state->mCommand = FastCaptureState::READ_WRITE;
8489#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008490 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008491 FastThreadDumpState::kSamplingNforLowRamDevice :
8492 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008493#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008494 didModify = true;
8495 }
8496 audio_track_cblk_t *cblkOld = state->mCblk;
8497 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8498 if (cblkNew != cblkOld) {
8499 state->mCblk = cblkNew;
8500 // block until acked if removing a fast track
8501 if (cblkOld != NULL) {
8502 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8503 }
8504 didModify = true;
8505 }
jiabin01c8f562018-07-19 17:47:28 -07008506 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8507 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8508 if (state->mFastPatchRecordBufferProvider != abp) {
8509 state->mFastPatchRecordBufferProvider = abp;
8510 state->mFastPatchRecordFormat = fastTrack == 0 ?
8511 AUDIO_FORMAT_INVALID : fastTrack->format();
8512 didModify = true;
8513 }
Eric Laurent33403f02020-05-29 18:35:06 -07008514 if (state->mSilenceCapture != silenceFastCapture) {
8515 state->mSilenceCapture = silenceFastCapture;
8516 didModify = true;
8517 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008518 sq->end(didModify);
8519 if (didModify) {
8520 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008521#if 0
8522 if (kUseFastCapture == FastCapture_Dynamic) {
8523 mNormalSource = mPipeSource;
8524 }
8525#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008526 }
8527 }
8528
Glenn Kasten735f45f2014-08-18 15:51:59 -07008529 // now run the fast track destructor with thread mutex unlocked
8530 fastTrackToRemove.clear();
8531
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008532 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8533 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8534 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8535 // If destination is non-contiguous, first read past the nominal end of buffer, then
8536 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008537
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008538 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008539 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008540 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008541
8542 // If an NBAIO source is present, use it to read the normal capture's data
8543 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008544 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008545
8546 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8547 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8548 // we immediately retry the read() to get data and prevent another overflow.
8549 for (int retries = 0; retries <= 2; ++retries) {
8550 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8551 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8552 framesToRead);
8553 if (framesRead != OVERRUN) break;
8554 }
8555
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008556 const ssize_t availableToRead = mPipeSource->availableToRead();
8557 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008558 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008559 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008560 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8561 "more frames to read than fifo size, %zd > %zu",
8562 availableToRead, mPipeFramesP2);
8563 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8564 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8565 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8566 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008567 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8568 }
8569 if (framesRead < 0) {
8570 status_t status = (status_t) framesRead;
8571 switch (status) {
8572 case OVERRUN:
8573 ALOGW("overrun on read from pipe");
8574 framesRead = 0;
8575 break;
8576 case NEGOTIATE:
8577 ALOGE("re-negotiation is needed");
8578 framesRead = -1; // Will cause an attempt to recover.
8579 break;
8580 default:
8581 ALOGE("unknown error %d on read from pipe", status);
8582 break;
8583 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008584 }
8585 // otherwise use the HAL / AudioStreamIn directly
8586 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008587 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008588 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008589 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008590 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008591 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008592 if (result < 0) {
8593 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008594 } else {
8595 framesRead = bytesRead / mFrameSize;
8596 }
8597 }
8598
Andy Hung446f4df2019-02-21 12:26:41 -08008599 const int64_t lastIoEndNs = systemTime(); // end IO timing
8600
Andy Hung3f0c9022016-01-15 17:49:46 -08008601 // Update server timestamp with server stats
8602 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008603 if (framesRead >= 0) {
8604 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8605 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8606 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008607
8608 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008609 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008610 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008611 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008612 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8613 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8614 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008615 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008616 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8617
8618 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008619 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008620 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008621 id(), (long long)time, (long long)position);
8622 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8623 position = correctedTimestamp.mFrames;
8624 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008625 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008626 id(), (long long)time, (long long)position);
8627 }
8628
Andy Hung3f0c9022016-01-15 17:49:46 -08008629 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8630 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8631 // Note: In general record buffers should tend to be empty in
8632 // a properly running pipeline.
8633 //
8634 // Also, it is not advantageous to call get_presentation_position during the read
8635 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008636 } else {
8637 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008638 }
8639 }
Andy Hunge6c37112019-02-26 17:38:10 -08008640
8641 // From the timestamp, input read latency is negative output write latency.
8642 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008643 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008644 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8645 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8646 mLatencyMs.add(latencyMs);
8647 }
8648
Andy Hung3f0c9022016-01-15 17:49:46 -08008649 // Use this to track timestamp information
8650 // ALOGD("%s", mTimestamp.toString().c_str());
8651
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008652 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008653 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008654 // Force input into standby so that it tries to recover at next read attempt
8655 inputStandBy();
8656 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008657 }
8658 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008659 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008660 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008661 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008662 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008663
Andy Hung8946a282018-04-19 20:04:56 -07008664#ifdef TEE_SINK
8665 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8666#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008667 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008668 {
8669 size_t part1 = mRsmpInFramesP2 - rear;
8670 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008671 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008672 (framesRead - part1) * mFrameSize);
8673 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008674 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008675 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008676
8677 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008678
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008679 // loop over each active track
8680 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008681 if (activeTrack) { // ensure track release is outside lock.
8682 oldActiveTracks.emplace_back(std::move(activeTrack));
8683 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008684 activeTrack = activeTracks[i];
8685
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008686 // skip fast tracks, as those are handled directly by FastCapture
8687 if (activeTrack->isFastTrack()) {
8688 continue;
8689 }
8690
Andy Hung73c02e42015-03-29 01:13:58 -07008691 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008692 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8693
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008694 enum {
8695 OVERRUN_UNKNOWN,
8696 OVERRUN_TRUE,
8697 OVERRUN_FALSE
8698 } overrun = OVERRUN_UNKNOWN;
8699
8700 // loop over getNextBuffer to handle circular sink
8701 for (;;) {
8702
Andy Hung8d31fd22023-06-26 19:20:57 -07008703 activeTrack->sinkBuffer().frameCount = ~0;
8704 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8705 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008706 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8707
Andy Hung73c02e42015-03-29 01:13:58 -07008708 // check available frames and handle overrun conditions
8709 // if the record track isn't draining fast enough.
8710 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008711 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008712 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008713 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008714 overrun = OVERRUN_TRUE;
8715 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008716 if (framesOut == 0 || framesIn == 0) {
8717 break;
8718 }
8719
Andy Hung6770c6f2015-04-07 13:43:36 -07008720 // Don't allow framesOut to be larger than what is possible with resampling
8721 // from framesIn.
8722 // This isn't strictly necessary but helps limit buffer resizing in
8723 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008724 if (audio_is_linear_pcm(activeTrack->format())) {
8725 framesOut = min(framesOut,
8726 destinationFramesPossible(
8727 framesIn, mSampleRate, activeTrack->sampleRate()));
8728 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008729
8730 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008731 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008732 // straight from RecordThread buffer to RecordTrack buffer.
8733 AudioBufferProvider::Buffer buffer;
8734 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008735 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008736 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008737 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008738 ALOGV_IF(buffer.frameCount != framesOut,
8739 "%s() read less than expected (%zu vs %zu)",
8740 __func__, buffer.frameCount, framesOut);
8741 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008742 memcpy(activeTrack->sinkBuffer().raw,
8743 buffer.raw, buffer.frameCount * mFrameSize);
8744 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008745 } else {
8746 framesOut = 0;
8747 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008748 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008749 }
8750 } else {
8751 // process frames from the RecordThread buffer provider to the RecordTrack
8752 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008753 framesOut = activeTrack->recordBufferConverter()->convert(
8754 activeTrack->sinkBuffer().raw,
8755 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008756 framesOut);
8757 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008758
8759 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8760 overrun = OVERRUN_FALSE;
8761 }
8762
Andy Hung93bb5732023-05-04 21:16:34 -07008763 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8764 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008765 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008766 if (framesToDrop == 0) {
8767 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008768 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008769 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008770 // Sanitize before releasing if the track has no access to the source data
8771 // An idle UID receives silence from non virtual devices until active
8772 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008773 memset(activeTrack->sinkBuffer().raw,
8774 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008775 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008776 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008777 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008778 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008779 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008780 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008781 }
8782 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008783
8784 switch (overrun) {
8785 case OVERRUN_TRUE:
8786 // client isn't retrieving buffers fast enough
8787 if (!activeTrack->setOverflow()) {
8788 nsecs_t now = systemTime();
8789 // FIXME should lastWarning per track?
8790 if ((now - lastWarning) > kWarningThrottleNs) {
8791 ALOGW("RecordThread: buffer overflow");
8792 lastWarning = now;
8793 }
8794 }
8795 break;
8796 case OVERRUN_FALSE:
8797 activeTrack->clearOverflow();
8798 break;
8799 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008800 break;
8801 }
8802
Andy Hung3f0c9022016-01-15 17:49:46 -08008803 // update frame information and push timestamp out
8804 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008805 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008806 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8807 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008808 }
8809
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008810unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008811 // enable changes in effect chain
8812 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008813 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008814 if (audio_has_proportional_frames(mFormat)
8815 && loopCount == lastLoopCountRead + 1) {
8816 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8817 const double jitterMs =
8818 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8819 {framesRead, readPeriodNs},
8820 {0, 0} /* lastTimestamp */, mSampleRate);
8821 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8822
Andy Hung972bec12023-08-31 16:13:39 -07008823 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008824 mIoJitterMs.add(jitterMs);
8825 mProcessTimeMs.add(processMs);
8826 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008827 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008828 // update timing info.
8829 mLastIoBeginNs = lastIoBeginNs;
8830 mLastIoEndNs = lastIoEndNs;
8831 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008832 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008833 mThreadloopExecutor.process(); // process any remaining deferred actions.
8834 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008835
Glenn Kasten93e471f2013-08-19 08:40:07 -07008836 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008837
8838 {
Andy Hung972bec12023-08-31 16:13:39 -07008839 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008840 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008841 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008842 track->invalidate();
8843 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008844 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008845 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008846 }
8847
8848 releaseWakeLock();
8849
8850 ALOGV("RecordThread %p exiting", this);
8851 return false;
8852}
8853
Andy Hungee58e4a2023-07-07 13:47:37 -07008854void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008855{
8856 if (!mStandby) {
8857 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008858 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008859 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008860 mStandby = true;
8861 }
8862}
8863
Andy Hungee58e4a2023-07-07 13:47:37 -07008864void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008865{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008866 // Idle the fast capture if it's currently running
8867 if (mFastCapture != 0) {
8868 FastCaptureStateQueue *sq = mFastCapture->sq();
8869 FastCaptureState *state = sq->begin();
8870 if (!(state->mCommand & FastCaptureState::IDLE)) {
8871 state->mCommand = FastCaptureState::COLD_IDLE;
8872 state->mColdFutexAddr = &mFastCaptureFutex;
8873 state->mColdGen++;
8874 mFastCaptureFutex = 0;
8875 sq->end();
8876 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8877 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8878#if 0
8879 if (kUseFastCapture == FastCapture_Dynamic) {
8880 // FIXME
8881 }
8882#endif
8883#ifdef AUDIO_WATCHDOG
8884 // FIXME
8885#endif
8886 } else {
8887 sq->end(false /*didModify*/);
8888 }
8889 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008890 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008891 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008892
8893 // If going into standby, flush the pipe source.
8894 if (mPipeSource.get() != nullptr) {
8895 const ssize_t flushed = mPipeSource->flush();
8896 if (flushed > 0) {
8897 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8898 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8899 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8900 }
8901 }
Eric Laurent81784c32012-11-19 14:55:58 -08008902}
8903
Andy Hungc5007f82023-08-29 14:26:09 -07008904// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008905sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008906 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008907 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008908 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008909 audio_format_t format,
8910 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008911 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008912 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008913 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008914 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008915 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008916 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008917 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008918 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008919 audio_port_handle_t portId,
8920 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008921{
Glenn Kasten74935e42013-12-19 08:56:45 -08008922 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008923 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008924 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008925 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008926 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008927 audio_input_flags_t requestedFlags = *flags;
8928 uint32_t sampleRate;
8929
8930 lStatus = initCheck();
8931 if (lStatus != NO_ERROR) {
8932 ALOGE("createRecordTrack_l() audio driver not initialized");
8933 goto Exit;
8934 }
8935
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008936 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8937 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8938 lStatus = BAD_VALUE;
8939 goto Exit;
8940 }
8941
Eric Laurentec376dc2021-04-08 20:41:22 +02008942 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008943 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008944 lStatus = PERMISSION_DENIED;
8945 goto Exit;
8946 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008947 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008948 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008949 lStatus = BAD_VALUE;
8950 goto Exit;
8951 }
8952 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008953 if (*pSampleRate == 0) {
8954 *pSampleRate = mSampleRate;
8955 }
8956 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008957
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008958 // special case for FAST flag considered OK if fast capture is present and access to
8959 // audio history is not required
8960 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008961 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8962 }
8963
Eric Laurentf14db3c2017-12-08 14:20:36 -08008964 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008965 if ((*flags & inputFlags) != *flags) {
8966 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8967 " input flags (%08x)",
8968 *flags, inputFlags);
8969 *flags = (audio_input_flags_t)(*flags & inputFlags);
8970 }
Eric Laurent81784c32012-11-19 14:55:58 -08008971
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008972 // client expresses a preference for FAST and no access to audio history,
8973 // but we get the final say
8974 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008975 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008976 // we formerly checked for a callback handler (non-0 tid),
8977 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008978 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008979 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008980 // Frame count is not specified (0), or is less than or equal the pipe depth.
8981 // It is OK to provide a higher capacity than requested.
8982 // We will force it to mPipeFramesP2 below.
8983 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008984 // PCM data
8985 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008986 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008987 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008988 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008989 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008990 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008991 hasFastCapture() &&
8992 // there are sufficient fast track slots available
8993 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008994 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008995 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008996 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008997 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008998 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008999 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009000 audio_input_flags_t old = *flags;
9001 chain->checkInputFlagCompatibility(flags);
9002 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009003 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9004 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009005 }
9006 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009007 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009008 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9009 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009010 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009011 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9012 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009013 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009014 this, frameCount, mFrameCount, mPipeFramesP2,
9015 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009016 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009017 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009018 }
9019 }
9020
Eric Laurentf14db3c2017-12-08 14:20:36 -08009021 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9022 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9023 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9024 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9025 lStatus = BAD_TYPE;
9026 goto Exit;
9027 }
9028
Glenn Kasten74105912014-07-03 12:28:53 -07009029 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009030 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009031 // fast track: frame count is exactly the pipe depth
9032 frameCount = mPipeFramesP2;
9033 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009034 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009035 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009036 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9037 // or 20 ms if there is a fast capture
9038 // TODO This could be a roundupRatio inline, and const
9039 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9040 * sampleRate + mSampleRate - 1) / mSampleRate;
9041 // minimum number of notification periods is at least kMinNotifications,
9042 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9043 static const size_t kMinNotifications = 3;
9044 static const uint32_t kMinMs = 30;
9045 // TODO This could be a roundupRatio inline
9046 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9047 // TODO This could be a roundupRatio inline
9048 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9049 maxNotificationFrames;
9050 const size_t minFrameCount = maxNotificationFrames *
9051 max(kMinNotifications, minNotificationsByMs);
9052 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009053 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9054 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009055 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009056 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009057 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009058 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009059
Andy Hungc5007f82023-08-29 14:26:09 -07009060 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009061 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009062 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009063 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009064 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009065 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009066 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009067 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009068 }
Eric Laurent81784c32012-11-19 14:55:58 -08009069
Andy Hung8d31fd22023-06-26 19:20:57 -07009070 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009071 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009072 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009073 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009074 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009075
Glenn Kasten03003332013-08-06 15:40:54 -07009076 lStatus = track->initCheck();
9077 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009078 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009079 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009080 goto Exit;
9081 }
9082 mTracks.add(track);
9083
Eric Laurent05067782016-06-01 18:27:28 -07009084 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009085 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9086 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9087 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009088 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009089 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009090
9091 if (maxSharedAudioHistoryMs != 0) {
9092 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9093 }
Eric Laurent81784c32012-11-19 14:55:58 -08009094 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009095
Eric Laurent81784c32012-11-19 14:55:58 -08009096 lStatus = NO_ERROR;
9097
9098Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009099 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009100 return track;
9101}
9102
Andy Hungee58e4a2023-07-07 13:47:37 -07009103status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009104 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009105 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009106{
9107 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9108 sp<ThreadBase> strongMe = this;
9109 status_t status = NO_ERROR;
9110
9111 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009112 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009113 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009114 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009115 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009116 event, triggerSession,
9117 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009118 }
9119
9120 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009121 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009122 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009123 if (recordTrack->isInvalid()) {
9124 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009125 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9126 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009127 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009128 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009129 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009130 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9131 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009132 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009133 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009134 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009135 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009136 }
9137 return status;
9138 }
9139
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009140 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9141 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9142 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009143 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009144 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009145 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009146 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009147 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009148 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009149 if (recordTrack->isInvalid()) {
9150 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009151 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9152 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009153 // STARTING_2 forces destroy to call stopInput.
9154 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009155 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9156 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009157 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009158 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009159 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009160 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009161 // Someone else has changed state, let them take over,
9162 // leave mState in the new state.
9163 recordTrack->clearSyncStartEvent();
9164 return INVALID_OPERATION;
9165 }
9166 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009167 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009168 ALOGW("%s(%d): startInput failed, status %d",
9169 __func__, recordTrack->id(), status);
9170 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9171 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009172 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009173 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009174 return status;
9175 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009176 sendIoConfigEvent_l(
9177 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009178 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009179
9180 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9181
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009182 // Catch up with current buffer indices if thread is already running.
9183 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9184 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9185 // see previously buffered data before it called start(), but with greater risk of overrun.
9186
Andy Hung8d31fd22023-06-26 19:20:57 -07009187 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009188 if (!recordTrack->isDirect()) {
9189 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009190 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009191 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009192 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009193 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009194 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009195 return status;
9196 }
Eric Laurent81784c32012-11-19 14:55:58 -08009197}
9198
Andy Hungee58e4a2023-07-07 13:47:37 -07009199void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009200{
Andy Hungee58e4a2023-07-07 13:47:37 -07009201 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009202
9203 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009204 sp<IAfTrackBase> ptr =
9205 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9206 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009207 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009208 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009209 }
Eric Laurent81784c32012-11-19 14:55:58 -08009210 }
9211}
9212
Andy Hungee58e4a2023-07-07 13:47:37 -07009213bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009214 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009215 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009216 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009217 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009218 return false;
9219 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009220 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009221 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009222
Andy Hungabfab202019-03-07 19:45:54 -08009223 // NOTE: Waiting here is important to keep stop synchronous.
9224 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009225 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009226 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009227 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009228 }
Andy Hungce685402018-10-05 17:23:27 -07009229
Andy Hung8d31fd22023-06-26 19:20:57 -07009230 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009231 ALOGV("Record stopped OK");
9232 return true;
9233 }
Andy Hungce685402018-10-05 17:23:27 -07009234
9235 // don't handle anything - we've been invalidated or restarted and in a different state
9236 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009237 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009238 return false;
9239}
9240
Andy Hungee58e4a2023-07-07 13:47:37 -07009241bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009242{
9243 return false;
9244}
9245
Andy Hungee58e4a2023-07-07 13:47:37 -07009246status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009247{
9248#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9249 if (!isValidSyncEvent(event)) {
9250 return BAD_VALUE;
9251 }
9252
Glenn Kastend848eb42016-03-08 13:42:11 -08009253 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009254 status_t ret = NAME_NOT_FOUND;
9255
Andy Hung972bec12023-08-31 16:13:39 -07009256 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009257
9258 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009259 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009260 if (eventSession == track->sessionId()) {
9261 (void) track->setSyncEvent(event);
9262 ret = NO_ERROR;
9263 }
9264 }
9265 return ret;
9266#else
9267 return BAD_VALUE;
9268#endif
9269}
9270
Andy Hungee58e4a2023-07-07 13:47:37 -07009271status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009272 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009273{
9274 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009275 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009276 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009277 return NO_INIT;
9278 }
jiabin9ff780e2018-03-19 18:19:52 -07009279 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9280 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009281}
9282
Andy Hungee58e4a2023-07-07 13:47:37 -07009283status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009284 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009285{
Paul McLean12340082019-03-19 09:35:05 -06009286 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009287 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009288 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009289 return NO_INIT;
9290 }
Paul McLean12340082019-03-19 09:35:05 -06009291 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009292}
9293
Andy Hungee58e4a2023-07-07 13:47:37 -07009294status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009295{
Paul McLean12340082019-03-19 09:35:05 -06009296 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009297 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009298 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009299 return NO_INIT;
9300 }
Paul McLean12340082019-03-19 09:35:05 -06009301 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009302}
9303
Andy Hungee58e4a2023-07-07 13:47:37 -07009304status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009305 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9306 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009307 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009308 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9309}
9310
Andy Hungee58e4a2023-07-07 13:47:37 -07009311status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009312 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9313 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009314
Eric Laurentec376dc2021-04-08 20:41:22 +02009315 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9316 return BAD_VALUE;
9317 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009318
9319 if (sharedAudioStartMs < 0
9320 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009321 return BAD_VALUE;
9322 }
9323
Eric Laurent2407ce32021-04-26 14:56:03 +02009324 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9325 // As we cannot detect more than one wraparound, only accept values up current write position
9326 // after one wraparound
9327 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9328 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009329 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009330 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9331 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009332 // Bring the start frame position within the input buffer to match the documented
9333 // "best effort" behavior of the API.
9334 if (sharedOffset < 0) {
9335 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009336 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009337 sharedAudioStartFrames =
9338 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009339 }
9340
Eric Laurentec376dc2021-04-08 20:41:22 +02009341 mSharedAudioPackageName = sharedAudioPackageName;
9342 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009343 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009344 } else {
9345 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009346 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009347 }
9348 return NO_ERROR;
9349}
9350
Andy Hungee58e4a2023-07-07 13:47:37 -07009351void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009352 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9353 mSharedAudioStartFrames = -1;
9354 mSharedAudioPackageName = "";
9355}
9356
Andy Hungee58e4a2023-07-07 13:47:37 -07009357ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009358{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009359 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009360 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009361 }
9362 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009363 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009364 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009365 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009366 }
9367 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009368 MetadataUpdate change;
9369 change.recordMetadataUpdate = metadata.tracks;
9370 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009371}
9372
Andy Hungc5007f82023-08-29 14:26:09 -07009373// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009374void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009375{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009376 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009377 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009378
Eric Laurent81784c32012-11-19 14:55:58 -08009379 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009380 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009381 removeTrack_l(track);
9382 }
9383}
9384
Andy Hungee58e4a2023-07-07 13:47:37 -07009385void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009386{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009387 String8 result;
9388 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009389 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009390
Eric Laurent81784c32012-11-19 14:55:58 -08009391 mTracks.remove(track);
9392 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009393 if (track->isFastTrack()) {
9394 ALOG_ASSERT(!mFastTrackAvail);
9395 mFastTrackAvail = true;
9396 }
Eric Laurent81784c32012-11-19 14:55:58 -08009397}
9398
Andy Hungee58e4a2023-07-07 13:47:37 -07009399void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009400{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009401 AudioStreamIn *input = mInput;
9402 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9403 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009404 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009405 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009406 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009407 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009408 }
Andy Hungbfa64962017-06-12 14:43:19 -07009409
9410 if (input != nullptr) {
9411 dprintf(fd, " Hal stream dump:\n");
9412 (void)input->stream->dump(fd);
9413 }
9414
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009415 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009416 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009417
Glenn Kasten2f90c512015-12-02 11:40:09 -08009418 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9419 // while we are dumping it. It may be inconsistent, but it won't mutate!
9420 // This is a large object so we place it on the heap.
9421 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009422 const std::unique_ptr<FastCaptureDumpState> copy =
9423 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009424 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009425}
9426
Andy Hungee58e4a2023-07-07 13:47:37 -07009427void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009428{
Eric Laurent81784c32012-11-19 14:55:58 -08009429 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009430 size_t numtracks = mTracks.size();
9431 size_t numactive = mActiveTracks.size();
9432 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009433 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009434 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009435 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009436 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009437 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009438 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009439 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009440 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009441 if (track != 0) {
9442 bool active = mActiveTracks.indexOf(track) >= 0;
9443 if (active) {
9444 numactiveseen++;
9445 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009446 result.append(prefix);
9447 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009448 }
Eric Laurent81784c32012-11-19 14:55:58 -08009449 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009450 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009451 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009452 }
9453
Marco Nelissenb2208842014-02-07 14:00:50 -08009454 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009455 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009456 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009457 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009458 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009459 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009460 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009461 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009462 result.append(prefix);
9463 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009464 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009465 }
Eric Laurent81784c32012-11-19 14:55:58 -08009466
9467 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009468 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009469}
9470
Andy Hungee58e4a2023-07-07 13:47:37 -07009471void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009472{
Andy Hung972bec12023-08-31 16:13:39 -07009473 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009474 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009475 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009476 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009477 track->setSilenced(silenced);
9478 }
9479 }
9480}
Andy Hung73c02e42015-03-29 01:13:58 -07009481
Andy Hung8d31fd22023-06-26 19:20:57 -07009482void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009483{
Andy Hung87c693c2023-07-06 20:56:16 -07009484 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009485 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009486 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009487 const int32_t rear = recordThread->mRsmpInRear;
9488 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009489 if (mRecordTrack->startFrames() >= 0) {
9490 int32_t startFrames = mRecordTrack->startFrames();
9491 // Accept a recent wraparound of mRsmpInRear
9492 if (startFrames <= rear) {
9493 deltaFrames = rear - startFrames;
9494 } else {
9495 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009496 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009497 // start frame cannot be further in the past than start of resampling buffer
9498 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9499 deltaFrames = recordThread->mRsmpInFrames;
9500 }
9501 }
9502 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009503}
9504
Andy Hung8d31fd22023-06-26 19:20:57 -07009505void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009506 size_t *framesAvailable, bool *hasOverrun)
9507{
Andy Hung87c693c2023-07-06 20:56:16 -07009508 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009509 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009510 const int32_t rear = recordThread->mRsmpInRear;
9511 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009512 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009513
9514 size_t framesIn;
9515 bool overrun = false;
9516 if (filled < 0) {
9517 // should not happen, but treat like a massive overrun and re-sync
9518 framesIn = 0;
9519 mRsmpInFront = rear;
9520 overrun = true;
9521 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9522 framesIn = (size_t) filled;
9523 } else {
9524 // client is not keeping up with server, but give it latest data
9525 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009526 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9527 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009528 overrun = true;
9529 }
9530 if (framesAvailable != NULL) {
9531 *framesAvailable = framesIn;
9532 }
9533 if (hasOverrun != NULL) {
9534 *hasOverrun = overrun;
9535 }
9536}
9537
Eric Laurent81784c32012-11-19 14:55:58 -08009538// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009539status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009540 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009541{
Andy Hung87c693c2023-07-06 20:56:16 -07009542 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009543 if (threadBase == 0) {
9544 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009545 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009546 return NOT_ENOUGH_DATA;
9547 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009548 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009549 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009550 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009551 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009552 // FIXME should not be P2 (don't want to increase latency)
9553 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009554 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009555 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009556
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009557 front &= recordThread->mRsmpInFramesP2 - 1;
9558 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009559 if (part1 > (size_t) filled) {
9560 part1 = filled;
9561 }
9562 size_t ask = buffer->frameCount;
9563 ALOG_ASSERT(ask > 0);
9564 if (part1 > ask) {
9565 part1 = ask;
9566 }
9567 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009568 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009569 buffer->raw = NULL;
9570 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009571 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009572 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009573 }
9574
Andy Hung57446612015-04-19 23:56:46 -07009575 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009576 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009577 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009578 return NO_ERROR;
9579}
9580
9581// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009582void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009583 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009584{
Hongwei Wang95e37682019-04-12 11:13:36 -07009585 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009586 if (stepCount == 0) {
9587 return;
9588 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009589 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009590 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009591 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009592 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009593 buffer->frameCount = 0;
9594}
9595
Andy Hungee58e4a2023-07-07 13:47:37 -07009596void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009597{
Andy Hung972bec12023-08-31 16:13:39 -07009598 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009599 checkBtNrec_l();
9600}
9601
Andy Hungee58e4a2023-07-07 13:47:37 -07009602void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009603{
9604 // disable AEC and NS if the device is a BT SCO headset supporting those
9605 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009606 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009607 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009608 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9609 for (size_t i = 0; i < mEffectChains.size(); i++) {
9610 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9611 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9612 }
9613 }
9614}
9615
Andy Hung97a893e2015-03-29 01:03:07 -07009616
Andy Hungee58e4a2023-07-07 13:47:37 -07009617bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009618 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009619{
9620 bool reconfig = false;
9621
Eric Laurent10351942014-05-08 18:49:52 -07009622 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009623
Eric Laurent10351942014-05-08 18:49:52 -07009624 audio_format_t reqFormat = mFormat;
9625 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009626 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Jing Mike537412f2023-03-12 11:01:47 +08009627 [[maybe_unused]] audio_channel_mask_t channelMask =
9628 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009629
9630 AudioParameter param = AudioParameter(keyValuePair);
9631 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009632
9633 // scope for AutoPark extends to end of method
9634 AutoPark<FastCapture> park(mFastCapture);
9635
Eric Laurent10351942014-05-08 18:49:52 -07009636 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9637 // channel count change can be requested. Do we mandate the first client defines the
9638 // HAL sampling rate and channel count or do we allow changes on the fly?
9639 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9640 samplingRate = value;
9641 reconfig = true;
9642 }
9643 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009644 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009645 status = BAD_VALUE;
9646 } else {
9647 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009648 reconfig = true;
9649 }
Eric Laurent10351942014-05-08 18:49:52 -07009650 }
9651 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9652 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009653 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009654 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009655 status = BAD_VALUE;
9656 } else {
9657 channelMask = mask;
9658 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009659 }
Eric Laurent10351942014-05-08 18:49:52 -07009660 }
9661 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9662 // do not accept frame count changes if tracks are open as the track buffer
9663 // size depends on frame count and correct behavior would not be guaranteed
9664 // if frame count is changed after track creation
9665 if (mActiveTracks.size() > 0) {
9666 status = INVALID_OPERATION;
9667 } else {
9668 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009669 }
Eric Laurent10351942014-05-08 18:49:52 -07009670 }
9671 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009672 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009673 }
9674 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9675 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009676 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009677 }
Glenn Kastene198c362013-08-13 09:13:36 -07009678
Eric Laurent10351942014-05-08 18:49:52 -07009679 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009680 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009681 if (status == INVALID_OPERATION) {
9682 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009683 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009684 }
9685 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009686 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009687 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9688 if (mInput->stream->getAudioProperties(&config) == OK &&
9689 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9690 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009691 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009692 status = NO_ERROR;
9693 }
Eric Laurent81784c32012-11-19 14:55:58 -08009694 }
Eric Laurent10351942014-05-08 18:49:52 -07009695 if (status == NO_ERROR) {
9696 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009697 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009698 }
9699 }
Eric Laurent81784c32012-11-19 14:55:58 -08009700 }
Eric Laurent10351942014-05-08 18:49:52 -07009701
Eric Laurent81784c32012-11-19 14:55:58 -08009702 return reconfig;
9703}
9704
Andy Hungee58e4a2023-07-07 13:47:37 -07009705String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009706{
Andy Hung972bec12023-08-31 16:13:39 -07009707 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009708 if (initCheck() == NO_ERROR) {
9709 String8 out_s8;
9710 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9711 return out_s8;
9712 }
Eric Laurent81784c32012-11-19 14:55:58 -08009713 }
Andy Hung920f6572022-10-06 12:09:49 -07009714 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009715}
9716
Andy Hungab65b182023-09-06 19:41:47 -07009717void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009718 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009719 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009720 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009721 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009722 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009723 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009724 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9725 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009726 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009727 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009728 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009729 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009730 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009731 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009732 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009733 break;
9734 }
Andy Hungab65b182023-09-06 19:41:47 -07009735 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009736}
9737
Andy Hungee58e4a2023-07-07 13:47:37 -07009738void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009739{
Dean Wheatley6c009512023-10-23 09:34:14 +11009740 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9741 mSampleRate = audioConfig.sample_rate;
9742 mChannelMask = audioConfig.channel_mask;
9743 if (!audio_is_input_channel(mChannelMask)) {
9744 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9745 }
9746
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009747 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009748
9749 // Get actual HAL format.
9750 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9751 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9752 // Get format from the shim, which will be different than the HAL format
9753 // if recording compressed audio from IEC61937 wrapped sources.
9754 mFormat = audioConfig.format;
9755 if (!audio_is_valid_format(mFormat)) {
9756 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9757 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009758 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009759 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9760 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009761 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009762 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009763 ALOGI("HAL format %#x is not linear pcm", mFormat);
9764 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009765 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009766 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9767 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009768 result = mInput->stream->getBufferSize(&mBufferSize);
9769 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009770 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009771 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9772 "mBufferSize=%zu, mFrameCount=%zu",
9773 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009774
Eric Laurentec376dc2021-04-08 20:41:22 +02009775 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9776 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009777 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009778
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009779 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9780 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009781
9782 audio_input_flags_t flags = mInput->flags;
9783 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9784 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009785 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009786 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9787 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9788 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9789 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9790 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9791 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009792}
9793
Andy Hungee58e4a2023-07-07 13:47:37 -07009794uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009795{
Andy Hung972bec12023-08-31 16:13:39 -07009796 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009797 uint32_t result;
9798 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9799 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009800 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009801 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009802}
9803
Andy Hungee58e4a2023-07-07 13:47:37 -07009804KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009805{
Glenn Kastend848eb42016-03-08 13:42:11 -08009806 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009807 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009808 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009809 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009810 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009811 if (ids.indexOfKey(sessionId) < 0) {
9812 ids.add(sessionId, true);
9813 }
9814 }
9815 return ids;
9816}
9817
Andy Hungee58e4a2023-07-07 13:47:37 -07009818AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009819{
Andy Hung972bec12023-08-31 16:13:39 -07009820 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009821 AudioStreamIn *input = mInput;
9822 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009823 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009824 return input;
9825}
9826
Andy Hungc5007f82023-08-29 14:26:09 -07009827// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009828sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009829{
9830 if (mInput == NULL) {
9831 return NULL;
9832 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009833 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009834}
9835
Andy Hungee58e4a2023-07-07 13:47:37 -07009836status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009837{
Eric Laurent81784c32012-11-19 14:55:58 -08009838 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009839 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009840 chain->setInBuffer(NULL);
9841 chain->setOutBuffer(NULL);
9842
9843 checkSuspendOnAddEffectChain_l(chain);
9844
Eric Laurent1b928682014-10-02 19:41:47 -07009845 // make sure enabled pre processing effects state is communicated to the HAL as we
9846 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009847 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009848
Eric Laurent81784c32012-11-19 14:55:58 -08009849 mEffectChains.add(chain);
9850
9851 return NO_ERROR;
9852}
9853
Andy Hungee58e4a2023-07-07 13:47:37 -07009854size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009855{
9856 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009857
9858 for (size_t i = 0; i < mEffectChains.size(); i++) {
9859 if (chain == mEffectChains[i]) {
9860 mEffectChains.removeAt(i);
9861 break;
9862 }
Eric Laurent81784c32012-11-19 14:55:58 -08009863 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009864 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009865}
9866
Andy Hungee58e4a2023-07-07 13:47:37 -07009867status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009868 audio_patch_handle_t *handle)
9869{
9870 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009871
9872 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009873 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009874 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009875 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009876 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009877 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009878 }
9879
Eric Laurentd8365c52017-07-16 15:27:05 -07009880 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009881
9882 // store new source and send to effects
9883 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9884 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009885 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009886 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009887 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009888 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009889
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009890 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009891 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9892 status = hwDevice->createAudioPatch(patch->num_sources,
9893 patch->sources,
9894 patch->num_sinks,
9895 patch->sinks,
9896 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009897 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009898 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9899 patch->sinks[0].ext.mix.usecase.source,
9900 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009901 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009902 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009903
jiabinc52b1ff2019-10-31 17:20:42 -07009904 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009905 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009906 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009907 }
Eric Laurent296fb132015-05-01 11:38:42 -07009908
Andy Hungc2b11cb2020-04-22 09:04:01 -07009909 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009910 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009911 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009912 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009913 // also dispatch to active AudioRecords
9914 for (const auto &track : mActiveTracks) {
9915 track->logEndInterval();
9916 track->logBeginInterval(pathSourcesAsString);
9917 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009918 // Force meteadata update after a route change
9919 mActiveTracks.setHasChanged();
9920
Eric Laurent1c333e22014-05-20 10:48:17 -07009921 return status;
9922}
9923
Andy Hungee58e4a2023-07-07 13:47:37 -07009924status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009925{
9926 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009927
jiabinc52b1ff2019-10-31 17:20:42 -07009928 mPatch = audio_patch{};
9929 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009930
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009931 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009932 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9933 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009934 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009935 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009936 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009937 // Force meteadata update after a route change
9938 mActiveTracks.setHasChanged();
9939
Eric Laurent1c333e22014-05-20 10:48:17 -07009940 return status;
9941}
9942
Andy Hungee58e4a2023-07-07 13:47:37 -07009943void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009944{
Andy Hung972bec12023-08-31 16:13:39 -07009945 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009946 mOutDevices = outDevices;
9947 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9948 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009949 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009950 }
9951}
9952
Andy Hungee58e4a2023-07-07 13:47:37 -07009953int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009954{
9955 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009956 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009957 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009958 int32_t oldestFront = mRsmpInRear;
9959 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009960 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009961 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009962 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009963 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009964 if (filled > maxFilled) {
9965 oldestFront = front;
9966 maxFilled = filled;
9967 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009968 }
Andy Hung920f6572022-10-06 12:09:49 -07009969 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009970 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9971 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009972 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009973}
9974
Andy Hungee58e4a2023-07-07 13:47:37 -07009975void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009976{
9977 if (offset == 0) {
9978 return;
9979 }
9980 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009981 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009982 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009983 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009984 }
9985}
9986
Andy Hungee58e4a2023-07-07 13:47:37 -07009987void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009988{
9989 // This is the formula for calculating the temporary buffer size.
9990 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9991 // 1 full output buffer, regardless of the alignment of the available input.
9992 // The value is somewhat arbitrary, and could probably be even larger.
9993 // A larger value should allow more old data to be read after a track calls start(),
9994 // without increasing latency.
9995 //
9996 // Note this is independent of the maximum downsampling ratio permitted for capture.
9997 size_t minRsmpInFrames = mFrameCount * 7;
9998
9999 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10000 // capture history available to another client using the same session ID:
10001 // dimension the resampler input buffer accordingly.
10002
10003 // Get oldest client read position: getOldestFront_l() must be called before altering
10004 // mRsmpInRear, or mRsmpInFrames
10005 int32_t previousFront = getOldestFront_l();
10006 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10007 int32_t previousRear = mRsmpInRear;
10008 mRsmpInRear = 0;
10009
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010010 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010011 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010012 "resizeInputBuffer_l() called with invalid max shared history %d",
10013 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010014 if (maxSharedAudioHistoryMs != 0) {
10015 // resizeInputBuffer_l should never be called with a non zero shared history if the
10016 // buffer was not already allocated
10017 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10018 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10019 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10020 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010021 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010022 return;
10023 }
10024 mRsmpInFrames = rsmpInFrames;
10025 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010026 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010027 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10028 // initialized
10029 if (mRsmpInFrames < minRsmpInFrames) {
10030 mRsmpInFrames = minRsmpInFrames;
10031 }
10032 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10033
10034 // TODO optimize audio capture buffer sizes ...
10035 // Here we calculate the size of the sliding buffer used as a source
10036 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10037 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10038 // be better to have it derived from the pipe depth in the long term.
10039 // The current value is higher than necessary. However it should not add to latency.
10040
10041 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10042 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10043
10044 void *rsmpInBuffer;
10045 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10046 // if posix_memalign fails, will segv here.
10047 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10048
10049 // Copy audio history if any from old buffer before freeing it
10050 if (previousRear != 0) {
10051 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10052 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10053
10054 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10055 previousFront &= previousRsmpInFramesP2 - 1;
10056 size_t part1 = previousRsmpInFramesP2 - previousFront;
10057 if (part1 > (size_t) unread) {
10058 part1 = unread;
10059 }
10060 if (part1 != 0) {
10061 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10062 part1 * mFrameSize);
10063 mRsmpInRear = part1;
10064 part1 = unread - part1;
10065 if (part1 != 0) {
10066 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10067 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10068 mRsmpInRear += part1;
10069 }
10070 }
10071 // Update front for all clients according to new rear
10072 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10073 } else {
10074 mRsmpInRear = 0;
10075 }
10076 free(mRsmpInBuffer);
10077 mRsmpInBuffer = rsmpInBuffer;
10078}
10079
Andy Hungee58e4a2023-07-07 13:47:37 -070010080void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010081{
Andy Hung972bec12023-08-31 16:13:39 -070010082 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010083 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010084 if (record->getSource()) {
10085 mSource = record->getSource();
10086 }
Eric Laurent83b88082014-06-20 18:31:16 -070010087}
10088
Andy Hungee58e4a2023-07-07 13:47:37 -070010089void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010090{
Andy Hung972bec12023-08-31 16:13:39 -070010091 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010092 if (mSource == record->getSource()) {
10093 mSource = mInput;
10094 }
Eric Laurent83b88082014-06-20 18:31:16 -070010095 destroyTrack_l(record);
10096}
10097
Andy Hungee58e4a2023-07-07 13:47:37 -070010098void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010099{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010100 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010101 config->role = AUDIO_PORT_ROLE_SINK;
10102 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10103 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010104 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10105 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10106 config->flags.input = mInput->flags;
10107 }
Eric Laurent83b88082014-06-20 18:31:16 -070010108}
Eric Laurent1c333e22014-05-20 10:48:17 -070010109
Eric Laurent6acd1d42017-01-04 14:23:29 -080010110// ----------------------------------------------------------------------------
10111// Mmap
10112// ----------------------------------------------------------------------------
10113
Andy Hung7aa7d102023-07-07 15:58:48 -070010114// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10115// MmapPlaybackThread or MmapCaptureThread instance.
10116class MmapThreadHandle : public MmapStreamInterface {
10117public:
10118 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10119 ~MmapThreadHandle() override;
10120
10121 // MmapStreamInterface virtuals
10122 status_t createMmapBuffer(int32_t minSizeFrames,
10123 struct audio_mmap_buffer_info* info) final;
10124 status_t getMmapPosition(struct audio_mmap_position* position) final;
10125 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10126 status_t start(const AudioClient& client,
10127 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10128 status_t stop(audio_port_handle_t handle) final;
10129 status_t standby() final;
10130 status_t reportData(const void* buffer, size_t frameCount) final;
10131private:
10132 const sp<IAfMmapThread> mThread;
10133};
10134
10135/* static */
10136sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10137 const sp<IAfMmapThread>& mmapThread) {
10138 return sp<MmapThreadHandle>::make(mmapThread);
10139}
10140
10141MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010142 : mThread(thread)
10143{
Phil Burk9fabbf82017-08-03 12:02:00 -070010144 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010145}
10146
Andy Hung7aa7d102023-07-07 15:58:48 -070010147// MmapStreamInterface could be directly implemented by MmapThread excepting this
10148// special handling on adapter dtor.
10149MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150{
Phil Burk9fabbf82017-08-03 12:02:00 -070010151 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152}
10153
Andy Hung7aa7d102023-07-07 15:58:48 -070010154status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155 struct audio_mmap_buffer_info *info)
10156{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157 return mThread->createMmapBuffer(minSizeFrames, info);
10158}
10159
Andy Hung7aa7d102023-07-07 15:58:48 -070010160status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010162 return mThread->getMmapPosition(position);
10163}
10164
Andy Hung7aa7d102023-07-07 15:58:48 -070010165status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010166 int64_t *timeNanos) {
10167 return mThread->getExternalPosition(position, timeNanos);
10168}
10169
Andy Hung7aa7d102023-07-07 15:58:48 -070010170status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010171 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010172{
jiabind1f1cb62020-03-24 11:57:57 -070010173 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174}
10175
Andy Hung7aa7d102023-07-07 15:58:48 -070010176status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010177{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 return mThread->stop(handle);
10179}
10180
Andy Hung7aa7d102023-07-07 15:58:48 -070010181status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010182{
Eric Laurent18b57012017-02-13 16:23:52 -080010183 return mThread->standby();
10184}
10185
Andy Hung7aa7d102023-07-07 15:58:48 -070010186status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10187{
jiabinfc791ee2023-02-15 19:43:40 +000010188 return mThread->reportData(buffer, frameCount);
10189}
10190
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191
Andy Hungee58e4a2023-07-07 13:47:37 -070010192MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010193 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010194 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010195 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010196 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010197 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010198 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010199 mActiveTracks(&this->mLocalLog),
10200 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10201 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010202{
Eric Laurent18b57012017-02-13 16:23:52 -080010203 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010204 readHalParameters_l();
10205}
10206
Andy Hungee58e4a2023-07-07 13:47:37 -070010207void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010208{
10209 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10210}
10211
Andy Hungee58e4a2023-07-07 13:47:37 -070010212void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213{
Andy Hung8d31fd22023-06-26 19:20:57 -070010214 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010215 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010216 {
Andy Hung972bec12023-08-31 16:13:39 -070010217 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010218 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010219 activeTracks.add(t);
10220 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010221 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010222 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010223 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010224 stop(t->portId());
10225 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010226 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010227 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010228 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010230 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231 }
10232}
10233
10234
Andy Hung8d672e02023-09-15 18:19:28 -070010235void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 audio_stream_type_t streamType __unused,
10237 audio_session_t sessionId,
10238 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010239 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010240 audio_port_handle_t portId)
10241{
10242 mAttr = *attr;
10243 mSessionId = sessionId;
10244 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010245 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246 mPortId = portId;
10247}
10248
Andy Hungee58e4a2023-07-07 13:47:37 -070010249status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010250 struct audio_mmap_buffer_info *info)
10251{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010252 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253 if (mHalStream == 0) {
10254 return NO_INIT;
10255 }
Eric Laurent18b57012017-02-13 16:23:52 -080010256 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257 return mHalStream->createMmapBuffer(minSizeFrames, info);
10258}
10259
Andy Hungee58e4a2023-07-07 13:47:37 -070010260status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010262 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263 if (mHalStream == 0) {
10264 return NO_INIT;
10265 }
10266 return mHalStream->getMmapPosition(position);
10267}
10268
Andy Hungee58e4a2023-07-07 13:47:37 -070010269status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010270{
Eric Laurentdda206a2022-07-08 17:28:35 +020010271 // The HAL must receive track metadata before starting the stream
10272 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010273 status_t ret = mHalStream->start();
10274 if (ret != NO_ERROR) {
10275 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10276 return ret;
10277 }
Andy Hungcf10d742020-04-28 15:38:24 -070010278 if (mStandby) {
10279 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010280 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010281 mStandby = false;
10282 }
Eric Laurent331679c2018-04-16 17:03:16 -070010283 return NO_ERROR;
10284}
10285
Andy Hungee58e4a2023-07-07 13:47:37 -070010286status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010287 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010288 audio_port_handle_t *handle)
10289{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010290 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010291 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010292 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 if (mHalStream == 0) {
10294 return NO_INIT;
10295 }
10296
10297 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298
Eric Laurentdda206a2022-07-08 17:28:35 +020010299 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010300 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010301 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010302 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010303 }
10304
10305 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10306
10307 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010308 AttributionSourceState adjAttributionSource;
10309 if (!com::android::media::audio::audioserver_permissions()) {
10310 adjAttributionSource = afutils::checkAttributionSourcePackage(
10311 client.attributionSource);
10312 } else {
10313 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10314 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10315 client.attributionSource,
10316 mAfThreadCallback->getPermissionProvider()
10317 );
10318 if (!validatedRes.has_value()) {
10319 ALOGE("MMAP client package validation fail: %s",
10320 validatedRes.error().toString8().c_str());
10321 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10322 }
10323 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10324 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010325
Andy Hung3f49ebb2023-09-19 14:48:41 -070010326 const auto localSessionId = mSessionId;
10327 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010328 if (isOutput()) {
10329 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10330 config.sample_rate = mSampleRate;
10331 config.channel_mask = mChannelMask;
10332 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010333 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010334 audio_output_flags_t flags =
10335 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010336 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010337 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010338 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010339 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010340 mutex().unlock();
10341 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10342 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010343 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010344 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010345 &config,
10346 flags,
10347 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010348 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010349 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010350 &isSpatialized,
Eric Laurent277a37e2024-07-29 18:37:52 +000010351 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010352 mutex().lock();
10353 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010354 ALOGD_IF(!secondaryOutputs.empty(),
10355 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010357 audio_config_base_t config;
10358 config.sample_rate = mSampleRate;
10359 config.channel_mask = mChannelMask;
10360 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010361 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010362 mutex().unlock();
10363 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010364 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010365 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010366 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010367 &config,
10368 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10369 &deviceId,
10370 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010371 mutex().lock();
10372 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010373 }
10374 // APM should not chose a different input or output stream for the same set of attributes
10375 // and audo configuration
10376 if (ret != NO_ERROR || io != mId) {
10377 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10378 __FUNCTION__, ret, io, mId);
10379 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 }
10381
10382 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010383 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010384 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010385 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010386 } else {
jiabin09609032022-06-15 19:26:01 +000010387 {
10388 // Add the track record before starting input so that the silent status for the
10389 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010390 setClientSilencedState_l(portId, false /*silenced*/);
10391 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010392 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010393 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010394 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010395 }
10396
10397 // abort if start is rejected by audio policy manager
10398 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010399 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010400 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010401 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010403 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010404 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010405 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406 }
Andy Hungc5007f82023-08-29 14:26:09 -070010407 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010408 } else {
10409 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010410 }
jiabin09609032022-06-15 19:26:01 +000010411 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010412 return PERMISSION_DENIED;
10413 }
10414
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010415 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010416 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10417 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010418 mChannelMask, mSessionId, isOutput(),
10419 client.attributionSource,
Eric Laurent277a37e2024-07-29 18:37:52 +000010420 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010421 if (!isOutput()) {
10422 track->setSilenced_l(isClientSilenced_l(portId));
10423 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010424
Eric Laurent4eb58f12018-12-07 16:41:02 -080010425 if (isOutput()) {
10426 // force volume update when a new track is added
10427 mHalVolFloat = -1.0f;
10428 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010429 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010430 if (t->isSilenced_l()
10431 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010432 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010433 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010434 }
10435 }
10436
Eric Laurent6acd1d42017-01-04 14:23:29 -080010437 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010438 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010439 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010440 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010441 chain->incTrackCnt();
10442 chain->incActiveTrackCnt();
10443 }
10444
Andy Hungc2b11cb2020-04-22 09:04:01 -070010445 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010446 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010447
10448 if (mActiveTracks.size() == 1) {
10449 ret = exitStandby_l();
10450 }
10451
Eric Laurent6acd1d42017-01-04 14:23:29 -080010452 broadcast_l();
10453
Eric Laurentdda206a2022-07-08 17:28:35 +020010454 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010455
Eric Laurentdda206a2022-07-08 17:28:35 +020010456 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457}
10458
Andy Hungee58e4a2023-07-07 13:47:37 -070010459status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010460{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010462 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010463
10464 if (mHalStream == 0) {
10465 return NO_INIT;
10466 }
10467
Eric Laurenta54f1282017-07-01 19:39:32 -070010468 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010469 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010470 return NO_ERROR;
10471 }
10472
Andy Hung8d31fd22023-06-26 19:20:57 -070010473 sp<IAfMmapTrack> track;
10474 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010475 if (handle == t->portId()) {
10476 track = t;
10477 break;
10478 }
10479 }
10480 if (track == 0) {
10481 return BAD_VALUE;
10482 }
10483
10484 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010485 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486
Andy Hungc5007f82023-08-29 14:26:09 -070010487 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010488 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010489 AudioSystem::stopOutput(track->portId());
10490 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010492 AudioSystem::stopInput(track->portId());
10493 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494 }
Andy Hungc5007f82023-08-29 14:26:09 -070010495 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496
Andy Hung116bc262023-06-20 18:56:17 -070010497 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010498 if (chain != 0) {
10499 chain->decActiveTrackCnt();
10500 chain->decTrackCnt();
10501 }
10502
Eric Laurentdda206a2022-07-08 17:28:35 +020010503 if (mActiveTracks.isEmpty()) {
10504 mHalStream->stop();
10505 }
10506
Eric Laurent6acd1d42017-01-04 14:23:29 -080010507 broadcast_l();
10508
Eric Laurent6acd1d42017-01-04 14:23:29 -080010509 return NO_ERROR;
10510}
10511
Andy Hungee58e4a2023-07-07 13:47:37 -070010512status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010513NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010514{
10515 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010516 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010517
10518 if (mHalStream == 0) {
10519 return NO_INIT;
10520 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010521 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010522 return INVALID_OPERATION;
10523 }
10524 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010525 if (!mStandby) {
10526 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010527 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010528 mStandby = true;
10529 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010530 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010531 return NO_ERROR;
10532}
10533
Andy Hungee58e4a2023-07-07 13:47:37 -070010534status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010535 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10536 return INVALID_OPERATION;
10537}
10538
Andy Hungee58e4a2023-07-07 13:47:37 -070010539void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010540{
10541 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10542 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10543 mFormat = mHALFormat;
10544 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10545 result = mHalStream->getFrameSize(&mFrameSize);
10546 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010547 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10548 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549 result = mHalStream->getBufferSize(&mBufferSize);
10550 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10551 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010552
Andy Hungcf10d742020-04-28 15:38:24 -070010553 // TODO: make a readHalParameters call?
10554 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010555 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010556 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010557 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10558 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10559 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10560 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10561 /*
10562 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10563 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10564 (int32_t)mHapticChannelMask)
10565 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10566 (int32_t)mHapticChannelCount)
10567 */
10568 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010569 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010570 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10571 (int32_t)mFrameCount) // sic - added HAL
10572 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573}
10574
Andy Hungee58e4a2023-07-07 13:47:37 -070010575bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576{
Andy Hungab65b182023-09-06 19:41:47 -070010577 {
10578 audio_utils::unique_lock _l(mutex());
10579 checkSilentMode_l();
10580 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581
10582 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10583
10584 while (!exitPending())
10585 {
Andy Hung116bc262023-06-20 18:56:17 -070010586 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010587
Andy Hung13850be2019-03-14 11:33:09 -070010588 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010589 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010590
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 if (mSignalPending) {
10592 // A signal was raised while we were unlocked
10593 mSignalPending = false;
10594 } else {
10595 if (mConfigEvents.isEmpty()) {
10596 // we're about to wait, flush the binder command buffer
10597 IPCThreadState::self()->flushCommands();
10598
10599 if (exitPending()) {
10600 break;
10601 }
10602
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010604 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010605 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010606 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607
10608 checkSilentMode_l();
10609
10610 continue;
10611 }
10612 }
10613
10614 processConfigEvents_l();
10615
10616 processVolume_l();
10617
10618 checkInvalidTracks_l();
10619
Andy Hungab65b182023-09-06 19:41:47 -070010620 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621
Kevin Rocard069c2712018-03-29 19:09:14 -070010622 updateMetadata_l();
10623
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010625 } // release Thread lock
10626
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010628 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 }
Andy Hung13850be2019-03-14 11:33:09 -070010630
10631 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632 unlockEffectChains(effectChains);
10633 // Effect chains will be actually deleted here if they were removed from
10634 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010635 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010636 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010637 mThreadloopExecutor.process(); // process any remaining deferred actions.
10638 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639
10640 threadLoop_exit();
10641
10642 if (!mStandby) {
10643 threadLoop_standby();
10644 mStandby = true;
10645 }
10646
Eric Laurent6acd1d42017-01-04 14:23:29 -080010647 ALOGV("Thread %p type %d exiting", this, mType);
10648 return false;
10649}
10650
Andy Hungc5007f82023-08-29 14:26:09 -070010651// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010652bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010653 status_t& status)
10654{
10655 AudioParameter param = AudioParameter(keyValuePair);
10656 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010657 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010659 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010661 if (sendToHal) {
10662 status = mHalStream->setParameters(keyValuePair);
10663 } else {
10664 status = NO_ERROR;
10665 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010666
10667 return false;
10668}
10669
Andy Hungee58e4a2023-07-07 13:47:37 -070010670String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671{
Andy Hung972bec12023-08-31 16:13:39 -070010672 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010673 String8 out_s8;
10674 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10675 return out_s8;
10676 }
Andy Hung920f6572022-10-06 12:09:49 -070010677 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010678}
10679
Andy Hungab65b182023-09-06 19:41:47 -070010680void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010681 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010682 sp<AudioIoDescriptor> desc;
10683 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010684 switch (event) {
10685 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010686 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010687 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010688 isInput = true;
10689 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010690 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010691 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010693 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10694 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010695 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696 case AUDIO_INPUT_CLOSED:
10697 case AUDIO_OUTPUT_CLOSED:
10698 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010699 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700 break;
10701 }
Andy Hungab65b182023-09-06 19:41:47 -070010702 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010703}
10704
Andy Hungee58e4a2023-07-07 13:47:37 -070010705status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010707NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708{
10709 status_t status = NO_ERROR;
10710
10711 // store new device and send to effects
10712 audio_devices_t type = AUDIO_DEVICE_NONE;
10713 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010714 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10715 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10716 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010717 if (isOutput()) {
10718 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010719 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10720 && !mAudioHwDev->supportsAudioPatches(),
10721 "Enumerated device type(%#x) must not be used "
10722 "as it does not support audio patches",
10723 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010724 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010725 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10726 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727 }
10728 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010729 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730 } else {
10731 type = patch->sources[0].ext.device.type;
10732 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010733 numDevices = mPatch.num_sources;
10734 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010735 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 }
10737
10738 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010739 if (isOutput()) {
10740 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10741 } else {
10742 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10743 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010744 }
10745
jiabinc52b1ff2019-10-31 17:20:42 -070010746 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010747 // store new source and send to effects
10748 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10749 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10750 for (size_t i = 0; i < mEffectChains.size(); i++) {
10751 mEffectChains[i]->setAudioSource_l(mAudioSource);
10752 }
10753 }
10754 }
10755
jiabin78b86f22024-02-22 00:39:29 +000010756 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10757 // okay to notify the client earlier before the new patch creation.
10758 if (mDeviceId != deviceId) {
10759 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10760 // The aaudioservice handle the routing changed event asynchronously. In that case,
10761 // it is safe to hold the lock here.
10762 callback->onRoutingChanged(deviceId);
10763 }
10764 }
10765
Eric Laurent6acd1d42017-01-04 14:23:29 -080010766 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010767 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10768 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010769 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010770 audio_port_config port;
10771 std::optional<audio_source_t> source;
10772 if (isOutput()) {
10773 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010775 port = patch->sources[0];
10776 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010777 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010778 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779 *handle = AUDIO_PATCH_HANDLE_NONE;
10780 }
10781
jiabinc52b1ff2019-10-31 17:20:42 -070010782 if (numDevices == 0 || mDeviceId != deviceId) {
10783 if (isOutput()) {
10784 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10785 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010786 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010787 } else {
10788 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10789 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10790 }
jiabinc52b1ff2019-10-31 17:20:42 -070010791 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010792 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010794 // Force meteadata update after a route change
10795 mActiveTracks.setHasChanged();
10796
Eric Laurent6acd1d42017-01-04 14:23:29 -080010797 return status;
10798}
10799
Andy Hungee58e4a2023-07-07 13:47:37 -070010800status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010801{
10802 status_t status = NO_ERROR;
10803
jiabinc52b1ff2019-10-31 17:20:42 -070010804 mPatch = audio_patch{};
10805 mOutDeviceTypeAddrs.clear();
10806 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010807
10808 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10809 supportsAudioPatches : false;
10810
10811 if (supportsAudioPatches) {
10812 status = mHalDevice->releaseAudioPatch(handle);
10813 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010814 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010815 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010816 // Force meteadata update after a route change
10817 mActiveTracks.setHasChanged();
10818
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819 return status;
10820}
10821
Andy Hungee58e4a2023-07-07 13:47:37 -070010822void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010823NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010825 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010826 if (isOutput()) {
10827 config->role = AUDIO_PORT_ROLE_SOURCE;
10828 config->ext.mix.hw_module = mAudioHwDev->handle();
10829 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10830 } else {
10831 config->role = AUDIO_PORT_ROLE_SINK;
10832 config->ext.mix.hw_module = mAudioHwDev->handle();
10833 config->ext.mix.usecase.source = mAudioSource;
10834 }
10835}
10836
Andy Hungee58e4a2023-07-07 13:47:37 -070010837status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010838{
10839 audio_session_t session = chain->sessionId();
10840
10841 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10842 // Attach all tracks with same session ID to this chain.
10843 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010844 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010845 if (session == track->sessionId()) {
10846 chain->incTrackCnt();
10847 chain->incActiveTrackCnt();
10848 }
10849 }
10850
10851 chain->setThread(this);
10852 chain->setInBuffer(nullptr);
10853 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010854 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010855
10856 mEffectChains.add(chain);
10857 checkSuspendOnAddEffectChain_l(chain);
10858 return NO_ERROR;
10859}
10860
Andy Hungee58e4a2023-07-07 13:47:37 -070010861size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010862{
10863 audio_session_t session = chain->sessionId();
10864
10865 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10866
10867 for (size_t i = 0; i < mEffectChains.size(); i++) {
10868 if (chain == mEffectChains[i]) {
10869 mEffectChains.removeAt(i);
10870 // detach all active tracks from the chain
10871 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010872 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010873 if (session == track->sessionId()) {
10874 chain->decActiveTrackCnt();
10875 chain->decTrackCnt();
10876 }
10877 }
10878 break;
10879 }
10880 }
10881 return mEffectChains.size();
10882}
10883
Andy Hungee58e4a2023-07-07 13:47:37 -070010884void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885{
10886 mHalStream->standby();
10887}
10888
Andy Hungee58e4a2023-07-07 13:47:37 -070010889void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010890{
Phil Burk7dce7282017-09-27 13:51:41 -070010891 // Do not call callback->onTearDown() because it is redundant for thread exit
10892 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010893}
10894
Andy Hungee58e4a2023-07-07 13:47:37 -070010895status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896{
10897 return BAD_VALUE;
10898}
10899
Andy Hungee58e4a2023-07-07 13:47:37 -070010900bool MmapThread::isValidSyncEvent(
10901 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010902{
10903 return false;
10904}
10905
Andy Hungee58e4a2023-07-07 13:47:37 -070010906status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010907 const effect_descriptor_t *desc, audio_session_t sessionId)
10908{
10909 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010910 if (audio_is_global_session(sessionId)) {
10911 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 desc->name, mThreadName);
10913 return BAD_VALUE;
10914 }
10915
10916 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10917 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10918 desc->name);
10919 return BAD_VALUE;
10920 }
10921 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010922 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10923 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010924 return BAD_VALUE;
10925 }
10926
10927 // Only allow effects without processing load or latency
10928 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10929 return BAD_VALUE;
10930 }
10931
Andy Hung116bc262023-06-20 18:56:17 -070010932 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010933 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10934 return BAD_VALUE;
10935 }
10936
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010938}
10939
Andy Hungee58e4a2023-07-07 13:47:37 -070010940void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010941{
Andy Hung8d31fd22023-06-26 19:20:57 -070010942 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010943 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010944 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10945 // The aaudioservice handle the routing changed event asynchronously. In that case,
10946 // it is safe to hold the lock here.
10947 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10948 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010949 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10950 mNoCallbackWarningCount++;
10951 }
10952 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010953 }
10954 }
10955}
10956
Andy Hungee58e4a2023-07-07 13:47:37 -070010957void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010958{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10960 mAttr.content_type, mAttr.usage, mAttr.source);
10961 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010962 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010963 dprintf(fd, " No active clients\n");
10964 }
10965}
10966
Andy Hungee58e4a2023-07-07 13:47:37 -070010967void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010968{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010970 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010971 dprintf(fd, " %zu Tracks\n", numtracks);
10972 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010973 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010974 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010975 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010977 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010978 result.append(prefix);
10979 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010980 }
10981 } else {
10982 dprintf(fd, "\n");
10983 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010984 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010985}
10986
Andy Hungee58e4a2023-07-07 13:47:37 -070010987/* static */
10988sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010989 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010990 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010991 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010992}
10993
10994MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010995 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010996 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010997 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010998 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010999 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011000{
11001 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11002 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011003 mMasterVolume = afThreadCallback->masterVolume_l();
11004 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent277a37e2024-07-29 18:37:52 +000011005
11006 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11007 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11008 mStreamTypes[stream].volume = 0.0f;
11009 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011010 }
Eric Laurent277a37e2024-07-29 18:37:52 +000011011 // Audio patch and call assistant volume are always max
11012 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11013 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11014 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11015 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
11016
Eric Laurent6acd1d42017-01-04 14:23:29 -080011017 if (mAudioHwDev) {
11018 if (mAudioHwDev->canSetMasterVolume()) {
11019 mMasterVolume = 1.0;
11020 }
11021
11022 if (mAudioHwDev->canSetMasterMute()) {
11023 mMasterMute = false;
11024 }
11025 }
11026}
11027
Andy Hungee58e4a2023-07-07 13:47:37 -070011028void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011029 audio_stream_type_t streamType,
11030 audio_session_t sessionId,
11031 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011032 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033 audio_port_handle_t portId)
11034{
Andy Hung8d672e02023-09-15 18:19:28 -070011035 audio_utils::lock_guard l(mutex());
11036 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011037 mStreamType = streamType;
11038}
11039
Andy Hungee58e4a2023-07-07 13:47:37 -070011040AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011041{
Andy Hung972bec12023-08-31 16:13:39 -070011042 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 AudioStreamOut *output = mOutput;
11044 mOutput = NULL;
11045 return output;
11046}
11047
Andy Hungee58e4a2023-07-07 13:47:37 -070011048void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011049{
Andy Hung972bec12023-08-31 16:13:39 -070011050 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051 // Don't apply master volume in SW if our HAL can do it for us.
11052 if (mAudioHwDev &&
11053 mAudioHwDev->canSetMasterVolume()) {
11054 mMasterVolume = 1.0;
11055 } else {
11056 mMasterVolume = value;
11057 }
11058}
11059
Andy Hungee58e4a2023-07-07 13:47:37 -070011060void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011061{
Andy Hung972bec12023-08-31 16:13:39 -070011062 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011063 // Don't apply master mute in SW if our HAL can do it for us.
11064 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11065 mMasterMute = false;
11066 } else {
11067 mMasterMute = muted;
11068 }
11069}
11070
Andy Hungee58e4a2023-07-07 13:47:37 -070011071void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011072{
Andy Hung972bec12023-08-31 16:13:39 -070011073 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011074 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011075 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011076 broadcast_l();
11077 }
11078}
11079
Andy Hungee58e4a2023-07-07 13:47:37 -070011080float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011081{
Andy Hung972bec12023-08-31 16:13:39 -070011082 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011083 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011084}
11085
Andy Hungee58e4a2023-07-07 13:47:37 -070011086void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011087{
Andy Hung972bec12023-08-31 16:13:39 -070011088 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011089 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011090 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011091 broadcast_l();
11092 }
11093}
11094
Andy Hungee58e4a2023-07-07 13:47:37 -070011095void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011096{
Andy Hung972bec12023-08-31 16:13:39 -070011097 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011098 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011099 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011100 track->invalidate();
11101 }
11102 broadcast_l();
11103 }
11104}
11105
Andy Hungee58e4a2023-07-07 13:47:37 -070011106void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011107{
Andy Hung972bec12023-08-31 16:13:39 -070011108 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011109 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011110 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011111 if (portIds.find(track->portId()) != portIds.end()) {
11112 track->invalidate();
11113 trackMatch = true;
11114 portIds.erase(track->portId());
11115 }
11116 if (portIds.empty()) {
11117 break;
11118 }
11119 }
11120 if (trackMatch) {
11121 broadcast_l();
11122 }
11123}
11124
Andy Hungee58e4a2023-07-07 13:47:37 -070011125void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011126NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011127{
Eric Laurent277a37e2024-07-29 18:37:52 +000011128 float volume;
11129
11130 if (mMasterMute || streamMuted_l()) {
11131 volume = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011132 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +000011133 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011134 }
Eric Laurent277a37e2024-07-29 18:37:52 +000011135
Eric Laurent6acd1d42017-01-04 14:23:29 -080011136 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011137 // Convert volumes from float to 8.24
11138 uint32_t vol = (uint32_t)(volume * (1 << 24));
11139
11140 // Delegate volume control to effect in track effect chain if needed
11141 // only one effect chain can be present on DirectOutputThread, so if
11142 // there is one, the track is connected to it
11143 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011144 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011145 volume = (float)vol / (1 << 24);
11146 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011147 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011148 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11149 mHalVolFloat = volume; // HW volume control worked, so update value.
11150 mNoCallbackWarningCount = 0;
11151 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011152 sp<MmapStreamCallback> callback = mCallback.promote();
11153 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011154 mHalVolFloat = volume; // SW volume control worked, so update value.
11155 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011156 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011157 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011158 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011159 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011160 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11161 ALOGW("Could not set MMAP stream volume: no volume callback!");
11162 mNoCallbackWarningCount++;
11163 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011164 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011165 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011166 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011167 track->setMetadataHasChanged();
Eric Laurent277a37e2024-07-29 18:37:52 +000011168 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11169 /*muteState=*/{mMasterMute,
11170 streamVolume_l() == 0.f,
11171 streamMuted_l(),
11172 // TODO(b/241533526): adjust logic to include mute from AppOps
11173 false /*muteFromPlaybackRestricted*/,
11174 false /*muteFromClientVolume*/,
11175 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011176 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011177 }
11178}
11179
Andy Hungee58e4a2023-07-07 13:47:37 -070011180ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011181{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011182 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011183 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011184 }
11185 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011186 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011187 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011188 playback_track_metadata_v7_t trackMetadata;
11189 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011190 .usage = track->attributes().usage,
11191 .content_type = track->attributes().content_type,
11192 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011193 };
11194 trackMetadata.channel_mask = track->channelMask(),
11195 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11196 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011197 }
11198 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011199
11200 MetadataUpdate change;
11201 change.playbackMetadataUpdate = metadata.tracks;
11202 return change;
11203};
Kevin Rocard069c2712018-03-29 19:09:14 -070011204
Andy Hungee58e4a2023-07-07 13:47:37 -070011205void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011206{
11207 if (!mMasterMute) {
11208 char value[PROPERTY_VALUE_MAX];
11209 if (property_get("ro.audio.silent", value, "0") > 0) {
11210 char *endptr;
11211 unsigned long ul = strtoul(value, &endptr, 0);
11212 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011213 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011214 // The setprop command will not allow a property to be changed after
11215 // the first time it is set, so we don't have to worry about un-muting.
11216 setMasterMute_l(true);
11217 }
11218 }
11219 }
11220}
11221
Andy Hungee58e4a2023-07-07 13:47:37 -070011222void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011223{
11224 MmapThread::toAudioPortConfig(config);
11225 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11226 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11227 config->flags.output = mOutput->flags;
11228 }
11229}
11230
Andy Hungee58e4a2023-07-07 13:47:37 -070011231status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011232 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011233{
11234 if (mOutput == nullptr) {
11235 return NO_INIT;
11236 }
11237 struct timespec timestamp;
11238 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11239 if (status == NO_ERROR) {
11240 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11241 }
11242 return status;
11243}
11244
Andy Hungee58e4a2023-07-07 13:47:37 -070011245status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011246 // Send to MelProcessor for sound dose measurement.
11247 auto processor = mMelProcessor.load();
11248 if (processor) {
11249 processor->process(buffer, frameCount * mFrameSize);
11250 }
11251
jiabinfc791ee2023-02-15 19:43:40 +000011252 return NO_ERROR;
11253}
11254
Andy Hungc5007f82023-08-29 14:26:09 -070011255// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011256void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011257 const sp<audio_utils::MelProcessor>& processor)
11258{
11259 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011260 mMelProcessor.store(processor);
11261 if (processor) {
11262 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011263 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011264
11265 // no need to update output format for MMapPlaybackThread since it is
11266 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011267}
11268
Andy Hungc5007f82023-08-29 14:26:09 -070011269// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011270void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011271{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011272 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11273 auto melProcessor = mMelProcessor.load();
11274 if (melProcessor != nullptr) {
11275 melProcessor->pause();
11276 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011277}
11278
Andy Hungee58e4a2023-07-07 13:47:37 -070011279void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011280{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011281 MmapThread::dumpInternals_l(fd, args);
Eric Laurent277a37e2024-07-29 18:37:52 +000011282
11283 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11284 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011285 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11286}
11287
Andy Hungee58e4a2023-07-07 13:47:37 -070011288/* static */
11289sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011290 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011291 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011292 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011293}
11294
11295MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011296 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011297 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011298 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011299 mInput(input)
11300{
11301 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11302 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11303}
11304
Andy Hungee58e4a2023-07-07 13:47:37 -070011305status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011306{
Phil Burkf054fc32018-12-06 09:45:59 -080011307 {
11308 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011309 if (mInput != nullptr && mInput->stream != nullptr) {
11310 mInput->stream->setGain(1.0f);
11311 }
11312 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011313 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011314}
11315
Andy Hungee58e4a2023-07-07 13:47:37 -070011316AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011317{
Andy Hung972bec12023-08-31 16:13:39 -070011318 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011319 AudioStreamIn *input = mInput;
11320 mInput = NULL;
11321 return input;
11322}
Kevin Rocard069c2712018-03-29 19:09:14 -070011323
Andy Hungee58e4a2023-07-07 13:47:37 -070011324void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011325{
11326 bool changed = false;
11327 bool silenced = false;
11328
11329 sp<MmapStreamCallback> callback = mCallback.promote();
11330 if (callback == 0) {
11331 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11332 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11333 mNoCallbackWarningCount++;
11334 }
11335 }
11336
11337 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11338 // track is silenced and unmute otherwise
11339 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11340 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11341 changed = true;
11342 silenced = mActiveTracks[i]->isSilenced_l();
11343 }
11344 }
11345
11346 if (changed) {
11347 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11348 }
11349}
11350
Andy Hungee58e4a2023-07-07 13:47:37 -070011351ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011352{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011353 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011354 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011355 }
11356 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011357 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011358 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011359 record_track_metadata_v7_t trackMetadata;
11360 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011361 .source = track->attributes().source,
11362 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011363 };
11364 trackMetadata.channel_mask = track->channelMask(),
11365 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11366 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011367 }
11368 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011369 MetadataUpdate change;
11370 change.recordMetadataUpdate = metadata.tracks;
11371 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011372}
11373
Andy Hungee58e4a2023-07-07 13:47:37 -070011374void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011375{
Andy Hung972bec12023-08-31 16:13:39 -070011376 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011377 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011378 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011379 mActiveTracks[i]->setSilenced_l(silenced);
11380 broadcast_l();
11381 }
11382 }
jiabin09609032022-06-15 19:26:01 +000011383 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011384}
11385
Andy Hungee58e4a2023-07-07 13:47:37 -070011386void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011387{
11388 MmapThread::toAudioPortConfig(config);
11389 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11390 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11391 config->flags.input = mInput->flags;
11392 }
11393}
11394
Andy Hungee58e4a2023-07-07 13:47:37 -070011395status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011396 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011397{
11398 if (mInput == nullptr) {
11399 return NO_INIT;
11400 }
11401 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11402}
11403
jiabinc658e452022-10-21 20:52:21 +000011404// ----------------------------------------------------------------------------
11405
Andy Hungee58e4a2023-07-07 13:47:37 -070011406/* static */
11407sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011408 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011409 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011410 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011411}
11412
Andy Hung583043b2023-07-17 17:05:00 -070011413BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011414 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011415 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011416
Andy Hungee58e4a2023-07-07 13:47:37 -070011417PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011418 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011419 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11420 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011421 float volumeLeft = 1.0f;
11422 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011423 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11424 bitPerfectTrack != nullptr) {
11425 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011426 mAudioMixer->setParameter(
11427 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11428 mAudioMixer->setParameter(
11429 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11430 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011431 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011432 mIsBitPerfect = true;
11433 } else {
11434 mIsBitPerfect = false;
11435 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11436 // active.
11437 for (const auto& track : mActiveTracks) {
11438 const int trackId = track->id();
11439 mAudioMixer->setParameter(
11440 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11441 }
11442 }
jiabin76d94692022-12-15 21:51:21 +000011443 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11444 mVolumeLeft = volumeLeft;
11445 mVolumeRight = volumeRight;
11446 setVolumeForOutput_l(volumeLeft, volumeRight);
11447 }
jiabinc658e452022-10-21 20:52:21 +000011448 return result;
11449}
11450
Andy Hungee58e4a2023-07-07 13:47:37 -070011451void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011452 MixerThread::threadLoop_mix();
11453 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11454}
11455
jiabin220eea12024-05-17 17:55:20 +000011456void BitPerfectThread::setTracksInternalMute(
11457 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11458 for (auto& track : mTracks) {
11459 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11460 track->setInternalMute(it->second);
11461 tracksInternalMute->erase(it);
11462 }
11463 }
11464}
11465
11466sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11467 if (com::android::media::audioserver::
11468 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11469 sp<IAfTrack> bitPerfectTrack = nullptr;
11470 bool allOtherTracksMuted = true;
11471 // Return the bit perfect track if all other tracks are muted
11472 for (const auto& track : mActiveTracks) {
11473 if (track->isBitPerfect()) {
11474 bitPerfectTrack = track;
11475 } else if (track->getFinalVolume() != 0.f) {
11476 allOtherTracksMuted = false;
11477 if (bitPerfectTrack != nullptr) {
11478 break;
11479 }
11480 }
11481 }
11482 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11483 } else {
11484 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11485 return mActiveTracks[0];
11486 }
11487 }
11488 return nullptr;
11489}
11490
Glenn Kasten63238ef2015-03-02 15:50:29 -080011491} // namespace android