blob: 82f68df393907ad372d0b7ce683181104b941336 [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>
Andy Hung6b137d12024-08-27 22:35:17 +000052#include <com_android_media_audioserver.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070053#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080054#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070055#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070056#include <media/AudioContainers.h>
57#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070058#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070059#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070060#ifdef ADD_BATTERY_DATA
61#include <media/IMediaPlayerService.h>
62#include <media/IMediaDeathNotifier.h>
63#endif
64#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080065#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070066#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070067#include <media/audiohal/EffectsFactoryHalInterface.h>
68#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070069#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070#include <media/nbaio/AudioStreamOutSink.h>
71#include <media/nbaio/MonoPipe.h>
72#include <media/nbaio/MonoPipeReader.h>
73#include <media/nbaio/Pipe.h>
74#include <media/nbaio/PipeReader.h>
75#include <media/nbaio/SourceAudioBufferProvider.h>
Atneya Nair5997a652024-06-14 17:24:45 -070076#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080077#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070078#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070079#include <mediautils/SchedulingPolicyService.h>
80#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070081#include <powermanager/PowerManager.h>
82#include <private/android_filesystem_config.h>
83#include <private/media/AudioTrackShared.h>
Andy Hung88a7afe2024-08-12 20:00:46 -070084#include <psh_utils/AudioPowerManager.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070085#include <system/audio_effects/effect_aec.h>
86#include <system/audio_effects/effect_downmix.h>
87#include <system/audio_effects/effect_ns.h>
88#include <system/audio_effects/effect_spatializer.h>
89#include <utils/Log.h>
90#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091
Andy Hung25a80ac2023-07-19 12:47:35 -070092#include <fcntl.h>
93#include <linux/futex.h>
94#include <math.h>
95#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070097#include <sstream>
98#include <string>
99#include <sys/stat.h>
100#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102// ----------------------------------------------------------------------------
103
104// Note: the following macro is used for extremely verbose logging message. In
105// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
106// 0; but one side effect of this is to turn all LOGV's as well. Some messages
107// are so verbose that we want to suppress them even when we have ALOG_ASSERT
108// turned on. Do not uncomment the #def below unless you really know what you
109// are doing and want to see all of the extremely verbose messages.
110//#define VERY_VERY_VERBOSE_LOGGING
111#ifdef VERY_VERY_VERBOSE_LOGGING
112#define ALOGVV ALOGV
113#else
114#define ALOGVV(a...) do { } while(0)
115#endif
116
Andy Hung6770c6f2015-04-07 13:43:36 -0700117// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700118#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700119
Andy Hung6770c6f2015-04-07 13:43:36 -0700120template <typename T>
121static inline T min(const T& a, const T& b)
122{
123 return a < b ? a : b;
124}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700125
Atneya Nair5997a652024-06-14 17:24:45 -0700126using com::android::media::permission::ValidatedAttributionSourceState;
Andy Hung6b137d12024-08-27 22:35:17 +0000127namespace audioserver_flags = com::android::media::audioserver;
Atneya Nair5997a652024-06-14 17:24:45 -0700128
Eric Laurent81784c32012-11-19 14:55:58 -0800129namespace android {
130
Andy Hungee58e4a2023-07-07 13:47:37 -0700131using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700132using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000133using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700134
Andy Hung25a80ac2023-07-19 12:47:35 -0700135// Keep in sync with java definition in media/java/android/media/AudioRecord.java
136static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
137
Eric Laurent81784c32012-11-19 14:55:58 -0800138// retry counts for buffer fill timeout
139// 50 * ~20msecs = 1 second
140static const int8_t kMaxTrackRetries = 50;
141static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700142
Eric Laurent81784c32012-11-19 14:55:58 -0800143// allow less retry attempts on direct output thread.
144// direct outputs can be a scarce resource in audio hardware and should
145// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700146// Notes:
147// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
148// in case the data write is bursty for the AudioTrack. The application
149// should endeavor to write at least once every kMaxTrackRetriesDirectMs
150// to prevent an underrun situation. If the data is bursty, then
151// the application can also throttle the data sent to be even.
152// 2) For compressed audio data, any data present in the AudioTrack buffer
153// will be sent and reset the retry count. This delivers data as
154// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
155// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
156// of data to be available, then any remaining data is delivered.
157// This is required to ensure the last bit of data is delivered before underrun.
158//
159// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
160// or the size of the HAL period for proportional / linear PCM tracks.
161static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800162
163// don't warn about blocked writes or record buffer overflows more often than this
164static const nsecs_t kWarningThrottleNs = seconds(5);
165
166// RecordThread loop sleep time upon application overrun or audio HAL read error
167static const int kRecordThreadSleepUs = 5000;
168
Eric Laurent10351942014-05-08 18:49:52 -0700169// maximum time to wait in sendConfigEvent_l() for a status to be received
170static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent3fddffe2024-07-31 14:18:34 +0000171// longer timeout for create audio patch to account for specific scenarii
172// with Bluetooth devices
173static const nsecs_t kCreatePatchEventTimeoutNs = seconds(4);
Eric Laurent81784c32012-11-19 14:55:58 -0800174
175// minimum sleep time for the mixer thread loop when tracks are active but in underrun
176static const uint32_t kMinThreadSleepTimeUs = 5000;
177// maximum divider applied to the active sleep time in the mixer thread loop
178static const uint32_t kMaxThreadSleepTimeShift = 2;
179
Andy Hung09a50072014-02-27 14:30:47 -0800180// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700181// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800182static const uint32_t kMinNormalSinkBufferSizeMs = 20;
183// maximum normal sink buffer size
184static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800185
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700186// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
187// FIXME This should be based on experimentally observed scheduling jitter
188static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
189
Eric Laurent972a1732013-09-04 09:42:59 -0700190// Offloaded output thread standby delay: allows track transition without going to standby
191static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
192
Eric Laurent51716182016-02-29 18:00:56 -0800193// Direct output thread minimum sleep time in idle or active(underrun) state
194static const nsecs_t kDirectMinSleepTimeUs = 10000;
195
Brian Lindahl65e90012022-07-27 18:01:07 +0200196// Minimum amount of time between checking to see if the timestamp is advancing
197// for underrun detection. If we check too frequently, we may not detect a
198// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800199static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200200
Glenn Kasten1b291842016-07-18 14:55:21 -0700201// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
202// balance between power consumption and latency, and allows threads to be scheduled reliably
203// by the CFS scheduler.
204// FIXME Express other hardcoded references to 20ms with references to this constant and move
205// it appropriately.
206#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800207
Eric Laurent81784c32012-11-19 14:55:58 -0800208// Whether to use fast mixer
209static const enum {
210 FastMixer_Never, // never initialize or use: for debugging only
211 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
212 // normal mixer multiplier is 1
213 FastMixer_Static, // initialize if needed, then use all the time if initialized,
214 // multiplier is calculated based on min & max normal mixer buffer size
215 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
216 // multiplier is calculated based on min & max normal mixer buffer size
217 // FIXME for FastMixer_Dynamic:
218 // Supporting this option will require fixing HALs that can't handle large writes.
219 // For example, one HAL implementation returns an error from a large write,
220 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
221 // We could either fix the HAL implementations, or provide a wrapper that breaks
222 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
223} kUseFastMixer = FastMixer_Static;
224
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225// Whether to use fast capture
226static const enum {
227 FastCapture_Never, // never initialize or use: for debugging only
228 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
229 FastCapture_Static, // initialize if needed, then use all the time if initialized
230} kUseFastCapture = FastCapture_Static;
231
Eric Laurent81784c32012-11-19 14:55:58 -0800232// Priorities for requestPriority
233static const int kPriorityAudioApp = 2;
234static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700235static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000236// Request real-time priority for PlaybackThread in ARC
237static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800238
Glenn Kastenea38ee72016-04-18 11:08:01 -0700239// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
240// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
241// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700242
243// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800244static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800245
Glenn Kasten03490092014-05-27 12:30:54 -0700246// The minimum and maximum allowed values
247static const int kFastTrackMultiplierMin = 1;
248static const int kFastTrackMultiplierMax = 2;
249
250// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
251static int sFastTrackMultiplier = kFastTrackMultiplier;
252
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700253// See Thread::readOnlyHeap().
254// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
255// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
256// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700257static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700258
Andy Hung25a80ac2023-07-19 12:47:35 -0700259static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700260
261static nsecs_t getStandbyTimeInNanos() {
262 static nsecs_t standbyTimeInNanos = []() {
263 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
264 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
265 ALOGI("%s: Using %d ms as standby time", __func__, ms);
266 return milliseconds(ms);
267 }();
268 return standbyTimeInNanos;
269}
270
Andy Hung81994d62023-07-20 21:44:14 -0700271// Set kEnableExtendedChannels to true to enable greater than stereo output
272// for the MixerThread and device sink. Number of channels allowed is
273// FCC_2 <= channels <= FCC_LIMIT.
274constexpr bool kEnableExtendedChannels = true;
275
276// Returns true if channel mask is permitted for the PCM sink in the MixerThread
277/* static */
278bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
279 switch (audio_channel_mask_get_representation(channelMask)) {
280 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
281 // Haptic channel mask is only applicable for channel position mask.
282 const uint32_t channelCount = audio_channel_count_from_out_mask(
283 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
284 const uint32_t maxChannelCount = kEnableExtendedChannels
285 ? FCC_LIMIT : FCC_2;
286 if (channelCount < FCC_2 // mono is not supported at this time
287 || channelCount > maxChannelCount) {
288 return false;
289 }
290 // check that channelMask is the "canonical" one we expect for the channelCount.
291 return audio_channel_position_mask_is_out_canonical(channelMask);
292 }
293 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
294 if (kEnableExtendedChannels) {
295 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
296 if (channelCount >= FCC_2 // mono is not supported at this time
297 && channelCount <= FCC_LIMIT) {
298 return true;
299 }
300 }
301 return false;
302 default:
303 return false;
304 }
305}
306
307// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
308constexpr bool kEnableExtendedPrecision = true;
309
310// Returns true if format is permitted for the PCM sink in the MixerThread
311/* static */
312bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
313 switch (format) {
314 case AUDIO_FORMAT_PCM_16_BIT:
315 return true;
316 case AUDIO_FORMAT_PCM_FLOAT:
317 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
318 case AUDIO_FORMAT_PCM_32_BIT:
319 case AUDIO_FORMAT_PCM_8_24_BIT:
320 return kEnableExtendedPrecision;
321 default:
322 return false;
323 }
324}
325
Eric Laurent81784c32012-11-19 14:55:58 -0800326// ----------------------------------------------------------------------------
327
Andy Hung25a80ac2023-07-19 12:47:35 -0700328// formatToString() needs to be exact for MediaMetrics purposes.
329// Do not use media/TypeConverter.h toString().
330/* static */
331std::string IAfThreadBase::formatToString(audio_format_t format) {
332 std::string result;
333 FormatConverter::toString(format, result);
334 return result;
335}
336
Andy Hungb68f5eb2019-12-03 16:49:17 -0800337// TODO: move all toString helpers to audio.h
338// under #ifdef __cplusplus #endif
339static std::string patchSinksToString(const struct audio_patch *patch)
340{
341 std::stringstream ss;
342 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700343 if (i > 0) {
344 ss << "|";
345 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800346 ss << "(" << toString(patch->sinks[i].ext.device.type)
347 << ", " << patch->sinks[i].ext.device.address << ")";
348 }
349 return ss.str();
350}
351
352static std::string patchSourcesToString(const struct audio_patch *patch)
353{
354 std::stringstream ss;
355 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700356 if (i > 0) {
357 ss << "|";
358 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800359 ss << "(" << toString(patch->sources[i].ext.device.type)
360 << ", " << patch->sources[i].ext.device.address << ")";
361 }
362 return ss.str();
363}
364
Andy Hung4bd53e72022-11-17 17:21:45 -0800365static std::string toString(audio_latency_mode_t mode) {
366 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000367 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
368 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800369}
370
371// Could be made a template, but other toString overloads for std::vector are confused.
372static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
373 std::string s("{ ");
374 for (const auto& e : elements) {
375 s.append(toString(e));
376 s.append(" ");
377 }
378 s.append("}");
379 return s;
380}
381
Glenn Kasten03490092014-05-27 12:30:54 -0700382static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
383
384static void sFastTrackMultiplierInit()
385{
386 char value[PROPERTY_VALUE_MAX];
387 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
388 char *endptr;
389 unsigned long ul = strtoul(value, &endptr, 0);
390 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
391 sFastTrackMultiplier = (int) ul;
392 }
393 }
394}
395
396// ----------------------------------------------------------------------------
397
Eric Laurent81784c32012-11-19 14:55:58 -0800398#ifdef ADD_BATTERY_DATA
399// To collect the amplifier usage
400static void addBatteryData(uint32_t params) {
401 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
402 if (service == NULL) {
403 // it already logged
404 return;
405 }
406
407 service->addBatteryData(params);
408}
409#endif
410
Andy Hung3f0c9022016-01-15 17:49:46 -0800411// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
412struct {
413 // call when you acquire a partial wakelock
414 void acquire(const sp<IBinder> &wakeLockToken) {
415 pthread_mutex_lock(&mLock);
416 if (wakeLockToken.get() == nullptr) {
417 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
418 } else {
419 if (mCount == 0) {
420 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
421 }
422 ++mCount;
423 }
424 pthread_mutex_unlock(&mLock);
425 }
426
427 // call when you release a partial wakelock.
428 void release(const sp<IBinder> &wakeLockToken) {
429 if (wakeLockToken.get() == nullptr) {
430 return;
431 }
432 pthread_mutex_lock(&mLock);
433 if (--mCount < 0) {
434 ALOGE("negative wakelock count");
435 mCount = 0;
436 }
437 pthread_mutex_unlock(&mLock);
438 }
439
440 // retrieves the boottime timebase offset from monotonic.
441 int64_t getBoottimeOffset() {
442 pthread_mutex_lock(&mLock);
443 int64_t boottimeOffset = mBoottimeOffset;
444 pthread_mutex_unlock(&mLock);
445 return boottimeOffset;
446 }
447
448 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
449 // and the selected timebase.
450 // Currently only TIMEBASE_BOOTTIME is allowed.
451 //
452 // This only needs to be called upon acquiring the first partial wakelock
453 // after all other partial wakelocks are released.
454 //
455 // We do an empirical measurement of the offset rather than parsing
456 // /proc/timer_list since the latter is not a formal kernel ABI.
457 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
458 int clockbase;
459 switch (timebase) {
460 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
461 clockbase = SYSTEM_TIME_BOOTTIME;
462 break;
463 default:
464 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
465 break;
466 }
467 // try three times to get the clock offset, choose the one
468 // with the minimum gap in measurements.
469 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700470 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800471 for (int i = 0; i < tries; ++i) {
472 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
473 const nsecs_t tbase = systemTime(clockbase);
474 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
475 const nsecs_t gap = tmono2 - tmono;
476 if (i == 0 || gap < bestGap) {
477 bestGap = gap;
478 measured = tbase - ((tmono + tmono2) >> 1);
479 }
480 }
481
482 // to avoid micro-adjusting, we don't change the timebase
483 // unless it is significantly different.
484 //
485 // Assumption: It probably takes more than toleranceNs to
486 // suspend and resume the device.
487 static int64_t toleranceNs = 10000; // 10 us
488 if (llabs(*offset - measured) > toleranceNs) {
489 ALOGV("Adjusting timebase offset old: %lld new: %lld",
490 (long long)*offset, (long long)measured);
491 *offset = measured;
492 }
493 }
494
495 pthread_mutex_t mLock;
496 int32_t mCount;
497 int64_t mBoottimeOffset;
498} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800499
500// ----------------------------------------------------------------------------
501// CPU Stats
502// ----------------------------------------------------------------------------
503
504class CpuStats {
505public:
506 CpuStats();
507 void sample(const String8 &title);
508#ifdef DEBUG_CPU_USAGE
509private:
510 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700511 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800512
Andy Hung16698b82018-08-01 10:48:38 -0700513 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800514
515 int mCpuNum; // thread's current CPU number
516 int mCpukHz; // frequency of thread's current CPU in kHz
517#endif
518};
519
520CpuStats::CpuStats()
521#ifdef DEBUG_CPU_USAGE
522 : mCpuNum(-1), mCpukHz(-1)
523#endif
524{
525}
526
Glenn Kasten0f11b512014-01-31 16:18:54 -0800527void CpuStats::sample(const String8 &title
528#ifndef DEBUG_CPU_USAGE
529 __unused
530#endif
531 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800532#ifdef DEBUG_CPU_USAGE
533 // get current thread's delta CPU time in wall clock ns
534 double wcNs;
535 bool valid = mCpuUsage.sampleAndEnable(wcNs);
536
537 // record sample for wall clock statistics
538 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700539 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800540 }
541
542 // get the current CPU number
543 int cpuNum = sched_getcpu();
544
545 // get the current CPU frequency in kHz
546 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
547
548 // check if either CPU number or frequency changed
549 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
550 mCpuNum = cpuNum;
551 mCpukHz = cpukHz;
552 // ignore sample for purposes of cycles
553 valid = false;
554 }
555
556 // if no change in CPU number or frequency, then record sample for cycle statistics
557 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700558 const double cycles = wcNs * cpukHz * 0.000001;
559 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800560 }
561
Eric Tan5b13ff82018-07-27 11:20:17 -0700562 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800563 // mCpuUsage.elapsed() is expensive, so don't call it every loop
564 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700565 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800566 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700567 const double perLoop = elapsed / (double) n;
568 const double perLoop100 = perLoop * 0.01;
569 const double perLoop1k = perLoop * 0.001;
570 const double mean = mWcStats.getMean();
571 const double stddev = mWcStats.getStdDev();
572 const double minimum = mWcStats.getMin();
573 const double maximum = mWcStats.getMax();
574 const double meanCycles = mHzStats.getMean();
575 const double stddevCycles = mHzStats.getStdDev();
576 const double minCycles = mHzStats.getMin();
577 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800578 mCpuUsage.resetElapsed();
579 mWcStats.reset();
580 mHzStats.reset();
581 ALOGD("CPU usage for %s over past %.1f secs\n"
582 " (%u mixer loops at %.1f mean ms per loop):\n"
583 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
584 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
585 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000586 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800587 elapsed * .000000001, n, perLoop * .000001,
588 mean * .001,
589 stddev * .001,
590 minimum * .001,
591 maximum * .001,
592 mean / perLoop100,
593 stddev / perLoop100,
594 minimum / perLoop100,
595 maximum / perLoop100,
596 meanCycles / perLoop1k,
597 stddevCycles / perLoop1k,
598 minCycles / perLoop1k,
599 maxCycles / perLoop1k);
600
601 }
602 }
603#endif
604};
605
606// ----------------------------------------------------------------------------
607// ThreadBase
608// ----------------------------------------------------------------------------
609
Glenn Kasten97b7b752014-09-28 13:04:24 -0700610// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700611const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700612{
613 switch (type) {
614 case MIXER:
615 return "MIXER";
616 case DIRECT:
617 return "DIRECT";
618 case DUPLICATING:
619 return "DUPLICATING";
620 case RECORD:
621 return "RECORD";
622 case OFFLOAD:
623 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700624 case MMAP_PLAYBACK:
625 return "MMAP_PLAYBACK";
626 case MMAP_CAPTURE:
627 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200628 case SPATIALIZER:
629 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000630 case BIT_PERFECT:
631 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700632 default:
633 return "unknown";
634 }
635}
636
Andy Hung583043b2023-07-17 17:05:00 -0700637ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700638 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800639 : Thread(false /*canCallJava*/),
640 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700641 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700642 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
643 isOut),
644 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700645 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800646 // are set by PlaybackThread::readOutputParameters_l() or
647 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700648 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700649 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700650 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800651 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700652 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800653 mSystemReady(systemReady),
654 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
Andy Hungcf10d742020-04-28 15:38:24 -0700656 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700657 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800658}
659
Andy Hungee58e4a2023-07-07 13:47:37 -0700660ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800661{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700662 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700663 mConfigEvents.clear();
664
Eric Laurent81784c32012-11-19 14:55:58 -0800665 // do not lock the mutex in destructor
666 releaseWakeLock_l();
667 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800668 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800669 binder->unlinkToDeath(mDeathRecipient);
670 }
Andy Hungd0979812019-02-21 15:51:44 -0800671
672 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800673}
674
Andy Hungee58e4a2023-07-07 13:47:37 -0700675status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700676{
677 status_t status = initCheck();
678 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800679 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700680 } else {
681 ALOGE("No working audio driver found.");
682 }
683 return status;
684}
685
Andy Hungee58e4a2023-07-07 13:47:37 -0700686void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800687{
688 ALOGV("ThreadBase::exit");
689 // do any cleanup required for exit to succeed
690 preExit();
691 {
692 // This lock prevents the following race in thread (uniprocessor for illustration):
693 // if (!exitPending()) {
694 // // context switch from here to exit()
695 // // exit() calls requestExit(), what exitPending() observes
696 // // exit() calls signal(), which is dropped since no waiters
697 // // context switch back from exit() to here
698 // mWaitWorkCV.wait(...);
699 // // now thread is hung
700 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700701 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800702 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700703 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800704 }
705 // When Thread::requestExitAndWait is made virtual and this method is renamed to
706 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700707
708 // For TimeCheck: track waiting on the thread join of getTid().
709 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
710
Eric Laurent81784c32012-11-19 14:55:58 -0800711 requestExitAndWait();
712}
713
Andy Hungee58e4a2023-07-07 13:47:37 -0700714status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800715{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000716 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700717 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800718
Eric Laurent10351942014-05-08 18:49:52 -0700719 return sendSetParameterConfigEvent_l(keyValuePairs);
720}
721
722// sendConfigEvent_l() must be called with ThreadBase::mLock held
723// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700724status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700725NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700726{
727 status_t status = NO_ERROR;
728
Eric Laurent72e3f392015-05-20 14:43:50 -0700729 if (event->mRequiresSystemReady && !mSystemReady) {
730 event->mWaitStatus = false;
731 mPendingConfigEvents.add(event);
732 return status;
733 }
Eric Laurent10351942014-05-08 18:49:52 -0700734 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700735 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700736 mWaitWorkCV.notify_one();
737 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700738 {
Andy Hungc5007f82023-08-29 14:26:09 -0700739 audio_utils::unique_lock _l(event->mutex());
Eric Laurent3fddffe2024-07-31 14:18:34 +0000740 nsecs_t timeoutNs = event->mType == CFG_EVENT_CREATE_AUDIO_PATCH ?
741 kCreatePatchEventTimeoutNs : kConfigEventTimeoutNs;
Eric Laurent10351942014-05-08 18:49:52 -0700742 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800743 if (event->mCondition.wait_for(
Eric Laurent3fddffe2024-07-31 14:18:34 +0000744 _l, std::chrono::nanoseconds(timeoutNs), getTid())
Andy Hung02ea2a02024-01-25 17:02:30 -0800745 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700746 event->mStatus = TIMED_OUT;
747 event->mWaitStatus = false;
748 }
749 }
750 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800751 }
Andy Hungc5007f82023-08-29 14:26:09 -0700752 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800753 return status;
754}
755
Andy Hungee58e4a2023-07-07 13:47:37 -0700756void ThreadBase::sendIoConfigEvent(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 Hung972bec12023-08-31 16:13:39 -0700759 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700760 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800761}
762
Andy Hungc5007f82023-08-29 14:26:09 -0700763// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700764void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700765 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800766{
Andy Hungd0979812019-02-21 15:51:44 -0800767 // The audio statistics history is exponentially weighted to forget events
768 // about five or more seconds in the past. In order to have
769 // crisper statistics for mediametrics, we reset the statistics on
770 // an IoConfigEvent, to reflect different properties for a new device.
771 mIoJitterMs.reset();
772 mLatencyMs.reset();
773 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000774 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100775 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800776
Eric Laurent09f1ed22019-04-24 17:45:17 -0700777 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700778 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800779}
780
Andy Hungee58e4a2023-07-07 13:47:37 -0700781void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700782{
Andy Hung972bec12023-08-31 16:13:39 -0700783 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800784 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700785}
786
Andy Hungc5007f82023-08-29 14:26:09 -0700787// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700788void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800789 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800790{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800791 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700792 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800793}
794
Andy Hungc5007f82023-08-29 14:26:09 -0700795// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700796status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800797{
Andy Hung2ddee192015-12-18 17:34:44 -0800798 sp<ConfigEvent> configEvent;
799 AudioParameter param(keyValuePair);
800 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700801 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800802 setMasterMono_l(value != 0);
803 if (param.size() == 1) {
804 return NO_ERROR; // should be a solo parameter - we don't pass down
805 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700806 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800807 configEvent = new SetParameterConfigEvent(param.toString());
808 } else {
809 configEvent = new SetParameterConfigEvent(keyValuePair);
810 }
Eric Laurent10351942014-05-08 18:49:52 -0700811 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700812}
813
Andy Hungee58e4a2023-07-07 13:47:37 -0700814status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700815 const struct audio_patch *patch,
816 audio_patch_handle_t *handle)
817{
Andy Hung972bec12023-08-31 16:13:39 -0700818 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700819 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
820 status_t status = sendConfigEvent_l(configEvent);
821 if (status == NO_ERROR) {
822 CreateAudioPatchConfigEventData *data =
823 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
824 *handle = data->mHandle;
825 }
826 return status;
827}
828
Andy Hungee58e4a2023-07-07 13:47:37 -0700829status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700830 const audio_patch_handle_t handle)
831{
Andy Hung972bec12023-08-31 16:13:39 -0700832 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700833 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
834 return sendConfigEvent_l(configEvent);
835}
836
Andy Hungee58e4a2023-07-07 13:47:37 -0700837status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700838 const DeviceDescriptorBaseVector& outDevices)
839{
840 if (type() != RECORD) {
841 // The update out device operation is only for record thread.
842 return INVALID_OPERATION;
843 }
Andy Hung972bec12023-08-31 16:13:39 -0700844 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700845 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
846 return sendConfigEvent_l(configEvent);
847}
848
Andy Hungee58e4a2023-07-07 13:47:37 -0700849void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200850{
851 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
852 sp<ConfigEvent> configEvent =
853 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
854 sendConfigEvent_l(configEvent);
855}
Eric Laurent1c333e22014-05-20 10:48:17 -0700856
Andy Hungee58e4a2023-07-07 13:47:37 -0700857void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200858{
Andy Hung972bec12023-08-31 16:13:39 -0700859 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200860 sendCheckOutputStageEffectsEvent_l();
861}
862
Andy Hungee58e4a2023-07-07 13:47:37 -0700863void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200864{
865 sp<ConfigEvent> configEvent =
866 (ConfigEvent *)new CheckOutputStageEffectsEvent();
867 sendConfigEvent_l(configEvent);
868}
869
Andy Hungee58e4a2023-07-07 13:47:37 -0700870void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200871{
872 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
873 sendConfigEvent_l(configEvent);
874}
875
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700876// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700877void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700878{
Eric Laurent10351942014-05-08 18:49:52 -0700879 bool configChanged = false;
880
Eric Laurent81784c32012-11-19 14:55:58 -0800881 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700882 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700883 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800884 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700885 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700886 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700887 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
888 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800889 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700890 true /*asynchronous*/);
891 if (err != 0) {
892 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700893 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700894 }
895 } break;
896 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700897 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700898 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700899 } break;
900 case CFG_EVENT_SET_PARAMETER: {
901 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
902 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
903 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700904 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000905 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700906 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700907 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700908 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700909 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700910 CreateAudioPatchConfigEventData *data =
911 (CreateAudioPatchConfigEventData *)event->mData.get();
912 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700913 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200914 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700915 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
916 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
917 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700918 } break;
919 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700920 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700921 ReleaseAudioPatchConfigEventData *data =
922 (ReleaseAudioPatchConfigEventData *)event->mData.get();
923 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700924 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200925 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700926 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
927 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
928 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
929 } break;
930 case CFG_EVENT_UPDATE_OUT_DEVICE: {
931 UpdateOutDevicesConfigEventData *data =
932 (UpdateOutDevicesConfigEventData *)event->mData.get();
933 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700934 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200935 case CFG_EVENT_RESIZE_BUFFER: {
936 ResizeBufferConfigEventData *data =
937 (ResizeBufferConfigEventData *)event->mData.get();
938 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
939 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200940
941 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
942 setCheckOutputStageEffects();
943 } break;
944
Eric Laurent68a40a82022-05-03 18:15:04 +0200945 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
946 onHalLatencyModesChanged_l();
947 } break;
948
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700949 default:
Eric Laurent10351942014-05-08 18:49:52 -0700950 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700951 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800952 }
Eric Laurent10351942014-05-08 18:49:52 -0700953 {
Andy Hung972bec12023-08-31 16:13:39 -0700954 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700955 if (event->mWaitStatus) {
956 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700957 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700958 }
959 }
960 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
961 }
962
963 if (configChanged) {
964 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800965 }
Eric Laurent81784c32012-11-19 14:55:58 -0800966}
967
Marco Nelissenb2208842014-02-07 14:00:50 -0800968String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
969 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700970 const audio_channel_representation_t representation =
971 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700972
973 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800974 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700975 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
976 if (output) {
977 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
978 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
979 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700980 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700981 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
982 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
983 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
984 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
985 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
986 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
987 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
988 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
989 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
990 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
991 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
992 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700993 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
994 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
995 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
996 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
997 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
998 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
999 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -07001000 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001001 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
1002 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001003 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
1004 } else {
1005 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
1006 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
1007 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1008 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1009 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1010 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1011 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1012 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1013 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1014 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1015 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1016 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001017 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1018 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1019 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001020 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001021 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1022 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001023 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1024 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1025 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1026 }
1027 const int len = s.length();
1028 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001029 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001030 s.unlockBuffer(len - 2); // remove trailing ", "
1031 }
1032 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001033 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001034 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1035 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1036 return s;
1037 default:
1038 s.appendFormat("unknown mask, representation:%d bits:%#x",
1039 representation, audio_channel_mask_get_bits(mask));
1040 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001041 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001042}
1043
Andy Hungee58e4a2023-07-07 13:47:37 -07001044void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001045NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001046{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001047 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1048 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1049
Andy Hungc5007f82023-08-29 14:26:09 -07001050 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001052 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001053 }
1054
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001055 dumpBase_l(fd, args);
1056 dumpInternals_l(fd, args);
1057 dumpTracks_l(fd, args);
1058 dumpEffectChains_l(fd, args);
1059
1060 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001061 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001062 }
1063
1064 dprintf(fd, " Local log:\n");
1065 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001066
1067 // --all does the statistics
1068 bool dumpAll = false;
1069 for (const auto &arg : args) {
1070 if (arg == String16("--all")) {
1071 dumpAll = true;
1072 }
1073 }
1074 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001075 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001076 if (!sched.empty()) {
1077 (void)write(fd, sched.c_str(), sched.size());
1078 }
1079 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001080}
1081
Andy Hungee58e4a2023-07-07 13:47:37 -07001082void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001083{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001084 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001086 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001088 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1089 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001090 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001091 dprintf(fd, " Channel count: %u\n", mChannelCount);
1092 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001093 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001094 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1095 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001096 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001097 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001098 size_t numConfig = mConfigEvents.size();
1099 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001100 const size_t SIZE = 256;
1101 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001102 for (size_t i = 0; i < numConfig; i++) {
1103 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001104 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001105 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001106 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001107 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001108 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001109 }
Andy Hung293558a2017-03-21 12:19:20 -07001110 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001111 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001112 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001113 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001114 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001115 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001116
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001117 // Dump timestamp statistics for the Thread types that support it.
1118 if (mType == RECORD
1119 || mType == MIXER
1120 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001121 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001122 || mType == OFFLOAD
1123 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001124 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001125 dprintf(fd, " Timestamp corrected: %s\n",
1126 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001127 }
1128
Andy Hung446f4df2019-02-21 12:26:41 -08001129 if (mLastIoBeginNs > 0) { // MMAP may not set this
1130 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1131 isOutput() ? "write" : "read",
1132 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1133 }
1134
1135 if (mProcessTimeMs.getN() > 0) {
1136 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1137 }
1138
1139 if (mIoJitterMs.getN() > 0) {
1140 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1141 isOutput() ? "write" : "read",
1142 mIoJitterMs.toString().c_str());
1143 }
1144
Andy Hunge6c37112019-02-26 17:38:10 -08001145 if (mLatencyMs.getN() > 0) {
1146 dprintf(fd, " Threadloop %s latency stats: %s\n",
1147 isOutput() ? "write" : "read",
1148 mLatencyMs.toString().c_str());
1149 }
Robert Wu06db0a32021-08-10 19:05:34 +00001150
1151 if (mMonopipePipeDepthStats.getN() > 0) {
1152 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1153 isOutput() ? "write" : "read",
1154 mMonopipePipeDepthStats.toString().c_str());
1155 }
Eric Laurent81784c32012-11-19 14:55:58 -08001156}
1157
Andy Hungee58e4a2023-07-07 13:47:37 -07001158void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001159{
1160 const size_t SIZE = 256;
1161 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001162
Marco Nelissenb2208842014-02-07 14:00:50 -08001163 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001164 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001165 write(fd, buffer, strlen(buffer));
1166
Marco Nelissenb2208842014-02-07 14:00:50 -08001167 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001168 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001169 if (chain != 0) {
1170 chain->dump(fd, args);
1171 }
1172 }
1173}
1174
Andy Hungee58e4a2023-07-07 13:47:37 -07001175void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001176{
Andy Hung972bec12023-08-31 16:13:39 -07001177 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001178 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001179}
1180
Andy Hungee58e4a2023-07-07 13:47:37 -07001181String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001182{
1183 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001184 case MIXER:
1185 return String16("AudioMix");
1186 case DIRECT:
1187 return String16("AudioDirectOut");
1188 case DUPLICATING:
1189 return String16("AudioDup");
1190 case RECORD:
1191 return String16("AudioIn");
1192 case OFFLOAD:
1193 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001194 case MMAP_PLAYBACK:
1195 return String16("MmapPlayback");
1196 case MMAP_CAPTURE:
1197 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001198 case SPATIALIZER:
1199 return String16("AudioSpatial");
jiabin10b2fb82024-09-03 17:51:35 +00001200 case BIT_PERFECT:
1201 return String16("AudioBitPerfect");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001202 default:
1203 ALOG_ASSERT(false);
1204 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001205 }
1206}
1207
Andy Hungee58e4a2023-07-07 13:47:37 -07001208void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001209{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001210 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001211 if (mPowerManager != 0) {
1212 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001213 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001214 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1215 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001216 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001217 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001218 {} /* workSource */,
1219 {} /* historyTag */);
1220 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001221 mWakeLockToken = binder;
Andy Hung88a7afe2024-08-12 20:00:46 -07001222 if (media::psh_utils::AudioPowerManager::enabled()) {
1223 mThreadToken = media::psh_utils::createAudioThreadToken(
1224 getTid(), String8(getWakeLockTag()).c_str());
1225 }
Eric Laurent81784c32012-11-19 14:55:58 -08001226 }
Chris Ye6597d732020-02-28 22:38:25 -08001227 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001228 }
Wei Jia3f273d12015-11-24 09:06:49 -08001229
Andy Hung3f0c9022016-01-15 17:49:46 -08001230 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001231 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1232 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001233}
1234
Andy Hungee58e4a2023-07-07 13:47:37 -07001235void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001236{
Andy Hung972bec12023-08-31 16:13:39 -07001237 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001238 releaseWakeLock_l();
1239}
1240
Andy Hungee58e4a2023-07-07 13:47:37 -07001241void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001242{
Andy Hung3f0c9022016-01-15 17:49:46 -08001243 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001244 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001245 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001246 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001247 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001248 }
1249 mWakeLockToken.clear();
1250 }
Andy Hung88a7afe2024-08-12 20:00:46 -07001251 mThreadToken.reset();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001252}
1253
Andy Hungee58e4a2023-07-07 13:47:37 -07001254void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001255 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001256 // use checkService() to avoid blocking if power service is not up yet
1257 sp<IBinder> binder =
1258 defaultServiceManager()->checkService(String16("power"));
1259 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001260 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001261 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001262 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001263 binder->linkToDeath(mDeathRecipient);
1264 }
1265 }
1266}
1267
Andy Hungee58e4a2023-07-07 13:47:37 -07001268void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001269 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001270
1271#if !LOG_NDEBUG
1272 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001273 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001274 s << uid << " ";
1275 }
1276 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1277#endif
1278
Andy Hung438e7572015-12-14 15:51:17 -08001279 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1280 if (mSystemReady) {
1281 ALOGE("no wake lock to update, but system ready!");
1282 } else {
1283 ALOGW("no wake lock to update, system not ready yet");
1284 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001285 return;
1286 }
1287 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001288 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001289 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1290 mWakeLockToken, uidsAsInt);
1291 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001292 }
1293}
1294
Andy Hungee58e4a2023-07-07 13:47:37 -07001295void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001296{
Andy Hung972bec12023-08-31 16:13:39 -07001297 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001298 releaseWakeLock_l();
1299 mPowerManager.clear();
1300}
1301
Andy Hungee58e4a2023-07-07 13:47:37 -07001302void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001303 const DeviceDescriptorBaseVector& outDevices __unused)
1304{
1305 ALOGE("%s should only be called in RecordThread", __func__);
1306}
1307
Andy Hungee58e4a2023-07-07 13:47:37 -07001308void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001309{
1310 ALOGE("%s should only be called in RecordThread", __func__);
1311}
1312
Andy Hungee58e4a2023-07-07 13:47:37 -07001313void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001314{
1315 sp<ThreadBase> thread = mThread.promote();
1316 if (thread != 0) {
1317 thread->clearPowerManager();
1318 }
1319 ALOGW("power manager service died !!!");
1320}
1321
Andy Hungee58e4a2023-07-07 13:47:37 -07001322void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001323 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001324{
Andy Hung116bc262023-06-20 18:56:17 -07001325 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001326 if (chain != 0) {
1327 if (type != NULL) {
1328 chain->setEffectSuspended_l(type, suspend);
1329 } else {
1330 chain->setEffectSuspendedAll_l(suspend);
1331 }
1332 }
1333
1334 updateSuspendedSessions_l(type, suspend, sessionId);
1335}
1336
Andy Hungee58e4a2023-07-07 13:47:37 -07001337void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001338{
1339 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1340 if (index < 0) {
1341 return;
1342 }
1343
1344 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1345 mSuspendedSessions.valueAt(index);
1346
1347 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001348 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001349 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001350 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001351 chain->setEffectSuspendedAll_l(true);
1352 } else {
1353 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1354 desc->mType.timeLow);
1355 chain->setEffectSuspended_l(&desc->mType, true);
1356 }
1357 }
1358 }
1359}
1360
Andy Hungee58e4a2023-07-07 13:47:37 -07001361void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001362 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001363 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001364{
1365 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1366
1367 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1368
1369 if (suspend) {
1370 if (index >= 0) {
1371 sessionEffects = mSuspendedSessions.valueAt(index);
1372 } else {
1373 mSuspendedSessions.add(sessionId, sessionEffects);
1374 }
1375 } else {
1376 if (index < 0) {
1377 return;
1378 }
1379 sessionEffects = mSuspendedSessions.valueAt(index);
1380 }
1381
1382
Andy Hung116bc262023-06-20 18:56:17 -07001383 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001384 if (type != NULL) {
1385 key = type->timeLow;
1386 }
1387 index = sessionEffects.indexOfKey(key);
1388
1389 sp<SuspendedSessionDesc> desc;
1390 if (suspend) {
1391 if (index >= 0) {
1392 desc = sessionEffects.valueAt(index);
1393 } else {
1394 desc = new SuspendedSessionDesc();
1395 if (type != NULL) {
1396 desc->mType = *type;
1397 }
1398 sessionEffects.add(key, desc);
1399 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1400 }
1401 desc->mRefCount++;
1402 } else {
1403 if (index < 0) {
1404 return;
1405 }
1406 desc = sessionEffects.valueAt(index);
1407 if (--desc->mRefCount == 0) {
1408 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1409 sessionEffects.removeItemsAt(index);
1410 if (sessionEffects.isEmpty()) {
1411 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1412 sessionId);
1413 mSuspendedSessions.removeItem(sessionId);
1414 }
1415 }
1416 }
1417 if (!sessionEffects.isEmpty()) {
1418 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1419 }
1420}
1421
Andy Hungee58e4a2023-07-07 13:47:37 -07001422void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001423 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001424 bool threadLocked)
1425NO_THREAD_SAFETY_ANALYSIS // manual locking
1426{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001427 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001428 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001429 }
Eric Laurent81784c32012-11-19 14:55:58 -08001430
Eric Laurent81784c32012-11-19 14:55:58 -08001431 if (mType != RECORD) {
1432 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1433 // another session. This gives the priority to well behaved effect control panels
1434 // and applications not using global effects.
1435 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1436 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001437 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001438 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1439 }
1440 }
1441
Eric Laurent6b446ce2019-12-13 10:56:31 -08001442 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001443 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001444 }
1445}
1446
Andy Hungc5007f82023-08-29 14:26:09 -07001447// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001448status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001449 const effect_descriptor_t *desc, audio_session_t sessionId)
1450{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001451 // No global output effect sessions on record threads
1452 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1453 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001454 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1455 desc->name, mThreadName);
1456 return BAD_VALUE;
1457 }
1458 // only pre processing effects on record thread
1459 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1460 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1461 desc->name, mThreadName);
1462 return BAD_VALUE;
1463 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001464
1465 // always allow effects without processing load or latency
1466 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1467 return NO_ERROR;
1468 }
1469
Eric Laurent4c415062016-06-17 16:14:16 -07001470 audio_input_flags_t flags = mInput->flags;
1471 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1472 if (flags & AUDIO_INPUT_FLAG_RAW) {
1473 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1474 desc->name, mThreadName);
1475 return BAD_VALUE;
1476 }
1477 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1478 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1479 desc->name, mThreadName);
1480 return BAD_VALUE;
1481 }
1482 }
jiabineb3bda02020-06-30 14:07:03 -07001483
Andy Hung116bc262023-06-20 18:56:17 -07001484 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001485 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1486 return BAD_VALUE;
1487 }
Eric Laurent4c415062016-06-17 16:14:16 -07001488 return NO_ERROR;
1489}
1490
Andy Hungc5007f82023-08-29 14:26:09 -07001491// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001492status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001493 const effect_descriptor_t *desc, audio_session_t sessionId)
1494{
1495 // no preprocessing on playback threads
1496 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001497 ALOGW("%s: pre processing effect %s created on playback"
1498 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001499 return BAD_VALUE;
1500 }
1501
Eric Laurent3e4de772017-07-16 16:55:08 -07001502 // always allow effects without processing load or latency
1503 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1504 return NO_ERROR;
1505 }
1506
Andy Hung116bc262023-06-20 18:56:17 -07001507 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001508 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1509 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001510 return BAD_VALUE;
1511 }
1512
Eric Laurent4eb45d02023-12-20 12:07:17 +01001513 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001514 && mType != SPATIALIZER) {
1515 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1516 __func__, mType);
1517 return BAD_VALUE;
1518 }
1519
Eric Laurent4c415062016-06-17 16:14:16 -07001520 switch (mType) {
1521 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001522 audio_output_flags_t flags = mOutput->flags;
1523 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1524 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1525 // global effects are applied only to non fast tracks if they are SW
1526 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1527 break;
1528 }
1529 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1530 // only post processing on output stage session
1531 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001532 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1533 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001534 return BAD_VALUE;
1535 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001536 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1537 // only post processing on output stage session
1538 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001539 ALOGW("%s: non post processing effect %s not allowed on device session",
1540 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001541 return BAD_VALUE;
1542 }
Eric Laurent4c415062016-06-17 16:14:16 -07001543 } else {
1544 // no restriction on effects applied on non fast tracks
1545 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1546 break;
1547 }
1548 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001549
Eric Laurent4c415062016-06-17 16:14:16 -07001550 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001551 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001552 return BAD_VALUE;
1553 }
1554 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001555 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1556 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001557 return BAD_VALUE;
1558 }
1559 }
1560 } break;
1561 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001562 // nothing actionable on offload threads, if the effect:
1563 // - is offloadable: the effect can be created
1564 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1565 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001566 break;
1567 case DIRECT:
1568 // Reject any effect on Direct output threads for now, since the format of
1569 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001570 ALOGW("%s: effect %s on DIRECT output thread %s",
1571 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001572 return BAD_VALUE;
1573 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001574 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001575 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1576 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001577 return BAD_VALUE;
1578 }
1579 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001580 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1581 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001582 return BAD_VALUE;
1583 }
1584 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001585 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1586 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001587 return BAD_VALUE;
1588 }
1589 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001590 case SPATIALIZER:
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001591 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are supported on spatializer mixer, but only
1592 // the spatialized track have global effects applied for now.
Eric Laurentb62d0362021-10-26 17:40:18 +02001593 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1594 // are supported and added after the spatializer.
1595 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001596 ALOGD("%s: global effect %s on spatializer thread %s", __func__, desc->name,
1597 mThreadName);
Eric Laurentb62d0362021-10-26 17:40:18 +02001598 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1599 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001600 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001601 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1602 break;
1603 }
1604 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1605 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1606 __func__, desc->name);
1607 return BAD_VALUE;
1608 }
1609 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1610 // only post processing on output stage session
1611 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1612 ALOGW("%s: non post processing effect %s not allowed on device session",
1613 __func__, desc->name);
1614 return BAD_VALUE;
1615 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001616 }
1617 break;
jiabinc658e452022-10-21 20:52:21 +00001618 case BIT_PERFECT:
1619 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1620 // Allow HW accelerated effects of tunnel type
1621 break;
1622 }
1623 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1624 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1625 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1626 // 3) there is any bit-perfect track with the given session id.
1627 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1628 sessionId == AUDIO_SESSION_DEVICE) {
1629 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1630 __func__, desc->name, mThreadName);
1631 return BAD_VALUE;
1632 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1633 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1634 __func__, desc->name, sessionId);
1635 return BAD_VALUE;
1636 }
1637 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001638 default:
1639 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1640 }
1641
1642 return NO_ERROR;
1643}
1644
Andy Hungc5007f82023-08-29 14:26:09 -07001645// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001646sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001647 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001648 const sp<IEffectClient>& effectClient,
1649 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001650 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001651 effect_descriptor_t *desc,
1652 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001653 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001654 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001655 bool probe,
1656 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001657{
Andy Hung116bc262023-06-20 18:56:17 -07001658 sp<IAfEffectModule> effect;
1659 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001660 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001661 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001662 bool chainCreated = false;
1663 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001664 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001665
1666 lStatus = initCheck();
1667 if (lStatus != NO_ERROR) {
1668 ALOGW("createEffect_l() Audio driver not initialized.");
1669 goto Exit;
1670 }
1671
Eric Laurent81784c32012-11-19 14:55:58 -08001672 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1673
Andy Hungc5007f82023-08-29 14:26:09 -07001674 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001675 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001676
Eric Laurent4c415062016-06-17 16:14:16 -07001677 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001678 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001679 goto Exit;
1680 }
1681
Eric Laurent81784c32012-11-19 14:55:58 -08001682 // check for existing effect chain with the requested audio session
1683 chain = getEffectChain_l(sessionId);
1684 if (chain == 0) {
1685 // create a new chain for this session
1686 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001687 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001688 addEffectChain_l(chain);
1689 chain->setStrategy(getStrategyForSession_l(sessionId));
1690 chainCreated = true;
1691 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001692 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001693 }
1694
1695 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1696
1697 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001698 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001699 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001700 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001701 if (lStatus != NO_ERROR) {
1702 goto Exit;
1703 }
1704 effectCreated = true;
1705
jiabinc52b1ff2019-10-31 17:20:42 -07001706 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001707 effect->setDevices(outDeviceTypeAddrs());
1708 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001709 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001710 effect->setAudioSource(mAudioSource);
1711 }
jiabin1319f5a2021-03-30 22:21:24 +00001712 if (effect->isHapticGenerator()) {
1713 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1714 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001715 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001716 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001717 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001718 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001719 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001720 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001721 }
1722 }
Eric Laurent81784c32012-11-19 14:55:58 -08001723 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001724 handle = IAfEffectHandle::create(
1725 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001726 lStatus = handle->initCheck();
1727 if (lStatus == OK) {
1728 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001729 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001730 }
Eric Laurent81784c32012-11-19 14:55:58 -08001731 if (enabled != NULL) {
1732 *enabled = (int)effect->isEnabled();
1733 }
1734 }
1735
1736Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001737 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001738 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001739 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001740 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001741 }
Eric Laurent81784c32012-11-19 14:55:58 -08001742 if (chainCreated) {
1743 removeEffectChain_l(chain);
1744 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001745 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001746 }
1747
Glenn Kasten9156ef32013-08-06 15:39:08 -07001748 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001749 return handle;
1750}
1751
Andy Hungee58e4a2023-07-07 13:47:37 -07001752void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001753 bool unpinIfLast)
1754{
1755 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001756 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001757 {
Andy Hung972bec12023-08-31 16:13:39 -07001758 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001759 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001760 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001761 return;
1762 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001763 effect = effectBase->asEffectModule();
1764 if (effect == nullptr) {
1765 return;
1766 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001767 // restore suspended effects if the disconnected handle was enabled and the last one.
1768 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1769 if (remove) {
1770 removeEffect_l(effect, true);
1771 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001772 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001773 }
1774 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001775 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001776 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001777 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001778 }
1779 }
1780}
1781
Andy Hungee58e4a2023-07-07 13:47:37 -07001782void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001783 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001784 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001785 broadcast_l();
1786 }
1787 if (!effect->isOffloadable()) {
1788 if (mType == ThreadBase::OFFLOAD) {
1789 PlaybackThread *t = (PlaybackThread *)this;
1790 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1791 }
1792 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001793 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001794 }
1795 }
1796}
1797
Andy Hungee58e4a2023-07-07 13:47:37 -07001798void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001799 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001800 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001801 broadcast_l();
1802 }
1803}
1804
Andy Hungee58e4a2023-07-07 13:47:37 -07001805sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001806 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001807{
Andy Hung972bec12023-08-31 16:13:39 -07001808 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001809 return getEffect_l(sessionId, effectId);
1810}
1811
Andy Hungee58e4a2023-07-07 13:47:37 -07001812sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001813 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001814{
Andy Hung116bc262023-06-20 18:56:17 -07001815 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001816 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1817}
1818
Andy Hungee58e4a2023-07-07 13:47:37 -07001819std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001820{
Andy Hung116bc262023-06-20 18:56:17 -07001821 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001822 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001823}
1824
Andy Hung972bec12023-08-31 16:13:39 -07001825// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1826// ThreadBase::mutex() held
1827status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001828{
1829 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001830 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001831 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001832 bool chainCreated = false;
1833
Eric Laurent5baf2af2013-09-12 17:37:00 -07001834 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001835 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1836 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001837
Eric Laurent81784c32012-11-19 14:55:58 -08001838 if (chain == 0) {
1839 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001840 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001841 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001842 addEffectChain_l(chain);
1843 chain->setStrategy(getStrategyForSession_l(sessionId));
1844 chainCreated = true;
1845 }
Andy Hung972bec12023-08-31 16:13:39 -07001846 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001847
1848 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001849 ALOGW("%s: %p effect %s already present in chain %p",
1850 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001851 return BAD_VALUE;
1852 }
1853
Shunkai Yaod125e402024-01-20 03:19:06 +00001854 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001855
Shunkai Yao29d10572024-03-19 04:31:47 +00001856 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001857 if (status != NO_ERROR) {
1858 if (chainCreated) {
1859 removeEffectChain_l(chain);
1860 }
1861 return status;
1862 }
1863
jiabin8f278ee2019-11-11 12:16:27 -08001864 effect->setDevices(outDeviceTypeAddrs());
1865 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001866 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001867 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001868
Eric Laurent81784c32012-11-19 14:55:58 -08001869 return NO_ERROR;
1870}
1871
Andy Hungee58e4a2023-07-07 13:47:37 -07001872void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001873
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001874 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001875 effect_descriptor_t desc = effect->desc();
1876 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1877 detachAuxEffect_l(effect->id());
1878 }
1879
Andy Hung116bc262023-06-20 18:56:17 -07001880 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001881 if (chain != 0) {
1882 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001883 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001884 removeEffectChain_l(chain);
1885 }
1886 } else {
1887 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1888 }
1889}
1890
Shunkai Yaof4847652024-01-12 00:25:20 +00001891void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1892 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001893{
1894 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001895 for (const auto& effectChain : effectChains) {
1896 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001897 }
1898}
1899
Shunkai Yaof4847652024-01-12 00:25:20 +00001900void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1901 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001902{
Shunkai Yaof4847652024-01-12 00:25:20 +00001903 for (const auto& effectChain : effectChains) {
1904 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001905 }
1906}
1907
Andy Hungee58e4a2023-07-07 13:47:37 -07001908sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001909{
Andy Hung972bec12023-08-31 16:13:39 -07001910 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001911 return getEffectChain_l(sessionId);
1912}
1913
Andy Hungee58e4a2023-07-07 13:47:37 -07001914sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001915 const
Eric Laurent81784c32012-11-19 14:55:58 -08001916{
1917 size_t size = mEffectChains.size();
1918 for (size_t i = 0; i < size; i++) {
1919 if (mEffectChains[i]->sessionId() == sessionId) {
1920 return mEffectChains[i];
1921 }
1922 }
1923 return 0;
1924}
1925
Andy Hungee58e4a2023-07-07 13:47:37 -07001926void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001927{
Andy Hung972bec12023-08-31 16:13:39 -07001928 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001929 size_t size = mEffectChains.size();
1930 for (size_t i = 0; i < size; i++) {
1931 mEffectChains[i]->setMode_l(mode);
1932 }
1933}
1934
Andy Hungee58e4a2023-07-07 13:47:37 -07001935void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001936{
1937 config->type = AUDIO_PORT_TYPE_MIX;
1938 config->ext.mix.handle = mId;
1939 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001940 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001941 config->channel_mask = mChannelMask;
1942 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1943 AUDIO_PORT_CONFIG_FORMAT;
1944}
1945
Andy Hungee58e4a2023-07-07 13:47:37 -07001946void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001947{
Andy Hung972bec12023-08-31 16:13:39 -07001948 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001949 if (mSystemReady) {
1950 return;
1951 }
1952 mSystemReady = true;
1953
1954 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1955 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1956 }
1957 mPendingConfigEvents.clear();
1958}
1959
Andy Hungdae27702016-10-31 14:01:16 -07001960template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001961ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001962 ssize_t index = mActiveTracks.indexOf(track);
1963 if (index >= 0) {
1964 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1965 return index;
1966 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001967 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001968 mActiveTracksGeneration++;
1969 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001970 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001971 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001972 return mActiveTracks.add(track);
1973}
1974
1975template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001976ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001977 ssize_t index = mActiveTracks.remove(track);
1978 if (index < 0) {
1979 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1980 return index;
1981 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001982 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001983 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001984 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001985 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001986 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001987#ifdef TEE_SINK
1988 track->dumpTee(-1 /* fd */, "_REMOVE");
1989#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001990 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001991 return index;
1992}
1993
1994template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001995void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001996 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001997 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001998 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001999 }
2000 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07002001 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07002002 mActiveTracks.clear();
2003 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07002004}
2005
2006template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07002007void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07002008 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002009 // Updates ActiveTracks client uids to the thread wakelock.
2010 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2011 thread->updateWakeLockUids_l(getWakeLockUids());
2012 mLastActiveTracksGeneration = mActiveTracksGeneration;
2013 }
Andy Hungdae27702016-10-31 14:01:16 -07002014}
Eric Laurent83b88082014-06-20 18:31:16 -07002015
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002016template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002017bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002018 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002019 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002020
2021 for (const sp<T> &track : mActiveTracks) {
2022 // Do not short-circuit as all hasChanged states must be reset
2023 // as all the metadata are going to be sent
2024 hasChanged |= track->readAndClearHasChanged();
2025 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002026 return hasChanged;
2027}
2028
2029template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002030void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002031 const char *funcName, const sp<T> &track) const {
2032 if (mLocalLog != nullptr) {
2033 String8 result;
2034 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002035 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002036 }
2037}
2038
Andy Hungee58e4a2023-07-07 13:47:37 -07002039void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002040{
2041 // Thread could be blocked waiting for async
2042 // so signal it to handle state changes immediately
2043 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2044 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2045 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002046 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002047}
2048
Andy Hungd0979812019-02-21 15:51:44 -08002049// Call only from threadLoop() or when it is idle.
2050// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002051void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002052NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002053{
2054 // Do not log if we have no stats.
2055 // We choose the timestamp verifier because it is the most likely item to be present.
2056 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2057 if (nstats == 0) {
2058 return;
2059 }
2060
2061 // Don't log more frequently than once per 12 hours.
2062 // We use BOOTTIME to include suspend time.
2063 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2064 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2065 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2066 return;
2067 }
2068
2069 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2070 mLastRecordedTimeNs = timeNs;
2071
Ray Essickf27e9872019-12-07 06:28:46 -08002072 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002073
2074#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2075
2076 // thread configuration
2077 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2078 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2079 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2080 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2081 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2082 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2083 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002084 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2085 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002086
2087 // thread statistics
2088 if (mIoJitterMs.getN() > 0) {
2089 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2090 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2091 }
2092 if (mProcessTimeMs.getN() > 0) {
2093 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2094 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2095 }
2096 const auto tsjitter = mTimestampVerifier.getJitterMs();
2097 if (tsjitter.getN() > 0) {
2098 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2099 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2100 }
2101 if (mLatencyMs.getN() > 0) {
2102 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2103 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2104 }
Robert Wu06db0a32021-08-10 19:05:34 +00002105 if (mMonopipePipeDepthStats.getN() > 0) {
2106 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2107 mMonopipePipeDepthStats.getMean());
2108 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2109 mMonopipePipeDepthStats.getStdDev());
2110 }
Andy Hungd0979812019-02-21 15:51:44 -08002111
2112 item->selfrecord();
2113}
2114
Andy Hungee58e4a2023-07-07 13:47:37 -07002115product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002116{
Andy Hung583043b2023-07-17 17:05:00 -07002117 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002118 return PRODUCT_STRATEGY_NONE;
2119 }
2120 return AudioSystem::getStrategyForStream(stream);
2121}
2122
Andy Hungc5007f82023-08-29 14:26:09 -07002123// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002124void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002125 const sp<audio_utils::MelProcessor>& /*processor*/)
2126{
2127 // Do nothing
2128 ALOGW("%s: ThreadBase does not support CSD", __func__);
2129}
2130
Andy Hungc5007f82023-08-29 14:26:09 -07002131// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002132void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002133{
2134 // Do nothing
2135 ALOGW("%s: ThreadBase does not support CSD", __func__);
2136}
2137
Eric Laurent81784c32012-11-19 14:55:58 -08002138// ----------------------------------------------------------------------------
2139// Playback
2140// ----------------------------------------------------------------------------
2141
Andy Hung583043b2023-07-17 17:05:00 -07002142PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002143 AudioStreamOut* output,
2144 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002145 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002146 bool systemReady,
2147 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002148 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002149 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002150 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002151 mMixerBuffer(NULL),
2152 mMixerBufferSize(0),
2153 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2154 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002155 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002156 mEffectBuffer(NULL),
2157 mEffectBufferSize(0),
2158 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2159 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002160 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002161 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002162 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002163 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002164 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002165 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002166 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002167 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002168 mMixerStatus(MIXER_IDLE),
2169 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002170 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002171 mBytesRemaining(0),
2172 mCurrentWriteLength(0),
2173 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002174 mWriteAckSequence(0),
2175 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002176 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002177 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002178 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002179 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002180 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002181 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002182 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002183{
Glenn Kastend7dca052015-03-05 16:05:54 -08002184 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002185 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002186
Andy Hungc5007f82023-08-29 14:26:09 -07002187 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002188 // it would be safer to explicitly pass initial masterVolume/masterMute as
2189 // parameter.
2190 //
2191 // If the HAL we are using has support for master volume or master mute,
2192 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2193 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002194 mMasterVolume = afThreadCallback->masterVolume_l();
2195 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002196 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002197 if (mOutput->audioHwDev->canSetMasterVolume()) {
2198 mMasterVolume = 1.0;
2199 }
2200
2201 if (mOutput->audioHwDev->canSetMasterMute()) {
2202 mMasterMute = false;
2203 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002204 mIsMsdDevice = strcmp(
2205 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002206 }
2207
Eric Laurentf1f22e72021-07-13 14:04:14 +02002208 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2209 mMixerChannelMask = mixerConfig->channel_mask;
2210 }
2211
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002212 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002213
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002214 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002215 && mMixerChannelMask != mChannelMask) {
2216 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2217 mChannelMask, mMixerChannelMask);
2218 }
2219
Andy Hungc8fddf32018-08-08 18:32:37 -07002220 // TODO: We may also match on address as well as device type for
2221 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002222 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002223 // TODO: This property should be ensure that only contains one single device type.
2224 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2225 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002226 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2227 : AUDIO_DEVICE_NONE));
2228 }
Andy Hung6b137d12024-08-27 22:35:17 +00002229 if (!audioserver_flags::portid_volume_management()) {
2230 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2231 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2232 mStreamTypes[stream].volume = 0.0f;
2233 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2234 }
2235 // Audio patch and call assistant volume are always max
2236 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2237 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2238 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2239 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002240 }
Eric Laurent81784c32012-11-19 14:55:58 -08002241}
2242
Andy Hungee58e4a2023-07-07 13:47:37 -07002243PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002244{
Andy Hung583043b2023-07-17 17:05:00 -07002245 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002246 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002247 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002248 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002249 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002250}
2251
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002252// Thread virtuals
2253
Andy Hungee58e4a2023-07-07 13:47:37 -07002254void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002255{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002256 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002257 ALOGE("The stream is not open yet"); // This should not happen.
2258 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002259 // Callbacks take strong or weak pointers as a parameter.
2260 // Since PlaybackThread passes itself as a callback handler, it can only
2261 // be done outside of the constructor. Creating weak and especially strong
2262 // pointers to a refcounted object in its own constructor is strongly
2263 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2264 // Even if a function takes a weak pointer, it is possible that it will
2265 // need to convert it to a strong pointer down the line.
2266 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2267 mOutput->stream->setCallback(this) == OK) {
2268 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002269 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002270 }
2271
jiabinf6eb4c32020-02-25 14:06:25 -08002272 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002273 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002274 }
2275 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002276 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002277 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002278}
2279
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002280// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002281void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002282{
2283 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002284 status_t result = mOutput->stream->exit();
2285 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002286}
2287
Andy Hungee58e4a2023-07-07 13:47:37 -07002288void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002289{
Eric Laurent81784c32012-11-19 14:55:58 -08002290 String8 result;
Andy Hung6b137d12024-08-27 22:35:17 +00002291 if (!audioserver_flags::portid_volume_management()) {
2292 result.appendFormat(" Stream volumes in dB: ");
2293 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2294 const stream_type_t *st = &mStreamTypes[i];
2295 if (i > 0) {
2296 result.appendFormat(", ");
2297 }
2298 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2299 if (st->mute) {
2300 result.append("M");
2301 }
Eric Laurent81784c32012-11-19 14:55:58 -08002302 }
2303 }
2304 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002305 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002306 result.clear();
2307
Eric Laurent81784c32012-11-19 14:55:58 -08002308 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2309 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002310 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002311 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002312
2313 size_t numtracks = mTracks.size();
2314 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002315 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002316 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002317 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002318 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002319 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002320 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002321 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002322 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002323 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002324 if (track != 0) {
2325 bool active = mActiveTracks.indexOf(track) >= 0;
2326 if (active) {
2327 numactiveseen++;
2328 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002329 result.append(prefix);
2330 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002331 }
2332 }
2333 } else {
2334 result.append("\n");
2335 }
2336 if (numactiveseen != numactive) {
2337 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002338 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002339 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002340 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002341 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002342 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002343 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002344 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002345 result.append(prefix);
2346 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002347 }
2348 }
2349 }
2350
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002351 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002352}
2353
Andy Hungee58e4a2023-07-07 13:47:37 -07002354void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002355{
Andy Hung04cb8f72020-03-20 13:44:33 -07002356 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002357 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002358 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2359 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002360 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2361 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2362 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2363 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002364 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002365 dprintf(fd, " Total writes: %d\n", mNumWrites);
2366 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2367 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002368 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002369 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002370 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002371 AudioStreamOut *output = mOutput;
2372 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002373 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002374 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002375 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2376 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2377 if (mPipeSink.get() != nullptr) {
2378 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2379 }
2380 if (output != nullptr) {
2381 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002382 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002383 }
Eric Laurent81784c32012-11-19 14:55:58 -08002384}
2385
Andy Hungc5007f82023-08-29 14:26:09 -07002386// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002387sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002388 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002389 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002390 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002391 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002392 audio_format_t format,
2393 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002394 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002395 size_t *pNotificationFrameCount,
2396 uint32_t notificationsPerBuffer,
2397 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002398 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002399 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002400 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002401 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002402 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002403 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002404 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002405 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002406 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002407 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002408 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00002409 audio_output_flags_t *afTrackFlags,
2410 float volume)
Eric Laurent81784c32012-11-19 14:55:58 -08002411{
Glenn Kasten74935e42013-12-19 08:56:45 -08002412 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002413 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002414 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002415 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002416 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002417 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002418 uint32_t sampleRate;
2419
2420 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2421 lStatus = BAD_VALUE;
2422 goto Exit;
2423 }
Eric Laurent21da6472017-11-09 16:29:26 -08002424
2425 if (*pSampleRate == 0) {
2426 *pSampleRate = mSampleRate;
2427 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002428 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002429
2430 // special case for FAST flag considered OK if fast mixer is present
2431 if (hasFastMixer()) {
2432 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2433 }
2434
2435 // Check if requested flags are compatible with output stream flags
2436 if ((*flags & outputFlags) != *flags) {
2437 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2438 *flags, outputFlags);
2439 *flags = (audio_output_flags_t)(*flags & outputFlags);
2440 }
Eric Laurent81784c32012-11-19 14:55:58 -08002441
jiabinc658e452022-10-21 20:52:21 +00002442 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002443 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002444 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002445 if (chain.get() != nullptr) {
2446 // Bit-perfect is required according to the configuration and preferred mixer
2447 // attributes, but it is not in the output flag from the client's request. Explicitly
2448 // adding bit-perfect flag to check the compatibility
2449 audio_output_flags_t flagsToCheck =
2450 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2451 chain->checkOutputFlagCompatibility(&flagsToCheck);
2452 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2453 ALOGE("%s cannot create track as there is data-processing effect attached to "
2454 "given session id(%d)", __func__, sessionId);
2455 lStatus = BAD_VALUE;
2456 goto Exit;
2457 }
2458 *flags = flagsToCheck;
2459 }
2460 }
2461
Eric Laurent81784c32012-11-19 14:55:58 -08002462 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002463 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002464 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002465 // PCM data
2466 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002467 // TODO: extract as a data library function that checks that a computationally
2468 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002469 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002470 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2471 (channelMask == AUDIO_CHANNEL_OUT_MONO
2472 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002473 // hardware sample rate
2474 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002475 // normal mixer has an associated fast mixer
2476 hasFastMixer() &&
2477 // there are sufficient fast track slots available
2478 (mFastTrackAvailMask != 0)
2479 // FIXME test that MixerThread for this fast track has a capable output HAL
2480 // FIXME add a permission test also?
2481 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002482 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2483 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002484 // read the fast track multiplier property the first time it is needed
2485 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2486 if (ok != 0) {
2487 ALOGE("%s pthread_once failed: %d", __func__, ok);
2488 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002489 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002490 }
Eric Laurent4c415062016-06-17 16:14:16 -07002491
2492 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002493 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002494 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002495 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002496 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002497 AUDIO_SESSION_OUTPUT_STAGE,
2498 AUDIO_SESSION_OUTPUT_MIX,
2499 sessionId,
2500 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002501 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002502 if (chain.get() != nullptr) {
2503 audio_output_flags_t old = *flags;
2504 chain->checkOutputFlagCompatibility(flags);
2505 if (old != *flags) {
2506 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2507 (int)session, (int)old, (int)*flags);
2508 }
Eric Laurent4c415062016-06-17 16:14:16 -07002509 }
2510 }
2511 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002512 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002513 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2514 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002515 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002516 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002517 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002518 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002519 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002520 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002521 audio_is_linear_pcm(format), channelMask, sampleRate,
2522 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002523 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002524 }
2525 }
Eric Laurent21da6472017-11-09 16:29:26 -08002526
2527 if (!audio_has_proportional_frames(format)) {
2528 if (sharedBuffer != 0) {
2529 // Same comment as below about ignoring frameCount parameter for set()
2530 frameCount = sharedBuffer->size();
2531 } else if (frameCount == 0) {
2532 frameCount = mNormalFrameCount;
2533 }
2534 if (notificationFrameCount != frameCount) {
2535 notificationFrameCount = frameCount;
2536 }
2537 } else if (sharedBuffer != 0) {
2538 // FIXME: Ensure client side memory buffers need
2539 // not have additional alignment beyond sample
2540 // (e.g. 16 bit stereo accessed as 32 bit frame).
2541 size_t alignment = audio_bytes_per_sample(format);
2542 if (alignment & 1) {
2543 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2544 alignment = 1;
2545 }
2546 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2547 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2548 if (channelCount > 1) {
2549 // More than 2 channels does not require stronger alignment than stereo
2550 alignment <<= 1;
2551 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002552 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002553 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002554 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002555 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002556 goto Exit;
2557 }
Eric Laurent21da6472017-11-09 16:29:26 -08002558
2559 // When initializing a shared buffer AudioTrack via constructors,
2560 // there's no frameCount parameter.
2561 // But when initializing a shared buffer AudioTrack via set(),
2562 // there _is_ a frameCount parameter. We silently ignore it.
2563 frameCount = sharedBuffer->size() / frameSize;
2564 } else {
2565 size_t minFrameCount = 0;
2566 // For fast tracks we try to respect the application's request for notifications per buffer.
2567 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2568 if (notificationsPerBuffer > 0) {
2569 // Avoid possible arithmetic overflow during multiplication.
2570 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2571 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2572 notificationsPerBuffer, mFrameCount);
2573 } else {
2574 minFrameCount = mFrameCount * notificationsPerBuffer;
2575 }
2576 }
2577 } else {
2578 // For normal PCM streaming tracks, update minimum frame count.
2579 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2580 // cover audio hardware latency.
2581 // This is probably too conservative, but legacy application code may depend on it.
2582 // If you change this calculation, also review the start threshold which is related.
2583 uint32_t latencyMs = latency_l();
2584 if (latencyMs == 0) {
2585 ALOGE("Error when retrieving output stream latency");
2586 lStatus = UNKNOWN_ERROR;
2587 goto Exit;
2588 }
2589
2590 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2591 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2592
Eric Laurent81784c32012-11-19 14:55:58 -08002593 }
Eric Laurent21da6472017-11-09 16:29:26 -08002594 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002595 frameCount = minFrameCount;
2596 }
Eric Laurent81784c32012-11-19 14:55:58 -08002597 }
Eric Laurent21da6472017-11-09 16:29:26 -08002598
2599 // Make sure that application is notified with sufficient margin before underrun.
2600 // The client can divide the AudioTrack buffer into sub-buffers,
2601 // and expresses its desire to server as the notification frame count.
2602 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2603 size_t maxNotificationFrames;
2604 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2605 // notify every HAL buffer, regardless of the size of the track buffer
2606 maxNotificationFrames = mFrameCount;
2607 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002608 // Triple buffer the notification period for a triple buffered mixer period;
2609 // otherwise, double buffering for the notification period is fine.
2610 //
2611 // TODO: This should be moved to AudioTrack to modify the notification period
2612 // on AudioTrack::setBufferSizeInFrames() changes.
2613 const int nBuffering =
2614 (uint64_t{frameCount} * mSampleRate)
2615 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2616
Eric Laurent21da6472017-11-09 16:29:26 -08002617 maxNotificationFrames = frameCount / nBuffering;
2618 // If client requested a fast track but this was denied, then use the smaller maximum.
2619 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2620 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2621 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2622 maxNotificationFrames = maxNotificationFramesFastDenied;
2623 }
2624 }
2625 }
2626 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2627 if (notificationFrameCount == 0) {
2628 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2629 maxNotificationFrames, frameCount);
2630 } else {
2631 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2632 notificationFrameCount, maxNotificationFrames, frameCount);
2633 }
2634 notificationFrameCount = maxNotificationFrames;
2635 }
2636 }
2637
Glenn Kasten74935e42013-12-19 08:56:45 -08002638 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002639 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002640
Glenn Kastenc3df8382014-03-13 15:05:25 -07002641 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002642 case BIT_PERFECT:
2643 if (isBitPerfect) {
2644 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2645 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2646 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2647 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2648 mChannelMask);
2649 lStatus = BAD_VALUE;
2650 goto Exit;
2651 }
2652 }
2653 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002654
2655 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002656 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002657 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002658 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2659 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002660 sampleRate, format, channelMask, mOutput, mFormat);
2661 lStatus = BAD_VALUE;
2662 goto Exit;
2663 }
2664 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002665 break;
2666
2667 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002669 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2670 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 sampleRate, format, channelMask, mOutput, mFormat);
2672 lStatus = BAD_VALUE;
2673 goto Exit;
2674 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002675 break;
2676
2677 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002678 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002679 ALOGE("createTrack_l() Bad parameter: format %#x \""
2680 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002681 format, mOutput, mFormat);
2682 lStatus = BAD_VALUE;
2683 goto Exit;
2684 }
Andy Hungcd044842014-08-07 11:04:34 -07002685 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002686 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2687 lStatus = BAD_VALUE;
2688 goto Exit;
2689 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002690 break;
2691
Eric Laurent81784c32012-11-19 14:55:58 -08002692 }
2693
2694 lStatus = initCheck();
2695 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002696 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002697 goto Exit;
2698 }
2699
Andy Hungc5007f82023-08-29 14:26:09 -07002700 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002701 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002702
2703 // all tracks in same audio session must share the same routing strategy otherwise
2704 // conflicts will happen when tracks are moved from one output to another by audio policy
2705 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002706 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002707 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002708 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002709 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002710 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002711 if (sessionId == t->sessionId() && strategy != actual) {
2712 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2713 strategy, actual);
2714 lStatus = BAD_VALUE;
2715 goto Exit;
2716 }
2717 }
2718 }
2719
Deeraj Soman2b515232024-05-14 12:58:24 +05302720 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2721 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002722 // dynamic audio policy.
2723 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302724 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002725 audio_output_flags_t trackFlags = *flags;
2726 if (mType == DIRECT) {
2727 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302728 } else if (mType == OFFLOAD) {
2729 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2730 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002731 }
jiabin94ed47c2023-07-27 23:34:20 +00002732 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002733
Andy Hung8d31fd22023-06-26 19:20:57 -07002734 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002735 channelMask, frameCount,
2736 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002737 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002738 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Andy Hung6b137d12024-08-27 22:35:17 +00002739 speed, isSpatialized, isBitPerfect, volume);
Glenn Kasten03003332013-08-06 15:40:54 -07002740
Glenn Kasten03003332013-08-06 15:40:54 -07002741 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2742 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002743 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002744 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002745 goto Exit;
2746 }
2747 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002748 {
Andy Hung972bec12023-08-31 16:13:39 -07002749 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002750 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002751 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002752 }
2753 }
Eric Laurent81784c32012-11-19 14:55:58 -08002754
Andy Hung116bc262023-06-20 18:56:17 -07002755 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002756 if (chain != 0) {
2757 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2758 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002759 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002760 chain->incTrackCnt();
2761 }
2762
Eric Laurent05067782016-06-01 18:27:28 -07002763 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002764 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2765 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2766 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002767 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002768 }
2769 }
2770
2771 lStatus = NO_ERROR;
2772
2773Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002774 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002775 return track;
2776}
2777
Andy Hung1bc088a2018-02-09 15:57:31 -08002778template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002779ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002780{
Andy Hungc0691382018-09-12 18:01:57 -07002781 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002782 const ssize_t index = mTracks.remove(track);
2783 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002784 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002785 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002786 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002787 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002788 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002789 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002790 }
2791 return index;
2792}
2793
Andy Hungee58e4a2023-07-07 13:47:37 -07002794uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002795{
2796 return latency;
2797}
2798
Andy Hungee58e4a2023-07-07 13:47:37 -07002799uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002800{
Andy Hung972bec12023-08-31 16:13:39 -07002801 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002802 return latency_l();
2803}
Andy Hungee58e4a2023-07-07 13:47:37 -07002804uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002805NO_THREAD_SAFETY_ANALYSIS
2806// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002807{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002808 uint32_t latency;
2809 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2810 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002811 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002812 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002813}
2814
Andy Hungee58e4a2023-07-07 13:47:37 -07002815void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002816{
Andy Hung972bec12023-08-31 16:13:39 -07002817 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002818 // Don't apply master volume in SW if our HAL can do it for us.
2819 if (mOutput && mOutput->audioHwDev &&
2820 mOutput->audioHwDev->canSetMasterVolume()) {
2821 mMasterVolume = 1.0;
2822 } else {
2823 mMasterVolume = value;
2824 }
2825}
2826
Andy Hungee58e4a2023-07-07 13:47:37 -07002827void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002828{
2829 mMasterBalance.store(balance);
2830}
2831
Andy Hungee58e4a2023-07-07 13:47:37 -07002832void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002833{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002834 if (isDuplicating()) {
2835 return;
2836 }
Andy Hung972bec12023-08-31 16:13:39 -07002837 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002838 // Don't apply master mute in SW if our HAL can do it for us.
2839 if (mOutput && mOutput->audioHwDev &&
2840 mOutput->audioHwDev->canSetMasterMute()) {
2841 mMasterMute = false;
2842 } else {
2843 mMasterMute = muted;
2844 }
2845}
2846
Andy Hungee58e4a2023-07-07 13:47:37 -07002847void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002848{
Andy Hung972bec12023-08-31 16:13:39 -07002849 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002850 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002851 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002852}
2853
Andy Hungee58e4a2023-07-07 13:47:37 -07002854void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002855{
Andy Hung972bec12023-08-31 16:13:39 -07002856 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002857 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002858 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002859}
2860
Andy Hungee58e4a2023-07-07 13:47:37 -07002861float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002862{
Andy Hung972bec12023-08-31 16:13:39 -07002863 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002864 return mStreamTypes[stream].volume;
2865}
2866
Andy Hung6b137d12024-08-27 22:35:17 +00002867status_t PlaybackThread::setPortsVolume(
2868 const std::vector<audio_port_handle_t>& portIds, float volume) {
2869 audio_utils::lock_guard _l(mutex());
2870 for (const auto& portId : portIds) {
2871 for (size_t i = 0; i < mTracks.size(); i++) {
2872 sp<IAfTrack> track = mTracks[i].get();
2873 if (portId == track->portId()) {
2874 track->setPortVolume(volume);
2875 break;
2876 }
2877 }
2878 }
2879 broadcast_l();
2880 return NO_ERROR;
2881}
2882
Andy Hungee58e4a2023-07-07 13:47:37 -07002883void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002884{
2885 mOutput->stream->setVolume(left, right);
2886}
2887
Andy Hungc5007f82023-08-29 14:26:09 -07002888// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002889status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002890{
2891 status_t status = ALREADY_EXISTS;
2892
Eric Laurent81784c32012-11-19 14:55:58 -08002893 if (mActiveTracks.indexOf(track) < 0) {
2894 // the track is newly added, make sure it fills up all its
2895 // buffers before playing. This is to ensure the client will
2896 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002897 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002898 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002899 // Because the track is not on the ActiveTracks,
2900 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002901 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002902 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002903 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002905 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002906 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002907 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002908 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002909 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002910 }
2911 return INVALID_OPERATION;
2912 }
2913 // abort if start is rejected by audio policy manager
2914 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002915 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2916 // current playback thread is reopened, which may happen when clients set preferred
2917 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2918 // immediately.
2919 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002920 }
2921#ifdef ADD_BATTERY_DATA
2922 // to track the speaker usage
2923 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2924#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002925 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 }
2927
Eric Laurent51716182016-02-29 18:00:56 -08002928 // set retry count for buffer fill
2929 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002930 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002931 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002932 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002933 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002934 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002935 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002936 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002937 track->retryCount() = kMaxTrackStartupRetries;
2938 track->fillingStatus() =
2939 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002940 }
2941
Andy Hung116bc262023-06-20 18:56:17 -07002942 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002943 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2944 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002945 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002946 // Unlock due to VibratorService will lock for this call and will
2947 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002948 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002949 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002950 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002951 std::optional<media::AudioVibratorInfo> vibratorInfo;
2952 {
2953 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2954 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002955 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002956 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002957 }
Andy Hungc5007f82023-08-29 14:26:09 -07002958 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002959 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002960 if (vibratorInfo) {
2961 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2962 }
2963
jiabin57303cc2018-12-18 15:45:57 -08002964 // Haptic playback should be enabled by vibrator service.
2965 if (track->getHapticPlaybackEnabled()) {
2966 // Disable haptic playback of all active track to ensure only
2967 // one track playing haptic if current track should play haptic.
2968 for (const auto &t : mActiveTracks) {
2969 t->setHapticPlaybackEnabled(false);
2970 }
jiabin245cdd92018-12-07 17:55:15 -08002971 }
jiabine70bc7f2020-06-30 22:07:55 -07002972
2973 // Set haptic intensity for effect
2974 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002975 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002976 }
jiabin245cdd92018-12-07 17:55:15 -08002977 }
2978
Andy Hung8d31fd22023-06-26 19:20:57 -07002979 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002980 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002981
2982 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2983 // all key changes are complete. It is possible that the threadLoop will begin
2984 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002985 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002986
Eric Laurentd0107bc2013-06-11 14:38:48 -07002987 if (chain != 0) {
2988 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2989 track->sessionId());
2990 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002991 }
2992
Andy Hungc2b11cb2020-04-22 09:04:01 -07002993 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002994 status = NO_ERROR;
2995 }
2996
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002997 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002998 return status;
2999}
3000
Andy Hungee58e4a2023-07-07 13:47:37 -07003001bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003002{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003003 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08003004 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003005 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07003006 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003007 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08003008 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07003009 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07003010 if (track->isPausePending()) {
3011 track->pauseAck();
3012 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003013 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003014 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003015
3016 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003017}
3018
Andy Hungee58e4a2023-07-07 13:47:37 -07003019void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003020{
3021 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003022
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003023 String8 result;
3024 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003025 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003026
Eric Laurent81784c32012-11-19 14:55:58 -08003027 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003028 {
Andy Hung972bec12023-08-31 16:13:39 -07003029 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003030 mAudioTrackCallbacks.erase(track);
3031 }
Eric Laurent81784c32012-11-19 14:55:58 -08003032 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003033 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003034 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003035 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3036 mFastTrackAvailMask |= 1 << index;
3037 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003038 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003039 }
Andy Hung116bc262023-06-20 18:56:17 -07003040 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003041 if (chain != 0) {
3042 chain->decTrackCnt();
3043 }
3044}
3045
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003046std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3047{
3048 std::set<int32_t> result;
3049 for (const auto& t : mTracks) {
3050 if (t->isExternalTrack()) {
3051 result.insert(t->portId());
3052 }
3053 }
3054 return result;
3055}
3056
3057std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3058{
3059 audio_utils::lock_guard _l(mutex());
3060 return getTrackPortIds_l();
3061}
3062
Andy Hungee58e4a2023-07-07 13:47:37 -07003063String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003064{
Andy Hung972bec12023-08-31 16:13:39 -07003065 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003066 String8 out_s8;
3067 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3068 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003069 }
Andy Hung920f6572022-10-06 12:09:49 -07003070 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003071}
3072
Andy Hungee58e4a2023-07-07 13:47:37 -07003073status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003074 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003075 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003076 return NO_INIT;
3077 }
3078 return mOutput->stream->selectPresentation(presentationId, programId);
3079}
3080
Andy Hungab65b182023-09-06 19:41:47 -07003081void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003082 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003083 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003084 sp<AudioIoDescriptor> desc;
3085 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003086 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003087 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003088 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003089 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003090 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3091 mSampleRate, mFormat, mChannelMask,
3092 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3093 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003094 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003095 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003096 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003097 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003098 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003099 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003100 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003101 break;
3102 }
Andy Hungab65b182023-09-06 19:41:47 -07003103 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003104}
3105
Andy Hungee58e4a2023-07-07 13:47:37 -07003106void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003108 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109}
3110
Andy Hungee58e4a2023-07-07 13:47:37 -07003111void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003113 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003114}
3115
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003116void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003117{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003118 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003119}
3120
Andy Hungee58e4a2023-07-07 13:47:37 -07003121void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003122 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003123{
Andy Hungee58e4a2023-07-07 13:47:37 -07003124 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003125 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003126 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003127 if (playbackThread == nullptr) {
3128 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3129 return;
3130 }
3131
jiabinf6eb4c32020-02-25 14:06:25 -08003132 audio_utils::metadata::Data metadata =
3133 audio_utils::metadata::dataFromByteString(metadataBs);
3134 if (metadata.empty()) {
3135 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3136 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3137 (int)metadataBs.size());
3138 return;
3139 }
3140
3141 audio_utils::metadata::ByteString metaDataStr =
3142 audio_utils::metadata::byteStringFromData(metadata);
3143 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003144 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003145 for (const auto& callbackPair : mAudioTrackCallbacks) {
3146 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003147 }
3148 }).detach();
3149}
3150
Andy Hungee58e4a2023-07-07 13:47:37 -07003151void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003152{
Andy Hung972bec12023-08-31 16:13:39 -07003153 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003154 // reject out of sequence requests
3155 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3156 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003157 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003158 }
3159}
3160
Andy Hungee58e4a2023-07-07 13:47:37 -07003161void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003162{
Andy Hung972bec12023-08-31 16:13:39 -07003163 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003164 // reject out of sequence requests
3165 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003166 // Register discontinuity when HW drain is completed because that can cause
3167 // the timestamp frame position to reset to 0 for direct and offload threads.
3168 // (Out of sequence requests are ignored, since the discontinuity would be handled
3169 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003170 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003171 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003172 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003173 }
3174}
3175
Andy Hungee58e4a2023-07-07 13:47:37 -07003176void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003177NO_THREAD_SAFETY_ANALYSIS
3178// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003179{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003180 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003181 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3182 mSampleRate = audioConfig.sample_rate;
3183 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003184 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003185 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003186 }
Andy Hung81994d62023-07-20 21:44:14 -07003187 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003188 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3189 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003190 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003191
3192 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3193 mMixerChannelMask = mChannelMask;
3194 }
3195
Andy Hunge5412692014-05-16 11:25:07 -07003196 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003197 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003198
Eric Laurentf1f22e72021-07-13 14:04:14 +02003199 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3200
Phil Burkca5e6142015-07-14 09:42:29 -07003201 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003202 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003203 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003204 // Get format from the shim, which will be different than the HAL format
3205 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003206 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003207 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003208 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003209 }
Andy Hung81994d62023-07-20 21:44:14 -07003210 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003211 LOG_FATAL("HAL format %#x not supported for mixed output",
3212 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003213 }
Phil Burk062e67a2015-02-11 13:40:50 -08003214 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003215 result = mOutput->stream->getBufferSize(&mBufferSize);
3216 LOG_ALWAYS_FATAL_IF(result != OK,
3217 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003218 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003219 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003220 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003221 mFrameCount);
3222 }
3223
Eric Laurentd1f69b02014-12-15 14:33:13 -08003224 mHwSupportsPause = false;
3225 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003226 bool supportsPause = false, supportsResume = false;
3227 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3228 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003229 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003230 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003231 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003232 } else if (supportsResume) {
3233 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003234 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003235 }
3236 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003237 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3238 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3239 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003240
Andy Hungfbfc3952015-01-15 13:33:51 -08003241 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3242 // For best precision, we use float instead of the associated output
3243 // device format (typically PCM 16 bit).
3244
3245 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3246 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3247 mBufferSize = mFrameSize * mFrameCount;
3248
3249 // TODO: We currently use the associated output device channel mask and sample rate.
3250 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3251 // (if a valid mask) to avoid premature downmix.
3252 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3253 // instead of the output device sample rate to avoid loss of high frequency information.
3254 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3255 }
3256
Andy Hung09a50072014-02-27 14:30:47 -08003257 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003258 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003259 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003260 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3261 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003262 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3263 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003264
Eric Laurent81784c32012-11-19 14:55:58 -08003265 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3266 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3267 maxNormalFrameCount = maxNormalFrameCount & ~15;
3268 if (maxNormalFrameCount < minNormalFrameCount) {
3269 maxNormalFrameCount = minNormalFrameCount;
3270 }
3271 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3272 if (multiplier <= 1.0) {
3273 multiplier = 1.0;
3274 } else if (multiplier <= 2.0) {
3275 if (2 * mFrameCount <= maxNormalFrameCount) {
3276 multiplier = 2.0;
3277 } else {
3278 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3279 }
3280 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003281 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003282 }
3283 }
3284 mNormalFrameCount = multiplier * mFrameCount;
3285 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003286 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003287 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3288 }
Andy Hungab65b182023-09-06 19:41:47 -07003289 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3290 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003291
Andy Hung08fb1742015-05-31 23:22:10 -07003292 // Check if we want to throttle the processing to no more than 2x normal rate
3293 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003294 mThreadThrottleTimeMs = 0;
3295 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003296 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3297
Andy Hung010a1a12014-03-13 13:57:33 -07003298 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3299 // Originally this was int16_t[] array, need to remove legacy implications.
3300 free(mSinkBuffer);
3301 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003302
Andy Hung5b10a202014-03-13 13:59:29 -07003303 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3304 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3305 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003306 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003307
Andy Hung69aed5f2014-02-25 17:24:40 -08003308 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3309 // drives the output.
3310 free(mMixerBuffer);
3311 mMixerBuffer = NULL;
3312 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003313 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003314 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003315 * audio_bytes_per_sample(mMixerBufferFormat);
3316 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3317 }
Andy Hung98ef9782014-03-04 14:46:50 -08003318 free(mEffectBuffer);
3319 mEffectBuffer = NULL;
3320 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003321 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003322 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003323 * audio_bytes_per_sample(mEffectBufferFormat);
3324 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3325 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003326
Eric Laurentb62d0362021-10-26 17:40:18 +02003327 if (mType == SPATIALIZER) {
3328 free(mPostSpatializerBuffer);
3329 mPostSpatializerBuffer = nullptr;
3330 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3331 * audio_bytes_per_sample(mEffectBufferFormat);
3332 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3333 }
3334
Mikhail Naganov55773032020-10-01 15:08:13 -07003335 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3336 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003337 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3338 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003339 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003340
Eric Laurent81784c32012-11-19 14:55:58 -08003341 // force reconfiguration of effect chains and engines to take new buffer size and audio
3342 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003343 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003344 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3345 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003346 // create a copy of mEffectChains as calling moveEffectChain_ll()
3347 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003348 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003349 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003350 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003351 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003352 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003353
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003354 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003355 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003356 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003357 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003358 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3359 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3360 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3361 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3362 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3363 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3364 (int32_t)mHapticChannelMask)
3365 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3366 (int32_t)mHapticChannelCount)
3367 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003368 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003369 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3370 (int32_t)mFrameCount) // sic - added HAL
3371 ;
3372 uint32_t latencyMs;
3373 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3374 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3375 }
3376 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003377}
3378
Andy Hungee58e4a2023-07-07 13:47:37 -07003379ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003380{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003381 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003382 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003383 }
3384 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003385 static const bool stereo_spatialization_property =
3386 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3387 const bool stereo_spatialization_enabled =
3388 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3389 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003390 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3391 for (const sp<IAfTrack>& track : mActiveTracks) {
3392 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3393 allSessionsMetadata[track->sessionId()];
3394 auto backInserter = std::back_inserter(sessionMetadata);
3395 // No track is invalid as this is called after prepareTrack_l in the same
3396 // critical section
3397 track->copyMetadataTo(backInserter);
3398 }
3399 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3400 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3401 metadata.tracks.insert(metadata.tracks.end(),
3402 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3403 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3404 chain->sendMetadata_l(sessionTrackMetadata, {});
3405 }
3406 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3407 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3408 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3409 }
3410 }
3411 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3412 chain->sendMetadata_l(metadata.tracks, {});
3413 }
3414 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3415 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3416 }
3417 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3418 chain->sendMetadata_l(metadata.tracks, {});
3419 }
3420 } else {
3421 auto backInserter = std::back_inserter(metadata.tracks);
3422 for (const sp<IAfTrack>& track : mActiveTracks) {
3423 // No track is invalid as this is called after prepareTrack_l in the same
3424 // critical section
3425 track->copyMetadataTo(backInserter);
3426 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003427 }
Kevin Rocard12381092018-04-11 09:19:59 -07003428 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003429 MetadataUpdate change;
3430 change.playbackMetadataUpdate = metadata.tracks;
3431 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003432}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003433
Andy Hungee58e4a2023-07-07 13:47:37 -07003434void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003435 const StreamOutHalInterface::SourceMetadata& metadata)
3436{
3437 mOutput->stream->updateSourceMetadata(metadata);
3438};
3439
Andy Hungee58e4a2023-07-07 13:47:37 -07003440status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003441 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003442{
3443 if (halFrames == NULL || dspFrames == NULL) {
3444 return BAD_VALUE;
3445 }
Andy Hung972bec12023-08-31 16:13:39 -07003446 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003447 if (initCheck() != NO_ERROR) {
3448 return INVALID_OPERATION;
3449 }
Andy Hung818e7a32016-02-16 18:08:07 -08003450 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003451 *halFrames = framesWritten;
3452
3453 if (isSuspended()) {
3454 // return an estimation of rendered frames when the output is suspended
3455 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003456 *dspFrames = (uint32_t)
3457 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003458 return NO_ERROR;
3459 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003460 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003461 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003462 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003463 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003464 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003465 }
3466}
3467
Andy Hungee58e4a2023-07-07 13:47:37 -07003468product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003469{
3470 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3471 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3472 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003473 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003474 }
3475 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003476 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003477 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003478 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003479 }
3480 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003481 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003482}
3483
3484
Andy Hungee58e4a2023-07-07 13:47:37 -07003485AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003486{
Andy Hung972bec12023-08-31 16:13:39 -07003487 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003488 return mOutput;
3489}
3490
Andy Hungee58e4a2023-07-07 13:47:37 -07003491AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003492{
Andy Hung972bec12023-08-31 16:13:39 -07003493 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003494 AudioStreamOut *output = mOutput;
3495 mOutput = NULL;
3496 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3497 // must push a NULL and wait for ack
3498 mOutputSink.clear();
3499 mPipeSink.clear();
3500 mNormalSink.clear();
3501 return output;
3502}
3503
Andy Hungc5007f82023-08-29 14:26:09 -07003504// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003505sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003506{
3507 if (mOutput == NULL) {
3508 return NULL;
3509 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003510 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003511}
3512
Andy Hungee58e4a2023-07-07 13:47:37 -07003513uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003514{
3515 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3516}
3517
Andy Hungee58e4a2023-07-07 13:47:37 -07003518status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003519{
3520 if (!isValidSyncEvent(event)) {
3521 return BAD_VALUE;
3522 }
3523
Andy Hung972bec12023-08-31 16:13:39 -07003524 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003525
3526 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003527 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003528 if (event->triggerSession() == track->sessionId()) {
3529 (void) track->setSyncEvent(event);
3530 return NO_ERROR;
3531 }
3532 }
3533
3534 return NAME_NOT_FOUND;
3535}
3536
Andy Hungee58e4a2023-07-07 13:47:37 -07003537bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003538{
3539 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3540}
3541
Andy Hungee58e4a2023-07-07 13:47:37 -07003542void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003543 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003544{
Andy Hungfe726a62018-09-27 15:17:25 -07003545 // Miscellaneous track cleanup when removed from the active list,
3546 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003547#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003548 for (const auto& track : tracksToRemove) {
3549 if (track->isExternalTrack()) {
3550 // to track the speaker usage
3551 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003552 }
3553 }
Andy Hungfe726a62018-09-27 15:17:25 -07003554#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003555}
3556
Andy Hungee58e4a2023-07-07 13:47:37 -07003557void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003558{
3559 if (!mMasterMute) {
3560 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003561 if (mOutDeviceTypeAddrs.empty()) {
3562 ALOGD("ro.audio.silent is ignored since no output device is set");
3563 return;
3564 }
Andy Hungab65b182023-09-06 19:41:47 -07003565 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003566 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3567 return;
3568 }
Eric Laurent81784c32012-11-19 14:55:58 -08003569 if (property_get("ro.audio.silent", value, "0") > 0) {
3570 char *endptr;
3571 unsigned long ul = strtoul(value, &endptr, 0);
3572 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003573 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003574 // The setprop command will not allow a property to be changed after
3575 // the first time it is set, so we don't have to worry about un-muting.
3576 setMasterMute_l(true);
3577 }
3578 }
3579 }
3580}
3581
3582// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003583ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003584{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003585 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003586 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003588 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003589
3590 // If an NBAIO sink is present, use it to write the normal mixer's submix
3591 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003592
Andy Hung010a1a12014-03-13 13:57:33 -07003593 const size_t count = mBytesRemaining / mFrameSize;
3594
Simon Wilson2d590962012-11-29 15:18:50 -08003595 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003596 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003597 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003598 if (screenState != mScreenState) {
3599 mScreenState = screenState;
3600 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3601 if (pipe != NULL) {
3602 pipe->setAvgFrames((mScreenState & 1) ?
3603 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3604 }
3605 }
Andy Hung010a1a12014-03-13 13:57:33 -07003606 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003607 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003608
Eric Laurent81784c32012-11-19 14:55:58 -08003609 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003610 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003611
Andy Hung8946a282018-04-19 20:04:56 -07003612#ifdef TEE_SINK
3613 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3614#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003615 } else {
3616 bytesWritten = framesWritten;
3617 }
3618 // otherwise use the HAL / AudioStreamOut directly
3619 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003620 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003621
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003623 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3624 mWriteAckSequence += 2;
3625 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003627 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003628 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003629 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003630 // FIXME We should have an implementation of timestamps for direct output threads.
3631 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003632 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003633 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003634
Eric Laurentbfb1b832013-01-07 09:53:42 -08003635 if (mUseAsyncWrite &&
3636 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3637 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003638 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003639 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003640 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003641 }
Eric Laurent81784c32012-11-19 14:55:58 -08003642 }
3643
Eric Laurent81784c32012-11-19 14:55:58 -08003644 mNumWrites++;
3645 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003646 if (mStandby) {
3647 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003648 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003649 mStandby = false;
3650 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003651 return bytesWritten;
3652}
3653
Andy Hungc5007f82023-08-29 14:26:09 -07003654// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003655void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003656 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003657{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003658 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003659 if (outputSink != nullptr) {
3660 outputSink->startMelComputation(processor);
3661 }
Vlad Popab042ee62022-10-20 18:05:00 +02003662}
3663
Andy Hungc5007f82023-08-29 14:26:09 -07003664// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003665void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003666{
3667 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003668 if (outputSink != nullptr) {
3669 outputSink->stopMelComputation();
3670 }
Vlad Popab042ee62022-10-20 18:05:00 +02003671}
3672
Andy Hungee58e4a2023-07-07 13:47:37 -07003673void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003674{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003675 bool supportsDrain = false;
3676 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003677 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3678 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003679 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3680 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003682 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003683 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003684 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003685 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003686 }
3687}
3688
Andy Hungee58e4a2023-07-07 13:47:37 -07003689void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003690{
Eric Laurent275e8e92014-11-30 15:14:47 -08003691 {
Andy Hung972bec12023-08-31 16:13:39 -07003692 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003693 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003694 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003695 track->invalidate();
3696 }
Andy Hungdae27702016-10-31 14:01:16 -07003697 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3698 // After we exit there are no more track changes sent to BatteryNotifier
3699 // because that requires an active threadLoop.
3700 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3701 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003702 }
Eric Laurent81784c32012-11-19 14:55:58 -08003703}
3704
3705/*
3706The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003707 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003708 - mActiveSleepTimeUs from activeSleepTimeUs()
3709 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003710 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3711 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003712 - maxPeriod from frame count and sample rate (MIXER only)
3713
3714The parameters that affect these derived values are:
3715 - frame count
3716 - frame size
3717 - sample rate
3718 - device type: A2DP or not
3719 - device latency
3720 - format: PCM or not
3721 - active sleep time
3722 - idle sleep time
3723*/
3724
Andy Hungee58e4a2023-07-07 13:47:37 -07003725void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003726{
Andy Hung25c2dac2014-02-27 14:56:00 -08003727 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003728 mActiveSleepTimeUs = activeSleepTimeUs();
3729 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003730
Andy Hung8fe87eb2023-07-20 21:31:38 -07003731 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003732
Eric Laurent42537be2016-01-08 17:16:42 -08003733 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3734 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003735 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003736 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3737 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3738 }
3739 }
Eric Laurent81784c32012-11-19 14:55:58 -08003740}
3741
Andy Hungee58e4a2023-07-07 13:47:37 -07003742bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003743{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003744 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003745 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003746 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003747 size_t size = mTracks.size();
3748 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003749 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003750 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003751 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003752 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003753 }
3754 }
Eric Laurent13084622016-05-17 10:51:49 -07003755 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003756}
3757
Andy Hungee58e4a2023-07-07 13:47:37 -07003758void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003759{
Andy Hung972bec12023-08-31 16:13:39 -07003760 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003761 invalidateTracks_l(streamType);
3762}
3763
Andy Hungee58e4a2023-07-07 13:47:37 -07003764void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003765 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003766 invalidateTracks_l(portIds);
3767}
3768
Andy Hungee58e4a2023-07-07 13:47:37 -07003769bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003770 bool trackMatch = false;
3771 const size_t size = mTracks.size();
3772 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003773 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003774 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3775 t->invalidate();
3776 portIds.erase(t->portId());
3777 trackMatch = true;
3778 }
3779 if (portIds.empty()) {
3780 break;
3781 }
3782 }
3783 return trackMatch;
3784}
3785
jiabinf042b9b2021-05-07 23:46:28 +00003786// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003787IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003788 audio_port_handle_t trackPortId) {
3789 for (size_t i = 0; i < mTracks.size(); i++) {
3790 if (mTracks[i]->portId() == trackPortId) {
3791 return mTracks[i].get();
3792 }
3793 }
3794 return nullptr;
3795}
3796
Andy Hungee58e4a2023-07-07 13:47:37 -07003797status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003798{
Glenn Kastend848eb42016-03-08 13:42:11 -08003799 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003800 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003801 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003802
Andy Hungd3639922022-04-28 18:00:49 -07003803 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003804 if (!audio_is_global_session(session)) {
3805 // player sessions on a spatializer output will use a dedicated input buffer and
3806 // will either output multi channel to mEffectBuffer if the track is spatilaized
3807 // or stereo to mPostSpatializerBuffer if not spatialized.
3808 uint32_t channelMask;
3809 bool isSessionSpatialized =
3810 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3811 if (isSessionSpatialized) {
3812 channelMask = mMixerChannelMask;
3813 } else {
3814 channelMask = mChannelMask;
3815 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003816 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003817 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003818 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003819 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003820 &halInBuffer);
3821 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003822
Andy Hung583043b2023-07-17 17:05:00 -07003823 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003824 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3825 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3826 &halOutBuffer);
3827 if (result != OK) return result;
3828
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003829 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003830
Mikhail Naganov022b9952017-01-04 16:36:51 -08003831 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3832 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003833 } else {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003834 status_t result = INVALID_OPERATION;
3835 // Buffer configuration for global sessions on a SPATIALIZER thread:
3836 // - AUDIO_SESSION_OUTPUT_MIX session uses the mEffectBuffer as input and output buffer
3837 // - AUDIO_SESSION_OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3838 // mPostSpatializerBuffer as output buffer
3839 // - AUDIO_SESSION_DEVICE session uses the mPostSpatializerBuffer as input and output
3840 // buffer
3841 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_OUTPUT_STAGE) {
3842 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3843 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3844 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003845
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003846 if (session == AUDIO_SESSION_OUTPUT_MIX) {
3847 halOutBuffer = halInBuffer;
3848 }
3849 }
3850
3851 if (session == AUDIO_SESSION_OUTPUT_STAGE || session == AUDIO_SESSION_DEVICE) {
3852 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3853 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3854 if (result != OK) return result;
3855
3856 if (session == AUDIO_SESSION_DEVICE) {
3857 halInBuffer = halOutBuffer;
3858 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003859 }
3860 }
3861 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003862 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003863 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3864 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3865 &halInBuffer);
3866 if (result != OK) return result;
3867 halOutBuffer = halInBuffer;
3868 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3869 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003870 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003871 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003872 // Only one effect chain can be present in direct output thread and it uses
3873 // the sink buffer as input
3874 if (mType != DIRECT) {
3875 size_t numSamples = mNormalFrameCount
3876 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3877 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003878 const status_t allocateStatus =
3879 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003880 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003881 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003882 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003883
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003884 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003885 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3886 buffer, session);
3887 }
3888 }
3889 }
3890
3891 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003892 // Attach all tracks with same session ID to this chain.
3893 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003894 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003895 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003896 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3897 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003898 track->setMainBuffer(buffer);
3899 chain->incTrackCnt();
3900 }
3901 }
3902
3903 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003904 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003905 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003906 ALOGV("addEffectChain_l() activating track %p on session %d",
3907 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003908 chain->incActiveTrackCnt();
3909 }
3910 }
3911 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003912
Eric Laurentaaa44472014-09-12 17:41:50 -07003913 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003914 chain->setInBuffer(halInBuffer);
3915 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003916 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3917 // chains list in order to be processed last as it contains output device effects.
3918 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3919 // processing effects specific to an output stream before effects applied to all streams
3920 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003921 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3922 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003923 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003924 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003925 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003926 // Effect chain for other sessions are inserted at beginning of effect
3927 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003928 // sessions is not important.
3929 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003930 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3931 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003932 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003933 size_t size = mEffectChains.size();
3934 size_t i = 0;
3935 for (i = 0; i < size; i++) {
3936 if (mEffectChains[i]->sessionId() < session) {
3937 break;
3938 }
3939 }
3940 mEffectChains.insertAt(chain, i);
3941 checkSuspendOnAddEffectChain_l(chain);
3942
3943 return NO_ERROR;
3944}
3945
Andy Hungee58e4a2023-07-07 13:47:37 -07003946size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003947{
Glenn Kastend848eb42016-03-08 13:42:11 -08003948 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003949
3950 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3951
3952 for (size_t i = 0; i < mEffectChains.size(); i++) {
3953 if (chain == mEffectChains[i]) {
3954 mEffectChains.removeAt(i);
3955 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003956 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003957 if (session == track->sessionId()) {
3958 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3959 chain.get(), session);
3960 chain->decActiveTrackCnt();
3961 }
3962 }
3963
3964 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003965 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003966 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003967 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003968 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003969 chain->decTrackCnt();
3970 }
3971 }
3972 break;
3973 }
3974 }
3975 return mEffectChains.size();
3976}
3977
Andy Hungee58e4a2023-07-07 13:47:37 -07003978status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003979 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003980{
Andy Hung972bec12023-08-31 16:13:39 -07003981 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003982 return attachAuxEffect_l(track, EffectId);
3983}
3984
Andy Hungee58e4a2023-07-07 13:47:37 -07003985status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003986 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003987{
3988 status_t status = NO_ERROR;
3989
3990 if (EffectId == 0) {
3991 track->setAuxBuffer(0, NULL);
3992 } else {
3993 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003994 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003995 if (effect != 0) {
3996 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3997 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3998 } else {
3999 status = INVALID_OPERATION;
4000 }
4001 } else {
4002 status = BAD_VALUE;
4003 }
4004 }
4005 return status;
4006}
4007
Andy Hungee58e4a2023-07-07 13:47:37 -07004008void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08004009{
4010 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004011 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004012 if (track->auxEffectId() == effectId) {
4013 attachAuxEffect_l(track, 0);
4014 }
4015 }
4016}
4017
Andy Hungee58e4a2023-07-07 13:47:37 -07004018bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07004019NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08004020{
Andy Hung78d8d952023-05-30 18:10:23 -07004021 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08004022
Andy Hung077d62e2023-10-03 10:49:34 -07004023 if (mType == SPATIALIZER) {
4024 const pid_t tid = getTid();
4025 if (tid == -1) { // odd: we are here, we must be a running thread.
4026 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4027 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004028 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4029 if (priorityBoost > 0) {
4030 stream()->setHalThreadPriority(priorityBoost);
4031 }
Andy Hung077d62e2023-10-03 10:49:34 -07004032 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004033 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4034 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4035 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4036 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4037 // only on ARC.
4038 const pid_t tid = getTid();
4039 if (tid == -1) {
4040 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4041 } else {
4042 const status_t status = requestPriority(getpid(),
4043 tid,
4044 kPriorityPlaybackThreadArc,
4045 false /* isForApp */,
4046 true /* asynchronous */);
4047 if (status != OK) {
4048 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4049 status);
4050 } else {
4051 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4052 }
4053 }
Andy Hung077d62e2023-10-03 10:49:34 -07004054 }
4055
Andy Hung8d31fd22023-06-26 19:20:57 -07004056 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004057
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004058 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004059 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004060
4061 // MIXER
4062 nsecs_t lastWarning = 0;
4063
4064 // DUPLICATING
4065 // FIXME could this be made local to while loop?
4066 writeFrames = 0;
4067
Andy Hung3f2cee62024-09-17 14:17:15 -07004068 {
4069 audio_utils::lock_guard l(mutex());
4070
4071 cacheParameters_l();
4072 checkSilentMode_l();
4073 }
4074
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004075 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004076
Andy Hungd3639922022-04-28 18:00:49 -07004077 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004078 sleepTimeShift = 0;
4079 }
4080
4081 CpuStats cpuStats;
4082 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4083
4084 acquireWakeLock();
4085
Glenn Kasteneef598c2017-04-03 14:41:13 -07004086 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4087 // thread associated with this PlaybackThread.
4088 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4089 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004090 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4091 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004092 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004093 const char *logString = NULL;
4094
rago1bb90822017-05-02 18:31:48 -07004095 // Estimated time for next buffer to be written to hal. This is used only on
4096 // suspended mode (for now) to help schedule the wait time until next iteration.
4097 nsecs_t timeLoopNextNs = 0;
4098
Andy Hung2dbffc22018-08-08 18:50:41 -07004099 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004100
Eric Laurentb3f315a2021-07-13 15:09:05 +02004101 sendCheckOutputStageEffectsEvent();
4102
Andy Hung446f4df2019-02-21 12:26:41 -08004103 // loopCount is used for statistics and diagnostics.
4104 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004105 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004106 // Log merge requests are performed during AudioFlinger binder transactions, but
4107 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004108 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004109
Eric Laurent81784c32012-11-19 14:55:58 -08004110 cpuStats.sample(myName);
4111
Andy Hung116bc262023-06-20 18:56:17 -07004112 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004113 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004114 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004115 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004116
Andy Hung2dbffc22018-08-08 18:50:41 -07004117 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4118 //
Andy Hungc5007f82023-08-29 14:26:09 -07004119 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004120 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004121 // Here, we try for the AF lock, but do not block on it as the latency
4122 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004123 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004124 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004125 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004126 status_t status = INVALID_OPERATION;
4127 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004128 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004129 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004130 && swPatches.size() > 0) {
4131 status = swPatches[0].getLatencyMs_l(&latencyMs);
4132 downstreamPatchHandle = swPatches[0].getPatchHandle();
4133 }
4134 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004135 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004136 lastDownstreamPatchHandle = downstreamPatchHandle;
4137 }
4138 if (status == OK) {
4139 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004140 // latency of 5 seconds).
4141 const double minLatency = 0., maxLatency = 5000.;
4142 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004143 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004144 } else {
4145 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004146 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004147 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004148 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004149 }
Andy Hung583043b2023-07-17 17:05:00 -07004150 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004151 }
4152 } else {
4153 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4154 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004155 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004156 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4157 }
4158 }
4159
Eric Laurentb3f315a2021-07-13 15:09:05 +02004160 if (mCheckOutputStageEffects.exchange(false)) {
4161 checkOutputStageEffects();
4162 }
4163
Vlad Popa7e81cea2023-01-19 16:34:16 +01004164 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004165 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004166
Andy Hungc5007f82023-08-29 14:26:09 -07004167 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004168
Eric Laurent021cf962014-05-13 10:18:14 -07004169 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004170 if (mCheckOutputStageEffects.load()) {
4171 continue;
4172 }
Eric Laurent10351942014-05-08 18:49:52 -07004173
Andy Hungc5007f82023-08-29 14:26:09 -07004174 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004175 if (logString != NULL) {
4176 mNBLogWriter->logTimestamp();
4177 mNBLogWriter->log(logString);
4178 logString = NULL;
4179 }
4180
Dean Wheatley12473e92021-03-18 23:00:55 +11004181 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004182
Eric Laurent81784c32012-11-19 14:55:58 -08004183 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004184 if (mSignalPending) {
4185 // A signal was raised while we were unlocked
4186 mSignalPending = false;
4187 } else if (waitingAsyncCallback_l()) {
4188 if (exitPending()) {
4189 break;
4190 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004191 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004192 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004193 releaseWakeLock_l();
4194 released = true;
4195 }
Andy Hung10cbff12017-02-21 17:30:14 -08004196
4197 const int64_t waitNs = computeWaitTimeNs_l();
4198 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004199 std::cv_status cvstatus =
4200 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4201 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004202 mSignalPending = true; // if timeout recheck everything
4203 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004204 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004205 if (released) {
4206 acquireWakeLock_l();
4207 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004208 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4209 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004210
4211 continue;
4212 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004213 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004214 isSuspended()) {
4215 // put audio hardware into standby after short delay
4216 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004217
4218 threadLoop_standby();
4219
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004220 // This is where we go into standby
4221 if (!mStandby) {
4222 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004223 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004224 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004225 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004226 }
Andy Hungd0979812019-02-21 15:51:44 -08004227 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004228 }
4229
Eric Tan39ec8d62018-07-24 09:49:29 -07004230 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004231 // we're about to wait, flush the binder command buffer
4232 IPCThreadState::self()->flushCommands();
4233
4234 clearOutputTracks();
4235
4236 if (exitPending()) {
4237 break;
4238 }
4239
4240 releaseWakeLock_l();
4241 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004242 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004243 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004244 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004245 acquireWakeLock_l();
4246
4247 mMixerStatus = MIXER_IDLE;
4248 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4249 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004250 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004251 checkSilentMode_l();
4252
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004253 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4254 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004255 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004256 sleepTimeShift = 0;
4257 }
4258
4259 continue;
4260 }
4261 }
Eric Laurent81784c32012-11-19 14:55:58 -08004262 // mMixerStatusIgnoringFastTracks is also updated internally
4263 mMixerStatus = prepareTracks_l(&tracksToRemove);
4264
Andy Hungab65b182023-09-06 19:41:47 -07004265 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004266
Vlad Popa7e81cea2023-01-19 16:34:16 +01004267 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004268
Andy Hungf302e812024-01-26 11:55:15 -08004269 // Acquire a local copy of active tracks with lock (release w/o lock).
4270 //
4271 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4272 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4273 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4274 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4275
4276 setHalLatencyMode_l();
4277
4278 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4279 // so this is done before we lock our effect chains.
4280 for (const auto& track : mActiveTracks) {
4281 track->updateTeePatches_l();
4282 }
4283
4284 // signal actual start of output stream when the render position reported by
4285 // the kernel starts moving.
4286 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4287 && (mKernelPositionOnStandby
4288 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4289 mHalStarted = true;
4290 mWaitHalStartCV.notify_all();
4291 }
4292
Eric Laurent81784c32012-11-19 14:55:58 -08004293 // prevent any changes in effect chain list and in each effect chain
4294 // during mixing and effect process as the audio buffers could be deleted
4295 // or modified if an effect is created or deleted
4296 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004297
4298 // Determine which session to pick up haptic data.
4299 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004300 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004301 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004302 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004303 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004304 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004305 if (effectChain != nullptr
4306 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004307 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004308 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004309 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004310 break;
4311 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004312 if (activeHapticSessionId == AUDIO_SESSION_NONE
4313 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004314 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004315 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004316 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004317 }
4318 }
4319 }
Andy Hungc5007f82023-08-29 14:26:09 -07004320 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004321
Eric Laurentbfb1b832013-01-07 09:53:42 -08004322 if (mBytesRemaining == 0) {
4323 mCurrentWriteLength = 0;
4324 if (mMixerStatus == MIXER_TRACKS_READY) {
4325 // threadLoop_mix() sets mCurrentWriteLength
4326 threadLoop_mix();
4327 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4328 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004329 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004330 // must be written to HAL
4331 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004332 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004333 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004334
4335 // Tally underrun frames as we are inserting 0s here.
4336 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004337 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004338 && !track->isStopped()
4339 && !track->isPaused()
4340 && !track->isTerminated()) {
4341 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4342 __func__, track->id(), track->getTrackStateAsString(),
4343 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004344 track->audioTrackServerProxy()->tallyUnderrunFrames(
4345 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004346 }
4347 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004348 }
4349 }
Andy Hung98ef9782014-03-04 14:46:50 -08004350 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004351 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004352 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004353 // or mSinkBuffer (if there are no effects and there is no data already copied to
4354 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004355 //
4356 // This is done pre-effects computation; if effects change to
4357 // support higher precision, this needs to move.
4358 //
4359 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004360 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004361 uint32_t mixerChannelCount = mEffectBufferValid ?
4362 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004363 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004364 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4365 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4366
David Li88ee0902022-06-22 10:01:21 +08004367 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4368 // do these processes after effects are applied.
4369 if (!mEffectBufferValid) {
4370 // mono blend occurs for mixer threads only (not direct or offloaded)
4371 // and is handled here if we're going directly to the sink.
4372 if (requireMonoBlend()) {
4373 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4374 mNormalFrameCount, true /*limit*/);
4375 }
Andy Hung2ddee192015-12-18 17:34:44 -08004376
David Li88ee0902022-06-22 10:01:21 +08004377 if (!hasFastMixer()) {
4378 // Balance must take effect after mono conversion.
4379 // We do it here if there is no FastMixer.
4380 // mBalance detects zero balance within the class for speed
4381 // (not needed here).
4382 mBalance.setBalance(mMasterBalance.load());
4383 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4384 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004385 }
4386
Andy Hung98ef9782014-03-04 14:46:50 -08004387 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004388 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004389
4390 // If we're going directly to the sink and there are haptic channels,
4391 // we should adjust channels as the sample data is partially interleaved
4392 // in this case.
4393 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4394 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4395 mChannelCount + mHapticChannelCount,
4396 audio_bytes_per_sample(format),
4397 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4398 }
Andy Hung98ef9782014-03-04 14:46:50 -08004399 }
4400
Eric Laurentbfb1b832013-01-07 09:53:42 -08004401 mBytesRemaining = mCurrentWriteLength;
4402 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004403 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4404 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4405 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4406 mBytesWritten += mBytesRemaining;
4407 mFramesWritten += framesRemaining;
4408 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004409 mBytesRemaining = 0;
4410 }
Eric Laurent81784c32012-11-19 14:55:58 -08004411
Eric Laurentbfb1b832013-01-07 09:53:42 -08004412 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004413 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004414 for (size_t i = 0; i < effectChains.size(); i ++) {
4415 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004416 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004417 if (activeHapticSessionId != AUDIO_SESSION_NONE
4418 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004419 // Haptic data is active in this case, copy it directly from
4420 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004421 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4422 audio_channel_count_from_out_mask(mMixerChannelMask) :
4423 mChannelCount;
4424 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4425 hapticSessionChannelCount = mChannelCount;
4426 }
4427
jiabin47affe52019-04-04 18:02:07 -07004428 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004429 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004430 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004431 memcpy_by_audio_format(
4432 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004433 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004434 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004435 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004436 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004437 }
Eric Laurent81784c32012-11-19 14:55:58 -08004438 }
4439 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004440 // Process effect chains for offloaded thread even if no audio
4441 // was read from audio track: process only updates effect state
4442 // and thus does have to be synchronized with audio writes but may have
4443 // to be called while waiting for async write callback
4444 if (mType == OFFLOAD) {
4445 for (size_t i = 0; i < effectChains.size(); i ++) {
4446 effectChains[i]->process_l();
4447 }
4448 }
Eric Laurent81784c32012-11-19 14:55:58 -08004449
Andy Hung98ef9782014-03-04 14:46:50 -08004450 // Only if the Effects buffer is enabled and there is data in the
4451 // Effects buffer (buffer valid), we need to
4452 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004453 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004454 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004455 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004456 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004457 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004458 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004459 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004460 }
4461
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004462 if (!hasFastMixer()) {
4463 // Balance must take effect after mono conversion.
4464 // We do it here if there is no FastMixer.
4465 // mBalance detects zero balance within the class for speed (not needed here).
4466 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004467 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004468 }
4469
Eric Laurentb62d0362021-10-26 17:40:18 +02004470 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4471 // mPostSpatializerBuffer if the haptics track is spatialized.
4472 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4473 // For other thread types, the haptics channels are already in mEffectBuffer.
4474 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4475 const size_t srcBufferSize = mNormalFrameCount *
4476 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4477 mEffectBufferFormat);
4478 const size_t dstBufferSize = mNormalFrameCount
4479 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4480
4481 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4482 mEffectBufferFormat,
4483 (uint8_t*)mEffectBuffer + srcBufferSize,
4484 mEffectBufferFormat,
4485 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004486 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004487 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4488 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4489 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4490 // Clamp PCM float values more than this distance from 0 to insulate
4491 // a HAL which doesn't handle NaN correctly.
4492 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4493 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4494 static_cast<const float*>(effectBuffer),
4495 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4496 } else {
4497 memcpy_by_audio_format(mSinkBuffer, mFormat,
4498 effectBuffer, mEffectBufferFormat, framesToCopy);
4499 }
jiabin245cdd92018-12-07 17:55:15 -08004500 // The sample data is partially interleaved when haptic channels exist,
4501 // we need to adjust channels here.
4502 if (mHapticChannelCount > 0) {
4503 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4504 mChannelCount + mHapticChannelCount,
4505 audio_bytes_per_sample(mFormat),
4506 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4507 }
Andy Hung98ef9782014-03-04 14:46:50 -08004508 }
4509
Eric Laurent81784c32012-11-19 14:55:58 -08004510 // enable changes in effect chain
4511 unlockEffectChains(effectChains);
4512
Vlad Popafce10862023-02-03 10:37:07 +01004513 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004514 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004515 metadataUpdate.playbackMetadataUpdate);
4516 }
4517
Eric Laurentbfb1b832013-01-07 09:53:42 -08004518 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004519 // mSleepTimeUs == 0 means we must write to audio hardware
4520 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004521 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004522 // writePeriodNs is updated >= 0 when ret > 0.
4523 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004524 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004525 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004526 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004527 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004528 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004529 if (ret < 0) {
4530 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004531 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004532 mBytesWritten += ret;
4533 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004534 const int64_t frames = ret / mFrameSize;
4535 mFramesWritten += frames;
4536
4537 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4538 // process information relating to write time.
4539 if (audio_has_proportional_frames(mFormat)) {
4540 // we are in a continuous mixing cycle
4541 if (mMixerStatus == MIXER_TRACKS_READY &&
4542 loopCount == lastLoopCountWritten + 1) {
4543
4544 const double jitterMs =
4545 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4546 {frames, writePeriodNs},
4547 {0, 0} /* lastTimestamp */, mSampleRate);
4548 const double processMs =
4549 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4550
Andy Hung972bec12023-08-31 16:13:39 -07004551 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004552 mIoJitterMs.add(jitterMs);
4553 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004554
4555 if (mPipeSink.get() != nullptr) {
4556 // Using the Monopipe availableToWrite, we estimate the current
4557 // buffer size.
4558 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4559 const ssize_t
4560 availableToWrite = mPipeSink->availableToWrite();
4561 const size_t pipeFrames = monoPipe->maxFrames();
4562 const size_t
4563 remainingFrames = pipeFrames - max(availableToWrite, 0);
4564 mMonopipePipeDepthStats.add(remainingFrames);
4565 }
Andy Hung446f4df2019-02-21 12:26:41 -08004566 }
4567
4568 // write blocked detection
4569 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004570 if ((mType == MIXER || mType == SPATIALIZER)
4571 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004572 mNumDelayedWrites++;
4573 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4574 ATRACE_NAME("underrun");
4575 ALOGW("write blocked for %lld msecs, "
4576 "%d delayed writes, thread %d",
4577 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4578 mNumDelayedWrites, mId);
4579 lastWarning = lastIoEndNs;
4580 }
4581 }
4582 }
4583 // update timing info.
4584 mLastIoBeginNs = lastIoBeginNs;
4585 mLastIoEndNs = lastIoEndNs;
4586 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004587 }
4588 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4589 (mMixerStatus == MIXER_DRAIN_ALL)) {
4590 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004591 }
Andy Hungd3639922022-04-28 18:00:49 -07004592 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004593
4594 if (mThreadThrottle
4595 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004596 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004597 // Limit MixerThread data processing to no more than twice the
4598 // expected processing rate.
4599 //
4600 // This helps prevent underruns with NuPlayer and other applications
4601 // which may set up buffers that are close to the minimum size, or use
4602 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4603 //
4604 // The throttle smooths out sudden large data drains from the device,
4605 // e.g. when it comes out of standby, which often causes problems with
4606 // (1) mixer threads without a fast mixer (which has its own warm-up)
4607 // (2) minimum buffer sized tracks (even if the track is full,
4608 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004609 //
4610 // Total time spent in last processing cycle equals time spent in
4611 // 1. threadLoop_write, as well as time spent in
4612 // 2. threadLoop_mix (significant for heavy mixing, especially
4613 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004614
Andy Hung446f4df2019-02-21 12:26:41 -08004615 // it's OK if deltaMs is an overestimate.
4616
4617 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004618
Ivan Lozanoea04d392017-11-07 14:37:07 -08004619 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004620 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004621 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004622
Andy Hung08fb1742015-05-31 23:22:10 -07004623 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004624 // notify of throttle start on verbose log
4625 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4626 "mixer(%p) throttle begin:"
4627 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004628 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004629 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004630 // Throttle must be attributed to the previous mixer loop's write time
4631 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004632 // This also ensures proper timing statistics.
4633 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004634 } else {
4635 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4636 if (diff > 0) {
4637 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004638 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004639 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004640 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004641 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004642 outDeviceTypes_l(),
4643 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004644 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004645 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4646 }
Andy Hung08fb1742015-05-31 23:22:10 -07004647 }
4648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 }
Eric Laurent81784c32012-11-19 14:55:58 -08004650
Eric Laurentbfb1b832013-01-07 09:53:42 -08004651 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004652 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004653 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004654 // suspended requires accurate metering of sleep time.
4655 if (isSuspended()) {
4656 // advance by expected sleepTime
4657 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4658 const nsecs_t nowNs = systemTime();
4659
4660 // compute expected next time vs current time.
4661 // (negative deltas are treated as delays).
4662 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4663 if (deltaNs < -kMaxNextBufferDelayNs) {
4664 // Delays longer than the max allowed trigger a reset.
4665 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4666 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4667 timeLoopNextNs = nowNs + deltaNs;
4668 } else if (deltaNs < 0) {
4669 // Delays within the max delay allowed: zero the delta/sleepTime
4670 // to help the system catch up in the next iteration(s)
4671 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4672 deltaNs = 0;
4673 }
4674 // update sleep time (which is >= 0)
4675 mSleepTimeUs = deltaNs / 1000;
4676 }
Eric Laurente93cc032016-05-05 10:15:10 -07004677 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004678 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004679 }
Glenn Kastene7754022014-10-31 12:11:26 -07004680 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004681 }
Eric Laurent81784c32012-11-19 14:55:58 -08004682 }
4683
4684 // Finally let go of removed track(s), without the lock held
4685 // since we can't guarantee the destructors won't acquire that
4686 // same lock. This will also mutate and push a new fast mixer state.
4687 threadLoop_removeTracks(tracksToRemove);
4688 tracksToRemove.clear();
4689
4690 // FIXME I don't understand the need for this here;
4691 // it was in the original code but maybe the
4692 // assignment in saveOutputTracks() makes this unnecessary?
4693 clearOutputTracks();
4694
4695 // Effect chains will be actually deleted here if they were removed from
4696 // mEffectChains list during mixing or effects processing
4697 effectChains.clear();
4698
4699 // FIXME Note that the above .clear() is no longer necessary since effectChains
4700 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004701
4702 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004703 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004704 mThreadloopExecutor.process(); // process any remaining deferred actions.
4705 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004706
Eric Laurentbfb1b832013-01-07 09:53:42 -08004707 threadLoop_exit();
4708
Eric Laurentcf817a22014-08-04 20:36:31 -07004709 if (!mStandby) {
4710 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004711 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004712 }
4713
4714 releaseWakeLock();
4715
4716 ALOGV("Thread %p type %d exiting", this, mType);
4717 return false;
4718}
4719
Andy Hungee58e4a2023-07-07 13:47:37 -07004720void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004721{
Dean Wheatley12473e92021-03-18 23:00:55 +11004722 if (mStandby) {
4723 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4724 return;
4725 } else if (mHwPaused) {
4726 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4727 return;
4728 }
4729
4730 // Gather the framesReleased counters for all active tracks,
4731 // and associate with the sink frames written out. We need
4732 // this to convert the sink timestamp to the track timestamp.
4733 bool kernelLocationUpdate = false;
4734 ExtendedTimestamp timestamp; // use private copy to fetch
4735
4736 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4737 // HAL may be draining some small duration buffered data for fade out.
4738 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4739 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4740 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4741 mSampleRate);
4742
Andy Hungab65b182023-09-06 19:41:47 -07004743 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004744 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4745 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4746 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4747 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4748 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4749 = correctedTimestamp.mFrames;
4750 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4751 = correctedTimestamp.mTimeNs;
4752 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4753 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4754 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4755
4756 // Note: Downstream latency only added if timestamp correction enabled.
4757 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4758 const int64_t newPosition =
4759 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4760 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4761 // prevent retrograde
4762 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4763 newPosition,
4764 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4765 - mSuspendedFrames));
4766 }
4767 }
4768
4769 // We always fetch the timestamp here because often the downstream
4770 // sink will block while writing.
4771
4772 // We keep track of the last valid kernel position in case we are in underrun
4773 // and the normal mixer period is the same as the fast mixer period, or there
4774 // is some error from the HAL.
4775 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4776 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4777 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4778 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4779 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4780
4781 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4782 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4783 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4784 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4785 }
4786
4787 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4788 kernelLocationUpdate = true;
4789 } else {
4790 ALOGVV("getTimestamp error - no valid kernel position");
4791 }
4792
4793 // copy over kernel info
4794 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4795 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4796 + mSuspendedFrames; // add frames discarded when suspended
4797 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4798 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4799 } else {
4800 mTimestampVerifier.error();
4801 }
4802
4803 // mFramesWritten for non-offloaded tracks are contiguous
4804 // even after standby() is called. This is useful for the track frame
4805 // to sink frame mapping.
4806 bool serverLocationUpdate = false;
4807 if (mFramesWritten != mLastFramesWritten) {
4808 serverLocationUpdate = true;
4809 mLastFramesWritten = mFramesWritten;
4810 }
4811 // Only update timestamps if there is a meaningful change.
4812 // Either the kernel timestamp must be valid or we have written something.
4813 if (kernelLocationUpdate || serverLocationUpdate) {
4814 if (serverLocationUpdate) {
4815 // use the time before we called the HAL write - it is a bit more accurate
4816 // to when the server last read data than the current time here.
4817 //
4818 // If we haven't written anything, mLastIoBeginNs will be -1
4819 // and we use systemTime().
4820 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4821 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004822 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004823 }
4824
Andy Hung8d31fd22023-06-26 19:20:57 -07004825 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004826 if (!t->isFastTrack()) {
4827 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004828 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004829 mFramesWritten,
4830 mSampleRate,
4831 mTimestamp);
4832 }
4833 }
4834 }
4835
4836 if (audio_has_proportional_frames(mFormat)) {
4837 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4838 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4839 mLatencyMs.add(latencyMs);
4840 }
4841 }
4842#if 0
4843 // logFormat example
4844 if (z % 100 == 0) {
4845 timespec ts;
4846 clock_gettime(CLOCK_MONOTONIC, &ts);
4847 LOGT("This is an integer %d, this is a float %f, this is my "
4848 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4849 LOGT("A deceptive null-terminated string %\0");
4850 }
4851 ++z;
4852#endif
4853}
4854
Andy Hungc5007f82023-08-29 14:26:09 -07004855// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004856void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004857NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004858{
Andy Hung6c498e92023-12-05 17:28:17 -08004859 if (tracksToRemove.empty()) return;
4860
4861 // Block all incoming TrackHandle requests until we are finished with the release.
4862 setThreadBusy_l(true);
4863
Andy Hungfe726a62018-09-27 15:17:25 -07004864 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004865 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004866 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004867 if (chain != 0) {
4868 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4869 __func__, track->id(), chain.get(), track->sessionId());
4870 chain->decActiveTrackCnt();
4871 }
Andy Hung6c498e92023-12-05 17:28:17 -08004872
Andy Hungfe726a62018-09-27 15:17:25 -07004873 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004874 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004875 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004876 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004877 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004878 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004879 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004880 }
Andy Hung6c498e92023-12-05 17:28:17 -08004881 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004882 }
jiabineb3bda02020-06-30 14:07:03 -07004883 if (mHapticChannelCount > 0 &&
4884 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004885 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004886 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004887 // Unlock due to VibratorService will lock for this call and will
4888 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004889 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004890 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004891
4892 // When the track is stop, set the haptic intensity as MUTE
4893 // for the HapticGenerator effect.
4894 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004895 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004896 }
jiabin245cdd92018-12-07 17:55:15 -08004897 }
Andy Hung6c498e92023-12-05 17:28:17 -08004898
4899 // Under lock, the track is removed from the active tracks list.
4900 //
4901 // Once the track is no longer active, the TrackHandle may directly
4902 // modify it as the threadLoop() is no longer responsible for its maintenance.
4903 // Do not modify the track from threadLoop after the mutex is unlocked
4904 // if it is not active.
4905 mActiveTracks.remove(track);
4906
4907 if (track->isTerminated()) {
4908 // remove from our tracks vector
4909 removeTrack_l(track);
4910 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004911 }
Andy Hung6c498e92023-12-05 17:28:17 -08004912
4913 // Allow incoming TrackHandle requests. We still hold the mutex,
4914 // so pending TrackHandle requests will occur after we unlock it.
4915 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004916}
Eric Laurent81784c32012-11-19 14:55:58 -08004917
Andy Hungee58e4a2023-07-07 13:47:37 -07004918status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004919{
4920 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004921 ExtendedTimestamp ets;
4922 status_t status = mNormalSink->getTimestamp(ets);
4923 if (status == NO_ERROR) {
4924 status = ets.getBestTimestamp(&timestamp);
4925 }
4926 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004927 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004928 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004929 collectTimestamps_l();
4930 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4931 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004932 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004933 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4934 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4935 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4936 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4937 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004938 }
4939 return INVALID_OPERATION;
4940}
Eric Laurent1c333e22014-05-20 10:48:17 -07004941
Eric Laurenteab90452019-06-24 15:17:46 -07004942// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4943// still applied by the mixer.
4944// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4945// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4946// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004947status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004948{
4949 status_t result = NO_ERROR;
4950 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4951 if (*volume != mLeftVolFloat) {
4952 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004953 // HAL can return INVALID_OPERATION if operation is not supported.
4954 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004955 "Error when setting output stream volume: %d", result);
4956 if (result == NO_ERROR) {
4957 mLeftVolFloat = *volume;
4958 }
4959 }
4960 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4961 // remove stream volume contribution from software volume.
4962 if (mLeftVolFloat == *volume) {
4963 *volume = 1.0f;
4964 }
4965 }
4966 return result;
4967}
4968
Andy Hungee58e4a2023-07-07 13:47:37 -07004969status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004970 audio_patch_handle_t *handle)
4971{
Andy Hungf60abce2016-08-26 11:37:54 -07004972 status_t status;
4973 if (property_get_bool("af.patch_park", false /* default_value */)) {
4974 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4975 // or if HAL does not properly lock against access.
4976 AutoPark<FastMixer> park(mFastMixer);
4977 status = PlaybackThread::createAudioPatch_l(patch, handle);
4978 } else {
4979 status = PlaybackThread::createAudioPatch_l(patch, handle);
4980 }
Eric Laurentb0463942022-12-20 16:31:10 +01004981
4982 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004983 return status;
4984}
4985
Andy Hungee58e4a2023-07-07 13:47:37 -07004986status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004987 audio_patch_handle_t *handle)
4988{
4989 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004990
4991 // store new device and send to effects
4992 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004993 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004994 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004995 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4996 && !mOutput->audioHwDev->supportsAudioPatches(),
4997 "Enumerated device type(%#x) must not be used "
4998 "as it does not support audio patches",
4999 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07005000 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07005001 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
5002 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07005003 }
5004
François Gaffie0c280aa2018-07-25 10:02:15 +02005005 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07005006#ifdef ADD_BATTERY_DATA
5007 // when changing the audio output device, call addBatteryData to notify
5008 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07005009 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005010 uint32_t params = 0;
5011 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07005012 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005013 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07005014 }
5015
Eric Laurent054d9d32015-04-24 08:48:48 -07005016 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07005017 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005018 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5019 }
5020
5021 if (params != 0) {
5022 addBatteryData(params);
5023 }
5024 }
5025#endif
5026
5027 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08005028 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005029 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005030
jiabinc52b1ff2019-10-31 17:20:42 -07005031 // mPatch.num_sinks is not set when the thread is created so that
5032 // the first patch creation triggers an ioConfigChanged callback
5033 bool configChanged = (mPatch.num_sinks == 0) ||
5034 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005035 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005036 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005037 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005038
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005039 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005040 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5041 status = hwDevice->createAudioPatch(patch->num_sources,
5042 patch->sources,
5043 patch->num_sinks,
5044 patch->sinks,
5045 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005046 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005047 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005048 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005049 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005050 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005051
5052 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005053 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005054 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005055 // also dispatch to active AudioTracks for MediaMetrics
5056 for (const auto &track : mActiveTracks) {
5057 track->logEndInterval();
5058 track->logBeginInterval(patchSinksAsString);
5059 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005060
Eric Laurente8726fe2015-06-26 09:39:24 -07005061 if (configChanged) {
5062 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5063 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005064 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005065 mActiveTracks.setHasChanged();
5066
Eric Laurent1c333e22014-05-20 10:48:17 -07005067 return status;
5068}
5069
Andy Hungee58e4a2023-07-07 13:47:37 -07005070status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005071{
Andy Hungf60abce2016-08-26 11:37:54 -07005072 status_t status;
5073 if (property_get_bool("af.patch_park", false /* default_value */)) {
5074 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5075 // or if HAL does not properly lock against access.
5076 AutoPark<FastMixer> park(mFastMixer);
5077 status = PlaybackThread::releaseAudioPatch_l(handle);
5078 } else {
5079 status = PlaybackThread::releaseAudioPatch_l(handle);
5080 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005081 return status;
5082}
5083
Andy Hungee58e4a2023-07-07 13:47:37 -07005084status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005085{
5086 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005087
jiabinc52b1ff2019-10-31 17:20:42 -07005088 mPatch = audio_patch{};
5089 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005090
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005091 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005092 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5093 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005094 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005095 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005096 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005097 // Force meteadata update after a route change
5098 mActiveTracks.setHasChanged();
5099
Eric Laurent1c333e22014-05-20 10:48:17 -07005100 return status;
5101}
5102
Andy Hungee58e4a2023-07-07 13:47:37 -07005103void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005104{
Andy Hung972bec12023-08-31 16:13:39 -07005105 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005106 mTracks.add(track);
5107}
5108
Andy Hungee58e4a2023-07-07 13:47:37 -07005109void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005110{
Andy Hung972bec12023-08-31 16:13:39 -07005111 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005112 destroyTrack_l(track);
5113}
5114
Andy Hungee58e4a2023-07-07 13:47:37 -07005115void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005116{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005117 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005118 config->role = AUDIO_PORT_ROLE_SOURCE;
5119 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5120 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005121 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5122 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5123 config->flags.output = mOutput->flags;
5124 }
Eric Laurent83b88082014-06-20 18:31:16 -07005125}
5126
Eric Laurent81784c32012-11-19 14:55:58 -08005127// ----------------------------------------------------------------------------
5128
Andy Hungee58e4a2023-07-07 13:47:37 -07005129/* static */
5130sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005131 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005132 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005133 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005134}
5135
Andy Hung583043b2023-07-17 17:05:00 -07005136MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005137 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005138 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005139 // mAudioMixer below
5140 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005141 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005142 mFastMixerFutex(0),
5143 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005144 // mOutputSink below
5145 // mPipeSink below
5146 // mNormalSink below
5147{
jiabinc52b1ff2019-10-31 17:20:42 -07005148 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005149 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005150 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005151 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5152 mNormalFrameCount);
5153 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5154
Andy Hungfbfc3952015-01-15 13:33:51 -08005155 if (type == DUPLICATING) {
5156 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5157 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5158 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005159 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5160 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005161 return;
5162 }
Eric Laurent81784c32012-11-19 14:55:58 -08005163 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005164 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005165 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005166 const NBAIO_Format offers[1] = {Format_from_SR_C(
5167 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005168#if !LOG_NDEBUG
5169 ssize_t index =
5170#else
5171 (void)
5172#endif
5173 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005174 ALOG_ASSERT(index == 0);
5175
5176 // initialize fast mixer depending on configuration
5177 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005178 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005179 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005180 } else {
5181 switch (kUseFastMixer) {
5182 case FastMixer_Never:
5183 initFastMixer = false;
5184 break;
5185 case FastMixer_Always:
5186 initFastMixer = true;
5187 break;
5188 case FastMixer_Static:
5189 case FastMixer_Dynamic:
5190 initFastMixer = mFrameCount < mNormalFrameCount;
5191 break;
5192 }
5193 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5194 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5195 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005196 }
5197 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005198 audio_format_t fastMixerFormat;
5199 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5200 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5201 } else {
5202 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5203 }
5204 if (mFormat != fastMixerFormat) {
5205 // change our Sink format to accept our intermediate precision
5206 mFormat = fastMixerFormat;
5207 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005208 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005209 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5210 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5211 }
Eric Laurent81784c32012-11-19 14:55:58 -08005212
5213 // create a MonoPipe to connect our submix to FastMixer
5214 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005215
Andy Hung1258c1a2014-05-23 21:22:17 -07005216 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005217 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005218 format.mFormat = fastMixerFormat;
5219 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5220
Eric Laurent81784c32012-11-19 14:55:58 -08005221 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5222 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5223 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5224 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005225 const NBAIO_Format offersFast[1] = {format};
5226 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005227#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005228 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005229#else
5230 (void)
5231#endif
Andy Hung920f6572022-10-06 12:09:49 -07005232 monoPipe->negotiate(offersFast, std::size(offersFast),
5233 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005234 ALOG_ASSERT(index == 0);
5235 monoPipe->setAvgFrames((mScreenState & 1) ?
5236 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5237 mPipeSink = monoPipe;
5238
Eric Laurent81784c32012-11-19 14:55:58 -08005239 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005240 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005241 FastMixerStateQueue *sq = mFastMixer->sq();
5242#ifdef STATE_QUEUE_DUMP
5243 sq->setObserverDump(&mStateQueueObserverDump);
5244 sq->setMutatorDump(&mStateQueueMutatorDump);
5245#endif
5246 FastMixerState *state = sq->begin();
5247 FastTrack *fastTrack = &state->mFastTracks[0];
5248 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5249 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5250 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005251 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5252 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5253 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005254 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005255 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005256 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005257 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005258 fastTrack->mGeneration++;
5259 state->mFastTracksGen++;
5260 state->mTrackMask = 1;
5261 // fast mixer will use the HAL output sink
5262 state->mOutputSink = mOutputSink.get();
5263 state->mOutputSinkGen++;
5264 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005265 // specify sink channel mask when haptic channel mask present as it can not
5266 // be calculated directly from channel count
5267 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005268 ? AUDIO_CHANNEL_NONE
5269 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005270 state->mCommand = FastMixerState::COLD_IDLE;
5271 // already done in constructor initialization list
5272 //mFastMixerFutex = 0;
5273 state->mColdFutexAddr = &mFastMixerFutex;
5274 state->mColdGen++;
5275 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005276 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005277 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005278 sq->end();
5279 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5280
Eric Tan0513b5d2018-09-17 10:32:48 -07005281 NBLog::thread_info_t info;
5282 info.id = mId;
5283 info.type = NBLog::FASTMIXER;
5284 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5285
Eric Laurent81784c32012-11-19 14:55:58 -08005286 // start the fast mixer
5287 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5288 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005289 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005290 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005291
5292#ifdef AUDIO_WATCHDOG
5293 // create and start the watchdog
5294 mAudioWatchdog = new AudioWatchdog();
5295 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5296 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5297 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005298 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005299#endif
Andy Hung8946a282018-04-19 20:04:56 -07005300 } else {
5301#ifdef TEE_SINK
5302 // Only use the MixerThread tee if there is no FastMixer.
5303 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5304 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5305#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005306 }
5307
5308 switch (kUseFastMixer) {
5309 case FastMixer_Never:
5310 case FastMixer_Dynamic:
5311 mNormalSink = mOutputSink;
5312 break;
5313 case FastMixer_Always:
5314 mNormalSink = mPipeSink;
5315 break;
5316 case FastMixer_Static:
5317 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5318 break;
5319 }
Andy Hung922617c2024-06-25 17:07:58 -07005320 // setMasterBalance needs to be called after the FastMixer
5321 // (if any) is set up, in order to deliver the balance settings to it.
5322 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005323}
5324
Andy Hungee58e4a2023-07-07 13:47:37 -07005325MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005326{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005327 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005328 FastMixerStateQueue *sq = mFastMixer->sq();
5329 FastMixerState *state = sq->begin();
5330 if (state->mCommand == FastMixerState::COLD_IDLE) {
5331 int32_t old = android_atomic_inc(&mFastMixerFutex);
5332 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005333 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005334 }
5335 }
5336 state->mCommand = FastMixerState::EXIT;
5337 sq->end();
5338 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5339 mFastMixer->join();
5340 // Though the fast mixer thread has exited, it's state queue is still valid.
5341 // We'll use that extract the final state which contains one remaining fast track
5342 // corresponding to our sub-mix.
5343 state = sq->begin();
5344 ALOG_ASSERT(state->mTrackMask == 1);
5345 FastTrack *fastTrack = &state->mFastTracks[0];
5346 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5347 delete fastTrack->mBufferProvider;
5348 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005349 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005350#ifdef AUDIO_WATCHDOG
5351 if (mAudioWatchdog != 0) {
5352 mAudioWatchdog->requestExit();
5353 mAudioWatchdog->requestExitAndWait();
5354 mAudioWatchdog.clear();
5355 }
5356#endif
5357 }
Andy Hung583043b2023-07-17 17:05:00 -07005358 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005359 delete mAudioMixer;
5360}
5361
Andy Hungee58e4a2023-07-07 13:47:37 -07005362void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005363 PlaybackThread::onFirstRef();
5364
Andy Hung972bec12023-08-31 16:13:39 -07005365 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005366 if (mOutput != nullptr && mOutput->stream != nullptr) {
5367 status_t status = mOutput->stream->setLatencyModeCallback(this);
5368 if (status != INVALID_OPERATION) {
5369 updateHalSupportedLatencyModes_l();
5370 }
5371 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5372 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5373 mBluetoothLatencyModesEnabled.store(
5374 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5375 }
5376}
Eric Laurent81784c32012-11-19 14:55:58 -08005377
Andy Hungee58e4a2023-07-07 13:47:37 -07005378uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005379{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005380 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005381 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5382 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5383 }
5384 return latency;
5385}
5386
Andy Hungee58e4a2023-07-07 13:47:37 -07005387ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005388{
5389 // FIXME we should only do one push per cycle; confirm this is true
5390 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005391 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005392 FastMixerStateQueue *sq = mFastMixer->sq();
5393 FastMixerState *state = sq->begin();
5394 if (state->mCommand != FastMixerState::MIX_WRITE &&
5395 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5396 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005397
5398 // FIXME workaround for first HAL write being CPU bound on some devices
5399 ATRACE_BEGIN("write");
5400 mOutput->write((char *)mSinkBuffer, 0);
5401 ATRACE_END();
5402
Eric Laurent81784c32012-11-19 14:55:58 -08005403 int32_t old = android_atomic_inc(&mFastMixerFutex);
5404 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005405 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005406 }
5407#ifdef AUDIO_WATCHDOG
5408 if (mAudioWatchdog != 0) {
5409 mAudioWatchdog->resume();
5410 }
5411#endif
5412 }
5413 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005414#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005415 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005416 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005417#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005418 sq->end();
5419 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5420 if (kUseFastMixer == FastMixer_Dynamic) {
5421 mNormalSink = mPipeSink;
5422 }
5423 } else {
5424 sq->end(false /*didModify*/);
5425 }
5426 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005427 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005428}
5429
Andy Hungee58e4a2023-07-07 13:47:37 -07005430void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005431{
5432 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005433 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005434 FastMixerStateQueue *sq = mFastMixer->sq();
5435 FastMixerState *state = sq->begin();
5436 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005437 // Report any frames trapped in the Monopipe
5438 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5439 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5440 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5441 "monoPipeWritten:%lld monoPipeLeft:%lld",
5442 (long long)mFramesWritten, (long long)mSuspendedFrames,
5443 (long long)mPipeSink->framesWritten(), pipeFrames);
5444 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5445
Eric Laurent81784c32012-11-19 14:55:58 -08005446 state->mCommand = FastMixerState::COLD_IDLE;
5447 state->mColdFutexAddr = &mFastMixerFutex;
5448 state->mColdGen++;
5449 mFastMixerFutex = 0;
5450 sq->end();
5451 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5452 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5453 if (kUseFastMixer == FastMixer_Dynamic) {
5454 mNormalSink = mOutputSink;
5455 }
5456#ifdef AUDIO_WATCHDOG
5457 if (mAudioWatchdog != 0) {
5458 mAudioWatchdog->pause();
5459 }
5460#endif
5461 } else {
5462 sq->end(false /*didModify*/);
5463 }
5464 }
5465 PlaybackThread::threadLoop_standby();
5466}
5467
Andy Hungee58e4a2023-07-07 13:47:37 -07005468bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005469{
5470 return false;
5471}
5472
Andy Hungee58e4a2023-07-07 13:47:37 -07005473bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005474{
5475 return !mStandby;
5476}
5477
Andy Hungee58e4a2023-07-07 13:47:37 -07005478bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005479{
Andy Hung972bec12023-08-31 16:13:39 -07005480 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005481 return waitingAsyncCallback_l();
5482}
5483
Eric Laurent81784c32012-11-19 14:55:58 -08005484// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005485void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005486{
Andy Hung8d672e02023-09-15 18:19:28 -07005487 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5488 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005489 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005490 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005491 // discard any pending drain or write ack by incrementing sequence
5492 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5493 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005494 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005495 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5496 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005497 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005498 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005499 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005500}
5501
Andy Hungee58e4a2023-07-07 13:47:37 -07005502void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005503{
5504 ALOGV("signal playback thread");
5505 broadcast_l();
5506}
5507
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005508void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005509{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005510 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005511 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5512 invalidateTracks((audio_stream_type_t)i);
5513 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005514 if (isHardError) {
5515 mAfThreadCallback->onHardError(allTrackPortIds);
5516 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005517}
5518
Andy Hungee58e4a2023-07-07 13:47:37 -07005519void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005520{
Eric Laurent81784c32012-11-19 14:55:58 -08005521 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005522 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005523 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005524 // increase sleep time progressively when application underrun condition clears.
5525 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5526 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5527 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005528 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005529 sleepTimeShift--;
5530 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005531 mSleepTimeUs = 0;
5532 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005533 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005534
Eric Laurent81784c32012-11-19 14:55:58 -08005535}
5536
Andy Hungee58e4a2023-07-07 13:47:37 -07005537void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005538{
5539 // If no tracks are ready, sleep once for the duration of an output
5540 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005541 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005542 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005543 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5544 // Using the Monopipe availableToWrite, we estimate the
5545 // sleep time to retry for more data (before we underrun).
5546 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5547 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5548 const size_t pipeFrames = monoPipe->maxFrames();
5549 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5550 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5551 const size_t framesDelay = std::min(
5552 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5553 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5554 pipeFrames, framesLeft, framesDelay);
5555 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5556 } else {
5557 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5558 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5559 mSleepTimeUs = kMinThreadSleepTimeUs;
5560 }
5561 // reduce sleep time in case of consecutive application underruns to avoid
5562 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5563 // duration we would end up writing less data than needed by the audio HAL if
5564 // the condition persists.
5565 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5566 sleepTimeShift++;
5567 }
Eric Laurent81784c32012-11-19 14:55:58 -08005568 }
5569 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005570 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005571 }
5572 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005573 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5574 // before effects processing or output.
5575 if (mMixerBufferValid) {
5576 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005577 if (mType == SPATIALIZER) {
5578 memset(mSinkBuffer, 0, mSinkBufferSize);
5579 }
Andy Hung98ef9782014-03-04 14:46:50 -08005580 } else {
5581 memset(mSinkBuffer, 0, mSinkBufferSize);
5582 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005583 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5585 "anticipated start");
5586 }
5587 // TODO add standby time extension fct of effect tail
5588}
5589
Andy Hungc5007f82023-08-29 14:26:09 -07005590// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005591PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005592 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005593{
Andy Hungc0691382018-09-12 18:01:57 -07005594 // clean up deleted track ids in AudioMixer before allocating new tracks
5595 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5596 // for each trackId, destroy it in the AudioMixer
5597 if (mAudioMixer->exists(trackId)) {
5598 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005599 }
5600 });
Andy Hungc0691382018-09-12 18:01:57 -07005601 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005602
5603 mixer_state mixerStatus = MIXER_IDLE;
5604 // find out which tracks need to be processed
5605 size_t count = mActiveTracks.size();
5606 size_t mixedTracks = 0;
5607 size_t tracksWithEffect = 0;
5608 // counts only _active_ fast tracks
5609 size_t fastTracks = 0;
5610 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5611
5612 float masterVolume = mMasterVolume;
5613 bool masterMute = mMasterMute;
5614
5615 if (masterMute) {
5616 masterVolume = 0;
5617 }
5618 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005619 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005620 if (chain != 0) {
5621 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005622 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005623 masterVolume = (float)((v + (1 << 23)) >> 24);
5624 chain.clear();
5625 }
5626
5627 // prepare a new state to push
5628 FastMixerStateQueue *sq = NULL;
5629 FastMixerState *state = NULL;
5630 bool didModify = false;
5631 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005632 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005633 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005634 sq = mFastMixer->sq();
5635 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005636 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005637 }
5638
Andy Hung69aed5f2014-02-25 17:24:40 -08005639 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005640 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005641
Andy Hungbd3b2b02018-05-21 10:53:11 -07005642 // DeferredOperations handles statistics after setting mixerStatus.
5643 class DeferredOperations {
5644 public:
Andy Hungea840382020-05-05 21:50:17 -07005645 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5646 : mMixerStatus(mixerStatus)
5647 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005648
5649 // when leaving scope, tally frames properly.
5650 ~DeferredOperations() {
5651 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5652 // because that is when the underrun occurs.
5653 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005654 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005655 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005656 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005657 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005658 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005659 }
5660 }
Andy Hungea840382020-05-05 21:50:17 -07005661 // send the max underrun frames for this mixer period
5662 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005663 }
5664
5665 // tallyUnderrunFrames() is called to update the track counters
5666 // with the number of underrun frames for a particular mixer period.
5667 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005668 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005669 mUnderrunFrames.emplace_back(track, underrunFrames);
5670 }
5671
5672 private:
5673 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005674 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005675 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005676 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005677 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005678
jiabin245cdd92018-12-07 17:55:15 -08005679 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005680 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005681 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005682
5683 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005684 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005685
5686 // process fast tracks
5687 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005688 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5689 "%s(%d): FastTrack(%d) present without FastMixer",
5690 __func__, id(), track->id());
5691
jiabin245cdd92018-12-07 17:55:15 -08005692 if (track->getHapticPlaybackEnabled()) {
5693 noFastHapticTrack = false;
5694 }
Eric Laurent81784c32012-11-19 14:55:58 -08005695
5696 // It's theoretically possible (though unlikely) for a fast track to be created
5697 // and then removed within the same normal mix cycle. This is not a problem, as
5698 // the track never becomes active so it's fast mixer slot is never touched.
5699 // The converse, of removing an (active) track and then creating a new track
5700 // at the identical fast mixer slot within the same normal mix cycle,
5701 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005702 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005703 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005704 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5705 FastTrack *fastTrack = &state->mFastTracks[j];
5706
5707 // Determine whether the track is currently in underrun condition,
5708 // and whether it had a recent underrun.
5709 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5710 FastTrackUnderruns underruns = ftDump->mUnderruns;
5711 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005712 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005713 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005714 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005715 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005716 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005717 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005718 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005719 // don't count underruns that occur while stopping or pausing
5720 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005721 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005722 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5723 recentUnderruns > 0) {
5724 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005725 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005726 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005727 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005728 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005729
5730 // This is similar to the state machine for normal tracks,
5731 // with a few modifications for fast tracks.
5732 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005733 switch (track->state()) {
5734 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005735 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005736 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005737 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005738 }
5739 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005740 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005741 // ramp down is not yet implemented
5742 track->setPaused();
5743 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005744 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005745 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005746 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005747 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005748 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005749 if (recentFull > 0 || recentPartial > 0) {
5750 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005751 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005752 }
5753 if (recentUnderruns == 0) {
5754 // no recent underruns: stay active
5755 break;
5756 }
5757 // there has recently been an underrun of some kind
5758 if (track->sharedBuffer() == 0) {
5759 // were any of the recent underruns "empty" (no frames available)?
5760 if (recentEmpty == 0) {
5761 // no, then ignore the partial underruns as they are allowed indefinitely
5762 break;
5763 }
5764 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005765 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005766 break;
5767 }
5768 // indicate to client process that the track was disabled because of underrun;
5769 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005770 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005771 // remove from active list, but state remains ACTIVE [confusing but true]
5772 isActive = false;
5773 break;
5774 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005775 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005776 case IAfTrackBase::STOPPING_2:
5777 case IAfTrackBase::PAUSED:
5778 case IAfTrackBase::STOPPED:
5779 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005780 // Check for presentation complete if track is inactive
5781 // We have consumed all the buffers of this track.
5782 // This would be incomplete if we auto-paused on underrun
5783 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005784 uint32_t latency = 0;
5785 status_t result = mOutput->stream->getLatency(&latency);
5786 ALOGE_IF(result != OK,
5787 "Error when retrieving output stream latency: %d", result);
5788 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005789 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005790 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5791 // track stays in active list until presentation is complete
5792 break;
5793 }
5794 }
5795 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005796 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005797 }
5798 if (track->isStopped()) {
5799 // Can't reset directly, as fast mixer is still polling this track
5800 // track->reset();
5801 // So instead mark this track as needing to be reset after push with ack
5802 resetMask |= 1 << i;
5803 }
5804 isActive = false;
5805 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005806 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005807 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005808 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005809 }
5810
5811 if (isActive) {
5812 // was it previously inactive?
5813 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005814 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5815 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005816 fastTrack->mBufferProvider = eabp;
5817 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005818 fastTrack->mChannelMask = track->channelMask();
5819 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005820 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005821 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005822 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005823 fastTrack->mGeneration++;
5824 state->mTrackMask |= 1 << j;
5825 didModify = true;
5826 // no acknowledgement required for newly active tracks
5827 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005828 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005829 float volume;
Andy Hung6b137d12024-08-27 22:35:17 +00005830 if (!audioserver_flags::portid_volume_management()) {
5831 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5832 volume = 0.f;
5833 } else {
5834 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5835 }
Eric Laurenteab90452019-06-24 15:17:46 -07005836 } else {
Andy Hung6b137d12024-08-27 22:35:17 +00005837 if (track->isPlaybackRestricted()) {
5838 volume = 0.f;
5839 } else {
5840 volume = masterVolume * track->getPortVolume();
5841 }
Eric Laurenteab90452019-06-24 15:17:46 -07005842 }
Eric Laurenteab90452019-06-24 15:17:46 -07005843 handleVoipVolume_l(&volume);
5844
Eric Laurent81784c32012-11-19 14:55:58 -08005845 // cache the combined master volume and stream type volume for fast mixer; this
5846 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005847 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005848 proxy->framesReleased()).first;
5849 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005850 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005851 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005852 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5853 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Andy Hung6b137d12024-08-27 22:35:17 +00005854 if (!audioserver_flags::portid_volume_management()) {
5855 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5856 /*muteState=*/{masterVolume == 0.f,
5857 mStreamTypes[track->streamType()].volume == 0.f,
5858 mStreamTypes[track->streamType()].mute,
5859 track->isPlaybackRestricted(),
5860 vlf == 0.f && vrf == 0.f,
5861 vh == 0.f});
5862 } else {
5863 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5864 /*muteState=*/{masterVolume == 0.f,
5865 track->getPortVolume() == 0.f,
5866 /* muteFromStreamMuted= */ false,
5867 track->isPlaybackRestricted(),
5868 vlf == 0.f && vrf == 0.f,
5869 vh == 0.f});
5870 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005871 vlf *= volume;
5872 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005873
jiabin220eea12024-05-17 17:55:20 +00005874 if (track->getInternalMute()) {
5875 vlf = 0.f;
5876 vrf = 0.f;
5877 }
5878
jiabin76d94692022-12-15 21:51:21 +00005879 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005880 ++fastTracks;
5881 } else {
5882 // was it previously active?
5883 if (state->mTrackMask & (1 << j)) {
5884 fastTrack->mBufferProvider = NULL;
5885 fastTrack->mGeneration++;
5886 state->mTrackMask &= ~(1 << j);
5887 didModify = true;
5888 // If any fast tracks were removed, we must wait for acknowledgement
5889 // because we're about to decrement the last sp<> on those tracks.
5890 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5891 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005892 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5893 // AudioTrack may start (which may not be with a start() but with a write()
5894 // after underrun) and immediately paused or released. In that case the
5895 // FastTrack state hasn't had time to update.
5896 // TODO Remove the ALOGW when this theory is confirmed.
5897 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005898 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005899 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005900 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005901 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005902 }
5903 tracksToRemove->add(track);
5904 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005905 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005906 }
jiabin245cdd92018-12-07 17:55:15 -08005907 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5908 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5909 didModify = true;
5910 }
Eric Laurent81784c32012-11-19 14:55:58 -08005911 continue;
5912 }
5913
5914 { // local variable scope to avoid goto warning
5915
5916 audio_track_cblk_t* cblk = track->cblk();
5917
5918 // The first time a track is added we wait
5919 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005920 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005921
5922 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005923 // use the trackId as the AudioMixer name.
5924 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005925 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005926 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005927 track->channelMask(),
5928 track->format(),
5929 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005930 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005931 ALOGW("%s(): AudioMixer cannot create track(%d)"
5932 " mask %#x, format %#x, sessionId %d",
5933 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005934 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005935 tracksToRemove->add(track);
5936 track->invalidate(); // consider it dead.
5937 continue;
5938 }
5939 }
5940
Eric Laurent81784c32012-11-19 14:55:58 -08005941 // make sure that we have enough frames to mix one full buffer.
5942 // enforce this condition only once to enable draining the buffer in case the client
5943 // app does not call stop() and relies on underrun to stop:
5944 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5945 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005946 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005947 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5948 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005949
5950 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005951 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005952 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5953 // add frames already consumed but not yet released by the resampler
5954 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005955 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005956
Eric Laurent81784c32012-11-19 14:55:58 -08005957 uint32_t minFrames = 1;
5958 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5959 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005960 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005961 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005962
5963 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005964 if (ATRACE_ENABLED()) {
5965 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005966 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005967 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005968 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005969 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005970 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005971 !track->isPaused() && !track->isTerminated())
5972 {
Andy Hungc0691382018-09-12 18:01:57 -07005973 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005974
5975 mixedTracks++;
5976
Shunkai Yaof4847652024-01-12 00:25:20 +00005977 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005978 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005979 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005980 if (track->mainBuffer() != mSinkBuffer &&
5981 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005982 if (mEffectBufferEnabled) {
5983 mEffectBufferValid = true; // Later can set directly.
5984 }
Eric Laurent81784c32012-11-19 14:55:58 -08005985 chain = getEffectChain_l(track->sessionId());
5986 // Delegate volume control to effect in track effect chain if needed
5987 if (chain != 0) {
5988 tracksWithEffect++;
5989 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005990 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005991 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005992 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005993 }
5994 }
5995
5996
5997 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005998 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005999 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07006000 track->fillingStatus() = IAfTrack::FS_ACTIVE;
6001 if (track->state() == IAfTrackBase::RESUMING) {
6002 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08006003 // If a new track is paused immediately after start, do not ramp on resume.
6004 if (cblk->mServer != 0) {
6005 param = AudioMixer::RAMP_VOLUME;
6006 }
Eric Laurent81784c32012-11-19 14:55:58 -08006007 }
Andy Hungc0691382018-09-12 18:01:57 -07006008 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07006009 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07006010 // FIXME should not make a decision based on mServer
6011 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006012 // If the track is stopped before the first frame was mixed,
6013 // do not apply ramp
6014 param = AudioMixer::RAMP_VOLUME;
6015 }
6016
6017 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07006018 uint32_t vl, vr; // in U8.24 integer format
6019 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07006020 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07006021 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07006022 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07006023 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07006024 track->audioTrackServerProxy()->framesReleased()).first;
Andy Hung6b137d12024-08-27 22:35:17 +00006025 float v;
6026 if (!audioserver_flags::portid_volume_management()) {
6027 v = masterVolume * mStreamTypes[track->streamType()].volume;
6028 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6029 v = 0;
6030 }
6031 } else {
6032 v = masterVolume * track->getPortVolume();
6033 if (track->isPlaybackRestricted()) {
6034 v = 0;
6035 }
Eric Laurenteab90452019-06-24 15:17:46 -07006036 }
Eric Laurenteab90452019-06-24 15:17:46 -07006037 handleVoipVolume_l(&v);
6038
6039 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006040 vl = vr = 0;
6041 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006042 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006043 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006044 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006045 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6046 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006047 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006048 if (vlf > GAIN_FLOAT_UNITY) {
6049 ALOGV("Track left volume out of range: %.3g", vlf);
6050 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006051 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006052 if (vrf > GAIN_FLOAT_UNITY) {
6053 ALOGV("Track right volume out of range: %.3g", vrf);
6054 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006055 }
Andy Hung6b137d12024-08-27 22:35:17 +00006056 if (!audioserver_flags::portid_volume_management()) {
6057 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6058 /*muteState=*/{masterVolume == 0.f,
6059 mStreamTypes[track->streamType()].volume == 0.f,
6060 mStreamTypes[track->streamType()].mute,
6061 track->isPlaybackRestricted(),
6062 vlf == 0.f && vrf == 0.f,
6063 vh == 0.f});
6064 } else {
6065 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6066 /*muteState=*/{masterVolume == 0.f,
6067 track->getPortVolume() == 0.f,
6068 /* muteFromStreamMuted= */ false,
6069 track->isPlaybackRestricted(),
6070 vlf == 0.f && vrf == 0.f,
6071 vh == 0.f});
6072 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006073 // now apply the master volume and stream type volume and shaper volume
6074 vlf *= v * vh;
6075 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006076 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006077 // then derive vl and vr as U8.24 versions for the effect chain
6078 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6079 vl = (uint32_t) (scaleto8_24 * vlf);
6080 vr = (uint32_t) (scaleto8_24 * vrf);
6081 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006082 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006083 // send level comes from shared memory and so may be corrupt
6084 if (sendLevel > MAX_GAIN_INT) {
6085 ALOGV("Track send level out of range: %04X", sendLevel);
6086 sendLevel = MAX_GAIN_INT;
6087 }
Andy Hung6be49402014-05-30 10:42:03 -07006088 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6089 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006090 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006091
jiabin220eea12024-05-17 17:55:20 +00006092 if (track->getInternalMute()) {
6093 vrf = 0.f;
6094 vlf = 0.f;
6095 }
6096
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006097 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006098
Eric Laurent81784c32012-11-19 14:55:58 -08006099 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006100 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006101 // Do not ramp volume if volume is controlled by effect
6102 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006103 // Update remaining floating point volume levels
6104 vlf = (float)vl / (1 << 24);
6105 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006106 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006107 } else {
6108 // force no volume ramp when volume controller was just disabled or removed
6109 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006110 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006111 param = AudioMixer::VOLUME;
6112 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006113 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006114 }
6115
Eric Laurent81784c32012-11-19 14:55:58 -08006116 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006117 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006118 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006119
Andy Hungc0691382018-09-12 18:01:57 -07006120 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6121 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6122 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006123 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006124 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006125 AudioMixer::TRACK,
6126 AudioMixer::FORMAT, (void *)track->format());
6127 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006128 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006129 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006130 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006131
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006132 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006133 mAudioMixer->setParameter(
6134 trackId,
6135 AudioMixer::TRACK,
6136 AudioMixer::MIXER_CHANNEL_MASK,
6137 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6138 } else {
6139 mAudioMixer->setParameter(
6140 trackId,
6141 AudioMixer::TRACK,
6142 AudioMixer::MIXER_CHANNEL_MASK,
6143 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6144 }
6145
Glenn Kastene3aa6592012-12-04 12:22:46 -08006146 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006147 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006148 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006149 if (reqSampleRate == 0) {
6150 reqSampleRate = mSampleRate;
6151 } else if (reqSampleRate > maxSampleRate) {
6152 reqSampleRate = maxSampleRate;
6153 }
Eric Laurent81784c32012-11-19 14:55:58 -08006154 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006155 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006156 AudioMixer::RESAMPLE,
6157 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006158 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006159
Andy Hung8edb8dc2015-03-26 19:13:55 -07006160 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006161 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006162 AudioMixer::TIMESTRETCH,
6163 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006164 // cast away constness for this generic API.
6165 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006166
Andy Hung69aed5f2014-02-25 17:24:40 -08006167 /*
6168 * Select the appropriate output buffer for the track.
6169 *
Andy Hung98ef9782014-03-04 14:46:50 -08006170 * Tracks with effects go into their own effects chain buffer
6171 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006172 *
6173 * Other tracks can use mMixerBuffer for higher precision
6174 * channel accumulation. If this buffer is enabled
6175 * (mMixerBufferEnabled true), then selected tracks will accumulate
6176 * into it.
6177 *
6178 */
6179 if (mMixerBufferEnabled
6180 && (track->mainBuffer() == mSinkBuffer
6181 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006182 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006183 mAudioMixer->setParameter(
6184 trackId,
6185 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006186 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006187 mAudioMixer->setParameter(
6188 trackId,
6189 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006190 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006191 } else {
6192 mAudioMixer->setParameter(
6193 trackId,
6194 AudioMixer::TRACK,
6195 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6196 mAudioMixer->setParameter(
6197 trackId,
6198 AudioMixer::TRACK,
6199 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6200 // TODO: override track->mainBuffer()?
6201 mMixerBufferValid = true;
6202 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006203 } else {
6204 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006205 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006206 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006207 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006208 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006209 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006210 AudioMixer::TRACK,
6211 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6212 }
Eric Laurent81784c32012-11-19 14:55:58 -08006213 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006214 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006215 AudioMixer::TRACK,
6216 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006217 mAudioMixer->setParameter(
6218 trackId,
6219 AudioMixer::TRACK,
6220 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006221 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006222 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006223 trackId,
6224 AudioMixer::TRACK,
6225 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006226 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006227 mAudioMixer->setParameter(
6228 trackId,
6229 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006230 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006231
6232 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006233 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006234
6235 // If one track is ready, set the mixer ready if:
6236 // - the mixer was not ready during previous round OR
6237 // - no other track is not ready
6238 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6239 mixerStatus != MIXER_TRACKS_ENABLED) {
6240 mixerStatus = MIXER_TRACKS_READY;
6241 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006242
6243 // Enable the next few lines to instrument a test for underrun log handling.
6244 // TODO: Remove when we have a better way of testing the underrun log.
6245#if 0
6246 static int i;
6247 if ((++i & 0xf) == 0) {
6248 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6249 }
6250#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006251 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006252 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006253 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006254 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6255 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006256 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006257 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006258 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006259
Eric Laurent81784c32012-11-19 14:55:58 -08006260 // clear effect chain input buffer if an active track underruns to avoid sending
6261 // previous audio buffer again to effects
6262 chain = getEffectChain_l(track->sessionId());
6263 if (chain != 0) {
6264 chain->clearInputBuffer();
6265 }
6266
Andy Hungc0691382018-09-12 18:01:57 -07006267 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006268 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6269 track->isStopped() || track->isPaused()) {
6270 // We have consumed all the buffers of this track.
6271 // Remove it from the list of active tracks.
6272 // TODO: use actual buffer filling status instead of latency when available from
6273 // audio HAL
6274 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006275 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006276 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6277 if (track->isStopped()) {
6278 track->reset();
6279 }
6280 tracksToRemove->add(track);
6281 }
6282 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006283 // No buffers for this track. Give it a few chances to
6284 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006285 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006286 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6287 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006288 tracksToRemove->add(track);
6289 // indicate to client process that the track was disabled because of underrun;
6290 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006291 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006292 // If one track is not ready, mark the mixer also not ready if:
6293 // - the mixer was ready during previous round OR
6294 // - no other track is ready
6295 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6296 mixerStatus != MIXER_TRACKS_READY) {
6297 mixerStatus = MIXER_TRACKS_ENABLED;
6298 }
6299 }
Andy Hungc0691382018-09-12 18:01:57 -07006300 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006301 }
6302
6303 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006304
6305 }
6306
jiabin245cdd92018-12-07 17:55:15 -08006307 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6308 // When there is no fast track playing haptic and FastMixer exists,
6309 // enabling the first FastTrack, which provides mixed data from normal
6310 // tracks, to play haptic data.
6311 FastTrack *fastTrack = &state->mFastTracks[0];
6312 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6313 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6314 didModify = true;
6315 }
6316 }
6317
Eric Laurent81784c32012-11-19 14:55:58 -08006318 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006319 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006320 if (didModify) {
6321 state->mFastTracksGen++;
6322 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6323 if (kUseFastMixer == FastMixer_Dynamic &&
6324 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6325 state->mCommand = FastMixerState::COLD_IDLE;
6326 state->mColdFutexAddr = &mFastMixerFutex;
6327 state->mColdGen++;
6328 mFastMixerFutex = 0;
6329 if (kUseFastMixer == FastMixer_Dynamic) {
6330 mNormalSink = mOutputSink;
6331 }
6332 // If we go into cold idle, need to wait for acknowledgement
6333 // so that fast mixer stops doing I/O.
6334 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6335 pauseAudioWatchdog = true;
6336 }
Eric Laurent81784c32012-11-19 14:55:58 -08006337 }
6338 if (sq != NULL) {
6339 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006340 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6341 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6342 // when bringing the output sink into standby.)
6343 //
6344 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6345 //
6346 // This occurs with BT suspend when we idle the FastMixer with
6347 // active tracks, which may be added or removed.
6348 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006349 }
6350#ifdef AUDIO_WATCHDOG
6351 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6352 mAudioWatchdog->pause();
6353 }
6354#endif
6355
6356 // Now perform the deferred reset on fast tracks that have stopped
6357 while (resetMask != 0) {
6358 size_t i = __builtin_ctz(resetMask);
6359 ALOG_ASSERT(i < count);
6360 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006361 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006362 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6363 track->reset();
6364 }
6365
Andy Hung80d03d22018-04-10 10:32:11 -07006366 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6367 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6368 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6369 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6370 // See also the implementation of destroyTrack_l().
6371 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006372 const int trackId = track->id();
6373 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6374 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006375 }
6376 }
6377
Eric Laurent81784c32012-11-19 14:55:58 -08006378 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006379 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006380
Eric Laurentb3f315a2021-07-13 15:09:05 +02006381 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6382 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006383 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006384 }
6385
6386 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006387 // as long as there are effects we should clear the effects buffer, to avoid
6388 // passing a non-clean buffer to the effect chain
6389 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006390 if (mType == SPATIALIZER) {
6391 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6392 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006393 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006394 // sink or mix buffer must be cleared if all tracks are connected to an
6395 // effect chain as in this case the mixer will not write to the sink or mix buffer
6396 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006397 // always clear sink buffer for spatializer output as the output of the spatializer
6398 // effect will be accumulated into it
6399 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6400 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006401 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006402 if (mMixerBufferValid) {
6403 memset(mMixerBuffer, 0, mMixerBufferSize);
6404 // TODO: In testing, mSinkBuffer below need not be cleared because
6405 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6406 // after mixing.
6407 //
6408 // To enforce this guarantee:
6409 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6410 // (mixedTracks == 0 && fastTracks > 0))
6411 // must imply MIXER_TRACKS_READY.
6412 // Later, we may clear buffers regardless, and skip much of this logic.
6413 }
Andy Hung98ef9782014-03-04 14:46:50 -08006414 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006415 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006416 }
6417
6418 // if any fast tracks, then status is ready
6419 mMixerStatusIgnoringFastTracks = mixerStatus;
6420 if (fastTracks > 0) {
6421 mixerStatus = MIXER_TRACKS_READY;
6422 }
6423 return mixerStatus;
6424}
6425
Andy Hungc5007f82023-08-29 14:26:09 -07006426// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006427uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006428{
6429 uint32_t trackCount = 0;
6430 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006431 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006432 trackCount++;
6433 }
6434 }
6435 return trackCount;
6436}
6437
Andy Hungee58e4a2023-07-07 13:47:37 -07006438bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006439{
Brian Lindahl65e90012022-07-27 18:01:07 +02006440 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6441 // could falsely detect that the frame position has stalled due to underrun because we haven't
6442 // given the Audio HAL enough time to update.
6443 const nsecs_t nowNs = systemTime();
6444 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6445 return mLatchedValue;
6446 }
6447 mPreviousNs = nowNs;
6448 mLatchedValue = false;
6449 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006450 uint64_t position = 0;
6451 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006452 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006453 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006454 if (position != mPreviousPosition) {
6455 mPreviousPosition = position;
6456 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006457 }
6458 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006459 return mLatchedValue;
6460}
6461
Andy Hungee58e4a2023-07-07 13:47:37 -07006462void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006463{
6464 mLatchedValue = true;
6465 mPreviousPosition = 0;
6466 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006467}
6468
Andy Hungc5007f82023-08-29 14:26:09 -07006469// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006470bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006471 audio_channel_mask_t channelMask, audio_format_t format,
6472 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006473{
Andy Hung1bc088a2018-02-09 15:57:31 -08006474 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6475 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006476 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006477 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006478 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006479 ALOGW("%s: invalid format: %#x", __func__, format);
6480 return false;
6481 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006482 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006483 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6484 return false;
6485 }
6486 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006487}
6488
Andy Hungc5007f82023-08-29 14:26:09 -07006489// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006490bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006491 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006492{
Eric Laurent81784c32012-11-19 14:55:58 -08006493 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006494 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006495
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006496 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006497
Eric Laurent10351942014-05-08 18:49:52 -07006498 AudioParameter param = AudioParameter(keyValuePair);
6499 int value;
6500 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6501 reconfig = true;
6502 }
6503 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006504 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006505 status = BAD_VALUE;
6506 } else {
6507 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006508 reconfig = true;
6509 }
Eric Laurent10351942014-05-08 18:49:52 -07006510 }
6511 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006512 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006513 status = BAD_VALUE;
6514 } else {
6515 // no need to save value, since it's constant
6516 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006517 }
Eric Laurent10351942014-05-08 18:49:52 -07006518 }
6519 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6520 // do not accept frame count changes if tracks are open as the track buffer
6521 // size depends on frame count and correct behavior would not be guaranteed
6522 // if frame count is changed after track creation
6523 if (!mTracks.isEmpty()) {
6524 status = INVALID_OPERATION;
6525 } else {
6526 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006527 }
Eric Laurent10351942014-05-08 18:49:52 -07006528 }
6529 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006530 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006531 }
Eric Laurent81784c32012-11-19 14:55:58 -08006532
Eric Laurent10351942014-05-08 18:49:52 -07006533 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006534 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006535 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006536 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6537 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006538 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006539 mThreadMetrics.logEndInterval();
6540 mThreadSnapshot.onEnd();
6541 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006542 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006543 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006544 }
Eric Laurent10351942014-05-08 18:49:52 -07006545 if (status == NO_ERROR && reconfig) {
6546 readOutputParameters_l();
6547 delete mAudioMixer;
6548 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006549 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006550 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006551 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006552 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006553 track->channelMask(),
6554 track->format(),
6555 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006556 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006557 "%s(): AudioMixer cannot create track(%d)"
6558 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006559 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006560 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006561 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006562 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006563 }
Eric Laurent81784c32012-11-19 14:55:58 -08006564 }
6565
Dean Wheatley68918102021-03-19 22:09:19 +11006566 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006567}
6568
6569
Andy Hungee58e4a2023-07-07 13:47:37 -07006570void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006571{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006572 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006573 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006574 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006575 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006576 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6577 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6578 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006579 if (hasFastMixer()) {
6580 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6581
6582 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6583 // while we are dumping it. It may be inconsistent, but it won't mutate!
6584 // This is a large object so we place it on the heap.
6585 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006586 const std::unique_ptr<FastMixerDumpState> copy =
6587 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006588 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006589
6590#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006591 // Similar for state queue
6592 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6593 observerCopy.dump(fd);
6594 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6595 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006596#endif
6597
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006598#ifdef AUDIO_WATCHDOG
6599 if (mAudioWatchdog != 0) {
6600 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6601 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6602 wdCopy.dump(fd);
6603 }
6604#endif
6605
6606 } else {
6607 dprintf(fd, " No FastMixer\n");
6608 }
Eric Laurent90cea102023-05-15 15:08:27 +02006609
6610 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6611 mBluetoothLatencyModesEnabled ? "" : "not ");
6612 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6613 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6614 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006615}
6616
Andy Hungee58e4a2023-07-07 13:47:37 -07006617uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006618{
6619 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6620}
6621
Andy Hungee58e4a2023-07-07 13:47:37 -07006622uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006623{
6624 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6625}
6626
Andy Hungee58e4a2023-07-07 13:47:37 -07006627void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006628{
6629 PlaybackThread::cacheParameters_l();
6630
6631 // FIXME: Relaxed timing because of a certain device that can't meet latency
6632 // Should be reduced to 2x after the vendor fixes the driver issue
6633 // increase threshold again due to low power audio mode. The way this warning
6634 // threshold is calculated and its usefulness should be reconsidered anyway.
6635 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6636}
6637
Andy Hungee58e4a2023-07-07 13:47:37 -07006638void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006639 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006640}
6641
Andy Hungee58e4a2023-07-07 13:47:37 -07006642void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006643 // Only handle latency mode if:
6644 // - mBluetoothLatencyModesEnabled is true
6645 // - the HAL supports latency modes
6646 // - the selected device is Bluetooth LE or A2DP
6647 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6648 return;
6649 }
6650 if (mOutDeviceTypeAddrs.size() != 1
6651 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6652 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6653 return;
6654 }
6655
6656 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6657 if (mSupportedLatencyModes.size() == 1) {
6658 // If the HAL only support one latency mode currently, confirm the choice
6659 latencyMode = mSupportedLatencyModes[0];
6660 } else if (mSupportedLatencyModes.size() > 1) {
6661 // Request low latency if:
6662 // - At least one active track is either:
6663 // - a fast track with gaming usage or
6664 // - a track with acessibility usage
6665 for (const auto& track : mActiveTracks) {
6666 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6667 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6668 latencyMode = AUDIO_LATENCY_MODE_LOW;
6669 break;
6670 }
6671 }
6672 }
6673
6674 if (latencyMode != mSetLatencyMode) {
6675 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6676 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6677 __func__, mId, toString(latencyMode).c_str(), status);
6678 if (status == NO_ERROR) {
6679 mSetLatencyMode = latencyMode;
6680 }
6681 }
6682}
6683
Andy Hungee58e4a2023-07-07 13:47:37 -07006684void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006685
6686 if (mOutput == nullptr || mOutput->stream == nullptr) {
6687 return;
6688 }
6689 std::vector<audio_latency_mode_t> latencyModes;
6690 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6691 if (status != NO_ERROR) {
6692 latencyModes.clear();
6693 }
6694 if (latencyModes != mSupportedLatencyModes) {
6695 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6696 __func__, mId, status, toString(latencyModes).c_str());
6697 mSupportedLatencyModes.swap(latencyModes);
6698 sendHalLatencyModesChangedEvent_l();
6699 }
6700}
6701
Andy Hungee58e4a2023-07-07 13:47:37 -07006702status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006703 std::vector<audio_latency_mode_t>* modes) {
6704 if (modes == nullptr) {
6705 return BAD_VALUE;
6706 }
Andy Hung972bec12023-08-31 16:13:39 -07006707 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006708 *modes = mSupportedLatencyModes;
6709 return NO_ERROR;
6710}
6711
Andy Hungee58e4a2023-07-07 13:47:37 -07006712void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006713 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006714 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006715 if (modes != mSupportedLatencyModes) {
6716 ALOGD("%s: thread(%d) supported latency modes: %s",
6717 __func__, mId, toString(modes).c_str());
6718 mSupportedLatencyModes.swap(modes);
6719 sendHalLatencyModesChangedEvent_l();
6720 }
6721}
6722
Andy Hungee58e4a2023-07-07 13:47:37 -07006723status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006724 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6725 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6726 return INVALID_OPERATION;
6727 }
6728 mBluetoothLatencyModesEnabled.store(enabled);
6729 return NO_ERROR;
6730}
6731
Eric Laurent81784c32012-11-19 14:55:58 -08006732// ----------------------------------------------------------------------------
6733
Andy Hungee58e4a2023-07-07 13:47:37 -07006734/* static */
6735sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006736 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006737 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6738 const audio_offload_info_t& offloadInfo) {
6739 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006740 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006741}
6742
Andy Hung583043b2023-07-17 17:05:00 -07006743DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006744 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6745 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006746 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006747 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006748{
Andy Hung583043b2023-07-17 17:05:00 -07006749 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006750}
6751
Andy Hungee58e4a2023-07-07 13:47:37 -07006752DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006753{
6754}
6755
Andy Hungee58e4a2023-07-07 13:47:37 -07006756void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006757{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006758 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006759 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6760 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6761}
6762
Andy Hungee58e4a2023-07-07 13:47:37 -07006763void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006764{
Andy Hung972bec12023-08-31 16:13:39 -07006765 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006766 if (mMasterBalance != balance) {
6767 mMasterBalance.store(balance);
6768 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6769 broadcast_l();
6770 }
6771}
6772
Andy Hungee58e4a2023-07-07 13:47:37 -07006773void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006774{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006775 float left, right;
6776
Andy Hung333ab962019-05-28 20:23:35 -07006777 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006778 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006779
Andy Hung398ffa22022-12-13 19:19:53 -08006780 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6781 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6782
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006783 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6784 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006785
6786 const int64_t volumeShaperFrames =
6787 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6788 const auto [shaperVolume, shaperActive] =
6789 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006790 mVolumeShaperActive = shaperActive;
6791
Vlad Popae2f5aef2022-07-25 16:00:20 +02006792 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6793 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6794 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6795
6796 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6797
Andy Hung6b137d12024-08-27 22:35:17 +00006798 if (!audioserver_flags::portid_volume_management()) {
6799 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6800 track->isPlaybackRestricted()) {
6801 left = right = 0;
6802 } else {
6803 float typeVolume = mStreamTypes[track->streamType()].volume;
6804 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurent277a37e2024-07-29 18:37:52 +00006805
Andy Hung6b137d12024-08-27 22:35:17 +00006806 if (left > GAIN_FLOAT_UNITY) {
6807 left = GAIN_FLOAT_UNITY;
6808 }
6809 if (right > GAIN_FLOAT_UNITY) {
6810 right = GAIN_FLOAT_UNITY;
6811 }
6812 left *= v;
6813 right *= v;
6814 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006815 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Andy Hung6b137d12024-08-27 22:35:17 +00006816 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6817 right *= mMasterBalanceRight;
6818 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006819 }
Andy Hung6b137d12024-08-27 22:35:17 +00006820 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6821 /*muteState=*/{mMasterMute,
6822 mStreamTypes[track->streamType()].volume == 0.f,
6823 mStreamTypes[track->streamType()].mute,
6824 track->isPlaybackRestricted(),
6825 clientVolumeMute,
6826 shaperVolume == 0.f});
6827 } else {
6828 if (mMasterMute || track->isPlaybackRestricted()) {
6829 left = right = 0;
6830 } else {
6831 float typeVolume = track->getPortVolume();
6832 const float v = mMasterVolume * typeVolume * shaperVolume;
Liana Kazanova (xWF)d3e99d22024-08-23 22:15:51 +00006833
Andy Hung6b137d12024-08-27 22:35:17 +00006834 if (left > GAIN_FLOAT_UNITY) {
6835 left = GAIN_FLOAT_UNITY;
6836 }
6837 if (right > GAIN_FLOAT_UNITY) {
6838 right = GAIN_FLOAT_UNITY;
6839 }
6840 left *= v;
6841 right *= v;
6842 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6843 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6844 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6845 right *= mMasterBalanceRight;
6846 }
6847 }
6848 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6849 /*muteState=*/{mMasterMute,
6850 track->getPortVolume() == 0.f,
6851 /* muteFromStreamMuted= */ false,
6852 track->isPlaybackRestricted(),
6853 clientVolumeMute,
6854 shaperVolume == 0.f});
6855 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006856
Eric Laurentbfb1b832013-01-07 09:53:42 -08006857 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006858 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006859 if (left != mLeftVolFloat || right != mRightVolFloat) {
6860 mLeftVolFloat = left;
6861 mRightVolFloat = right;
6862
Eric Laurentbfb1b832013-01-07 09:53:42 -08006863 // Delegate volume control to effect in track effect chain if needed
6864 // only one effect chain can be present on DirectOutputThread, so if
6865 // there is one, the track is connected to it
6866 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006867 // if effect chain exists, volume is handled by it.
6868 // Convert volumes from float to 8.24
6869 uint32_t vl = (uint32_t)(left * (1 << 24));
6870 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006871 // Direct/Offload effect chains set output volume in setVolume().
6872 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006873 } else {
6874 // otherwise we directly set the volume.
6875 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006876 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006877 }
6878 }
6879}
6880
Andy Hungee58e4a2023-07-07 13:47:37 -07006881void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006882{
Andy Hung8d31fd22023-06-26 19:20:57 -07006883 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6884 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006885
Eric Laurent0f0631e2015-07-06 18:01:25 -07006886 if (previousTrack != 0 && latestTrack != 0) {
6887 if (mType == DIRECT) {
6888 if (previousTrack.get() != latestTrack.get()) {
6889 mFlushPending = true;
6890 }
6891 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006892 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6893 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006894 mFlushPending = true;
6895 }
6896 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006897 } else if (previousTrack == 0) {
6898 // there could be an old track added back during track transition for direct
6899 // output, so always issues flush to flush data of the previous track if it
6900 // was already destroyed with HAL paused, then flush can resume the playback
6901 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006902 }
6903 PlaybackThread::onAddNewTrack_l();
6904}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006905
Andy Hungee58e4a2023-07-07 13:47:37 -07006906PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006907 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006908)
6909{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006910 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006911 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006912 bool doHwPause = false;
6913 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006914
6915 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006916 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006917 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006918 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006919 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006920 continue;
6921 }
6922
Andy Hung8d31fd22023-06-26 19:20:57 -07006923 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006924#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006925 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006926#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006927 // Only consider last track started for volume and mixer state control.
6928 // In theory an older track could underrun and restart after the new one starts
6929 // but as we only care about the transition phase between two tracks on a
6930 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006931 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006932 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006933
Kuowei Li23666472021-01-20 10:23:25 +08006934 if (track->isPausePending()) {
6935 track->pauseAck();
6936 // It is possible a track might have been flushed or stopped.
6937 // Other operations such as flush pending might occur on the next prepare.
6938 if (track->isPausing()) {
6939 track->setPaused();
6940 }
6941 // Always perform pause, as an immediate flush will change
6942 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006943 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006944 doHwPause = true;
6945 mHwPaused = true;
6946 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006947 } else if (track->isFlushPending()) {
6948 track->flushAck();
6949 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006950 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006951 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006952 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006953 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006954 if (last) {
6955 mLeftVolFloat = mRightVolFloat = -1.0;
6956 if (mHwPaused) {
6957 doHwResume = true;
6958 mHwPaused = false;
6959 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006960 }
6961 }
6962
Eric Laurent81784c32012-11-19 14:55:58 -08006963 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006964 // for all its buffers to be filled before processing it.
6965 // Allow draining the buffer in case the client
6966 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006967 // hence the test on (track->retryCount() > 1).
6968 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006969 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6970 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006971 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006972
6973 // target retry count that we will use is based on the time we wait for retries.
6974 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6975 // the retry threshold is when we accept any size for PCM data. This is slightly
6976 // smaller than the retry count so we can push small bits of data without a glitch.
6977 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006978 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006979 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006980 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006981 minFrames = mNormalFrameCount;
6982 } else {
6983 minFrames = 1;
6984 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006985
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006986 const size_t framesReady = track->framesReady();
6987 const int trackId = track->id();
6988 if (ATRACE_ENABLED()) {
6989 std::string traceName("nRdy");
6990 traceName += std::to_string(trackId);
6991 ATRACE_INT(traceName.c_str(), framesReady);
6992 }
6993 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006994 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006995 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006996 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006997
Andy Hung8d31fd22023-06-26 19:20:57 -07006998 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6999 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007000 if (last) {
7001 // make sure processVolume_l() will apply new volume even if 0
7002 mLeftVolFloat = mRightVolFloat = -1.0;
7003 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08007004 if (!mHwSupportsPause) {
7005 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08007006 }
7007 }
7008
7009 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08007010 processVolume_l(track, last);
7011 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007012 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007013 if (previousTrack != 0) {
7014 if (track != previousTrack.get()) {
7015 // Flush any data still being written from last track
7016 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07007017 // Invalidate previous track to force a seek when resuming.
7018 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007019 }
7020 }
7021 mPreviousTrack = track;
7022
Eric Laurentd595b7c2013-04-03 17:27:56 -07007023 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07007024 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08007025 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07007026 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07007027 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007028 doHwResume = true;
7029 mHwPaused = false;
7030 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007031 }
Eric Laurent81784c32012-11-19 14:55:58 -08007032 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007033 // clear effect chain input buffer if the last active track started underruns
7034 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007035 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007036 mEffectChains[0]->clearInputBuffer();
7037 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007038 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007039 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007040 if (last && mHwPaused) {
7041 doHwResume = true;
7042 mHwPaused = false;
7043 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007044 }
7045 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7046 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007047 // We have consumed all the buffers of this track.
7048 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007049 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007050 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007051 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007052 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007053 if (presComplete) {
7054 mOutput->presentationComplete();
7055 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007056 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007057 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007058 }
Eric Laurent81784c32012-11-19 14:55:58 -08007059 if (track->isStopped()) {
7060 track->reset();
7061 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007062 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007063 }
7064 } else {
7065 // No buffers for this track. Give it a few chances to
7066 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007067 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007068 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007069 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007070 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007071 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007072 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007073 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007074 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7075 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007076 tracksToRemove->add(track);
7077 // indicate to client process that the track was disabled because of
7078 // underrun; it will then automatically call start() when data is available
7079 track->disable();
7080 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7081 // unlike mixerthread, HAL can be paused for direct output
7082 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7083 "minFrames = %u, mFormat = %#x",
7084 framesReady, minFrames, mFormat);
7085 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7086 doHwPause = true;
7087 mHwPaused = true;
7088 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007089 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007090 } else if (last) {
7091 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007092 }
7093 }
7094 }
7095 }
7096
Eric Laurentd1f69b02014-12-15 14:33:13 -08007097 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007098 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007099 for (size_t i = 0; i < mTracks.size(); i++) {
7100 if (mTracks[i]->isFlushPending()) {
7101 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007102 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007103 }
7104 }
7105 }
7106
7107 // make sure the pause/flush/resume sequence is executed in the right order.
7108 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7109 // before flush and then resume HW. This can happen in case of pause/flush/resume
7110 // if resume is received before pause is executed.
7111 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007112 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007113 status_t result = mOutput->stream->pause();
7114 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007115 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007116 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007117 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007118 flushHw_l();
7119 }
7120 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007121 status_t result = mOutput->stream->resume();
7122 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007123 }
Eric Laurent81784c32012-11-19 14:55:58 -08007124 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007125 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007126
7127 return mixerStatus;
7128}
7129
Andy Hungee58e4a2023-07-07 13:47:37 -07007130void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007131{
Eric Laurent81784c32012-11-19 14:55:58 -08007132 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007133 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007134 // output audio to hardware
7135 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007136 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007137 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007138 status_t status = mActiveTrack->getNextBuffer(&buffer);
7139 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007140 // no need to pad with 0 for compressed audio
7141 if (audio_has_proportional_frames(mFormat)) {
7142 memset(curBuf, 0, frameCount * mFrameSize);
7143 }
Eric Laurent81784c32012-11-19 14:55:58 -08007144 break;
7145 }
7146 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7147 frameCount -= buffer.frameCount;
7148 curBuf += buffer.frameCount * mFrameSize;
7149 mActiveTrack->releaseBuffer(&buffer);
7150 }
Andy Hung2098f272014-02-27 14:00:06 -08007151 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007152 mSleepTimeUs = 0;
7153 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007154 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007155}
7156
Andy Hungee58e4a2023-07-07 13:47:37 -07007157void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007158{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007159 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007160 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007161 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007162 return;
7163 }
Andy Hung85ba3332021-04-27 17:40:26 -07007164 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7165 mSleepTimeUs = mActiveSleepTimeUs;
7166 } else {
7167 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007168 }
Andy Hung85ba3332021-04-27 17:40:26 -07007169 // Note: In S or later, we do not write zeroes for
7170 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007171}
7172
Andy Hungee58e4a2023-07-07 13:47:37 -07007173void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007174{
7175 {
Andy Hung972bec12023-08-31 16:13:39 -07007176 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007177 for (size_t i = 0; i < mTracks.size(); i++) {
7178 if (mTracks[i]->isFlushPending()) {
7179 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007180 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007181 }
7182 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007183 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007184 flushHw_l();
7185 }
7186 }
7187 PlaybackThread::threadLoop_exit();
7188}
7189
7190// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007191bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007192{
7193 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007194 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007195 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007196
Eric Laurent022a5132024-04-12 17:02:51 +00007197 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007198 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007199 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007200 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007201 const auto& mainTrack = mTracks[mTracks.size() - 1];
7202
7203 trackPaused = mainTrack->isPaused();
7204 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7205 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007206 }
7207
Eric Laurent022a5132024-04-12 17:02:51 +00007208 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007209}
7210
Andy Hungc5007f82023-08-29 14:26:09 -07007211// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007212bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007213 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007214{
7215 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007216 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007217
Eric Laurent10351942014-05-08 18:49:52 -07007218 AudioParameter param = AudioParameter(keyValuePair);
7219 int value;
7220 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007221 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007222 }
Eric Laurent10351942014-05-08 18:49:52 -07007223 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7224 // do not accept frame count changes if tracks are open as the track buffer
7225 // size depends on frame count and correct behavior would not be garantied
7226 // if frame count is changed after track creation
7227 if (!mTracks.isEmpty()) {
7228 status = INVALID_OPERATION;
7229 } else {
7230 reconfig = true;
7231 }
7232 }
7233 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007234 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007235 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007236 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007237 if (!mStandby) {
7238 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007239 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007240 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007241 }
Eric Laurent10351942014-05-08 18:49:52 -07007242 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007243 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007244 }
7245 if (status == NO_ERROR && reconfig) {
7246 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007247 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007248 }
7249 }
7250
Dean Wheatley68918102021-03-19 22:09:19 +11007251 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007252}
7253
Andy Hungee58e4a2023-07-07 13:47:37 -07007254uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007255{
7256 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007257 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007258 time = PlaybackThread::activeSleepTimeUs();
7259 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007260 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007261 }
7262 return time;
7263}
7264
Andy Hungee58e4a2023-07-07 13:47:37 -07007265uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007266{
7267 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007268 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007269 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7270 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007271 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007272 }
7273 return time;
7274}
7275
Andy Hungee58e4a2023-07-07 13:47:37 -07007276uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007277{
7278 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007279 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007280 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7281 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007282 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007283 }
7284 return time;
7285}
7286
Andy Hungee58e4a2023-07-07 13:47:37 -07007287void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007288{
7289 PlaybackThread::cacheParameters_l();
7290
7291 // use shorter standby delay as on normal output to release
7292 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007293 // no delay on outputs with HW A/V sync
7294 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007295 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007296 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007297 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007298 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007299 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007300 }
Eric Laurent81784c32012-11-19 14:55:58 -08007301}
7302
Andy Hungee58e4a2023-07-07 13:47:37 -07007303void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007304{
ziyangch8f194f12021-12-01 13:48:04 -08007305 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007306 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007307 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007308 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007309 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007310 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007311 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007312}
7313
Andy Hungee58e4a2023-07-07 13:47:37 -07007314int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007315 // If a VolumeShaper is active, we must wake up periodically to update volume.
7316 const int64_t NS_PER_MS = 1000000;
7317 return mVolumeShaperActive ?
7318 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7319}
7320
Eric Laurent81784c32012-11-19 14:55:58 -08007321// ----------------------------------------------------------------------------
7322
Andy Hungee58e4a2023-07-07 13:47:37 -07007323AsyncCallbackThread::AsyncCallbackThread(
7324 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007325 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007326 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007327 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007328 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007329 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007330{
7331}
7332
Andy Hungee58e4a2023-07-07 13:47:37 -07007333void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007334{
7335 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7336}
7337
Andy Hungee58e4a2023-07-07 13:47:37 -07007338bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007339{
7340 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007341 uint32_t writeAckSequence;
7342 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007343 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007344
7345 {
Andy Hungc5007f82023-08-29 14:26:09 -07007346 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007347 while (!((mWriteAckSequence & 1) ||
7348 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007349 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007350 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007351 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007352 }
7353
Eric Laurentbfb1b832013-01-07 09:53:42 -08007354 if (exitPending()) {
7355 break;
7356 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007357 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7358 mWriteAckSequence, mDrainSequence);
7359 writeAckSequence = mWriteAckSequence;
7360 mWriteAckSequence &= ~1;
7361 drainSequence = mDrainSequence;
7362 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007363 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007364 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007365 }
7366 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007367 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007368 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007369 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007370 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007371 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007372 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007373 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007374 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007375 if (asyncError != ASYNC_ERROR_NONE) {
7376 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007377 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007378 }
7379 }
7380 }
7381 return false;
7382}
7383
Andy Hungee58e4a2023-07-07 13:47:37 -07007384void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385{
7386 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007387 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007388 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007389 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007390}
7391
Andy Hungee58e4a2023-07-07 13:47:37 -07007392void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007393{
Andy Hung972bec12023-08-31 16:13:39 -07007394 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007395 // bit 0 is cleared
7396 mWriteAckSequence = sequence << 1;
7397}
7398
Andy Hungee58e4a2023-07-07 13:47:37 -07007399void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007400{
Andy Hung972bec12023-08-31 16:13:39 -07007401 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007402 // ignore unexpected callbacks
7403 if (mWriteAckSequence & 2) {
7404 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007405 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007406 }
7407}
7408
Andy Hungee58e4a2023-07-07 13:47:37 -07007409void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007410{
Andy Hung972bec12023-08-31 16:13:39 -07007411 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007412 // bit 0 is cleared
7413 mDrainSequence = sequence << 1;
7414}
7415
Andy Hungee58e4a2023-07-07 13:47:37 -07007416void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007417{
Andy Hung972bec12023-08-31 16:13:39 -07007418 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007419 // ignore unexpected callbacks
7420 if (mDrainSequence & 2) {
7421 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007422 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007423 }
7424}
7425
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007426void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007427{
Andy Hung972bec12023-08-31 16:13:39 -07007428 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007429 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007430 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007431}
7432
Eric Laurentbfb1b832013-01-07 09:53:42 -08007433
7434// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007435
7436/* static */
7437sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007438 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007439 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7440 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007441 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007442}
7443
Andy Hung583043b2023-07-17 17:05:00 -07007444OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007445 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7446 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007447 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007448 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007449{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007450 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007451 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007452 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007453}
7454
Andy Hungee58e4a2023-07-07 13:47:37 -07007455void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007456{
7457 if (mFlushPending || mHwPaused) {
7458 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007459 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007460 flushHw_l();
7461 } else {
7462 mMixerStatus = MIXER_DRAIN_ALL;
7463 threadLoop_drain();
7464 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007465 if (mUseAsyncWrite) {
7466 ALOG_ASSERT(mCallbackThread != 0);
7467 mCallbackThread->exit();
7468 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007469 PlaybackThread::threadLoop_exit();
7470}
7471
Andy Hungee58e4a2023-07-07 13:47:37 -07007472PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007473 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007474)
7475{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007476 size_t count = mActiveTracks.size();
7477
7478 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007479 bool doHwPause = false;
7480 bool doHwResume = false;
7481
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007482 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007483
Eric Laurentbfb1b832013-01-07 09:53:42 -08007484 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007485 for (const sp<IAfTrack>& t : mActiveTracks) {
7486 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007487#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007488 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007489#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007490 // Only consider last track started for volume and mixer state control.
7491 // In theory an older track could underrun and restart after the new one starts
7492 // but as we only care about the transition phase between two tracks on a
7493 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007494 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007495 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007496
Haynes Mathew George7844f672014-01-15 12:32:55 -08007497 if (track->isInvalid()) {
7498 ALOGW("An invalidated track shouldn't be in active list");
7499 tracksToRemove->add(track);
7500 continue;
7501 }
7502
Andy Hung8d31fd22023-06-26 19:20:57 -07007503 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007504 ALOGW("An idle track shouldn't be in active list");
7505 continue;
7506 }
7507
Kuowei Li23666472021-01-20 10:23:25 +08007508 if (track->isPausePending()) {
7509 track->pauseAck();
7510 // It is possible a track might have been flushed or stopped.
7511 // Other operations such as flush pending might occur on the next prepare.
7512 if (track->isPausing()) {
7513 track->setPaused();
7514 }
7515 // Always perform pause if last, as an immediate flush will change
7516 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007517 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007518 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007519 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007520 mHwPaused = true;
7521 }
7522 // If we were part way through writing the mixbuffer to
7523 // the HAL we must save this until we resume
7524 // BUG - this will be wrong if a different track is made active,
7525 // in that case we want to discard the pending data in the
7526 // mixbuffer and tell the client to present it again when the
7527 // track is resumed
7528 mPausedWriteLength = mCurrentWriteLength;
7529 mPausedBytesRemaining = mBytesRemaining;
7530 mBytesRemaining = 0; // stop writing
7531 }
7532 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007533 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007534 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007535 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007536 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007537 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007538 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007539 track->flushAck();
7540 if (last) {
7541 mFlushPending = true;
7542 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007543 } else if (track->isResumePending()){
7544 track->resumeAck();
7545 if (last) {
7546 if (mPausedBytesRemaining) {
7547 // Need to continue write that was interrupted
7548 mCurrentWriteLength = mPausedWriteLength;
7549 mBytesRemaining = mPausedBytesRemaining;
7550 mPausedBytesRemaining = 0;
7551 }
7552 if (mHwPaused) {
7553 doHwResume = true;
7554 mHwPaused = false;
7555 // threadLoop_mix() will handle the case that we need to
7556 // resume an interrupted write
7557 }
7558 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007559 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007560
Eric Laurent3df841a2016-07-15 15:15:40 -07007561 mLeftVolFloat = mRightVolFloat = -1.0;
7562
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007563 // Do not handle new data in this iteration even if track->framesReady()
7564 mixerStatus = MIXER_TRACKS_ENABLED;
7565 }
7566 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007567 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007568 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007569 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7570 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007571 if (last) {
7572 // make sure processVolume_l() will apply new volume even if 0
7573 mLeftVolFloat = mRightVolFloat = -1.0;
7574 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007575 }
7576
7577 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007578 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007579 if (previousTrack != 0) {
7580 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007581 // Flush any data still being written from last track
7582 mBytesRemaining = 0;
7583 if (mPausedBytesRemaining) {
7584 // Last track was paused so we also need to flush saved
7585 // mixbuffer state and invalidate track so that it will
7586 // re-submit that unwritten data when it is next resumed
7587 mPausedBytesRemaining = 0;
7588 // Invalidate is a bit drastic - would be more efficient
7589 // to have a flag to tell client that some of the
7590 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007591 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007592 }
7593 // flush data already sent to the DSP if changing audio session as audio
7594 // comes from a different source. Also invalidate previous track to force a
7595 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007596 if (previousTrack->sessionId() != track->sessionId()) {
7597 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007598 }
7599 }
7600 }
7601 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007602 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007603 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007604 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007605 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007606 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007607 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007608 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007609 mixerStatus = MIXER_TRACKS_READY;
7610 }
7611 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007612 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007613 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007614 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007615 // Hardware buffer can hold a large amount of audio so we must
7616 // wait for all current track's data to drain before we say
7617 // that the track is stopped.
7618 if (mBytesRemaining == 0) {
7619 // Only start draining when all data in mixbuffer
7620 // has been written
7621 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007622 track->setState(IAfTrackBase::STOPPING_2);
7623 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007624 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7625 if (last && !mStandby) {
7626 // do not modify drain sequence if we are already draining. This happens
7627 // when resuming from pause after drain.
7628 if ((mDrainSequence & 1) == 0) {
7629 mSleepTimeUs = 0;
7630 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7631 mixerStatus = MIXER_DRAIN_TRACK;
7632 mDrainSequence += 2;
7633 }
7634 if (mHwPaused) {
7635 // It is possible to move from PAUSED to STOPPING_1 without
7636 // a resume so we must ensure hardware is running
7637 doHwResume = true;
7638 mHwPaused = false;
7639 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007640 }
7641 }
Eric Laurente93cc032016-05-05 10:15:10 -07007642 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007643 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007644 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007645 }
7646 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007647 // Drain has completed or we are in standby, signal presentation complete
7648 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007649 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007650 mOutput->presentationComplete();
7651 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007652 track->reset();
7653 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007654 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007655 if (!mUseAsyncWrite) {
7656 // If we don't get explicit drain notification we must
7657 // register discontinuity regardless of whether this is
7658 // the previous (!last) or the upcoming (last) track
7659 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007660 mTimestampVerifier.discontinuity(
7661 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007662 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007663 }
7664 } else {
7665 // No buffers for this track. Give it a few chances to
7666 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007667 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007668 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007669 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007670 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007671 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007672 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007673 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7674 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007675 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007676 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007677 // it will then automatically call start() when data is available
7678 track->disable();
7679 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007680 } else if (last){
7681 mixerStatus = MIXER_TRACKS_ENABLED;
7682 }
7683 }
7684 }
7685 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007686 if (track->isReady()) { // check ready to prevent premature start.
7687 processVolume_l(track, last);
7688 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007689 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007690
Eric Laurentea0fade2013-10-04 16:23:48 -07007691 // make sure the pause/flush/resume sequence is executed in the right order.
7692 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7693 // before flush and then resume HW. This can happen in case of pause/flush/resume
7694 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007695 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007696 status_t result = mOutput->stream->pause();
7697 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007698 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007699 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007700 if (mFlushPending) {
7701 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007702 }
Eric Laurentfd477972013-10-25 18:10:40 -07007703 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007704 status_t result = mOutput->stream->resume();
7705 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007706 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007707
Eric Laurentbfb1b832013-01-07 09:53:42 -08007708 // remove all the tracks that need to be...
7709 removeTracks_l(*tracksToRemove);
7710
7711 return mixerStatus;
7712}
7713
Eric Laurentbfb1b832013-01-07 09:53:42 -08007714// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007715bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007716{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007717 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7718 mWriteAckSequence, mDrainSequence);
7719 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007720 return true;
7721 }
7722 return false;
7723}
7724
Andy Hungee58e4a2023-07-07 13:47:37 -07007725bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007726{
Andy Hung972bec12023-08-31 16:13:39 -07007727 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007728 return waitingAsyncCallback_l();
7729}
7730
Andy Hungee58e4a2023-07-07 13:47:37 -07007731void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007732{
Eric Laurente659ef42014-09-29 13:06:46 -07007733 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007734 // Flush anything still waiting in the mixbuffer
7735 mCurrentWriteLength = 0;
7736 mBytesRemaining = 0;
7737 mPausedWriteLength = 0;
7738 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007739 // reset bytes written count to reflect that DSP buffers are empty after flush.
7740 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007741
Eric Laurentbfb1b832013-01-07 09:53:42 -08007742 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007743 // discard any pending drain or write ack by incrementing sequence
7744 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7745 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007746 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007747 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7748 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007749 }
7750}
7751
Andy Hungee58e4a2023-07-07 13:47:37 -07007752void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007753{
Andy Hung972bec12023-08-31 16:13:39 -07007754 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007755 if (PlaybackThread::invalidateTracks_l(streamType)) {
7756 mFlushPending = true;
7757 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007758}
7759
Andy Hungee58e4a2023-07-07 13:47:37 -07007760void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007761 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007762 if (PlaybackThread::invalidateTracks_l(portIds)) {
7763 mFlushPending = true;
7764 }
7765}
7766
Eric Laurentbfb1b832013-01-07 09:53:42 -08007767// ----------------------------------------------------------------------------
7768
Andy Hungee58e4a2023-07-07 13:47:37 -07007769/* static */
7770sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007771 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007772 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007773 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007774}
7775
Andy Hung583043b2023-07-17 17:05:00 -07007776DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007777 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007778 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007779 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007780 mWaitTimeMs(UINT_MAX)
7781{
7782 addOutputTrack(mainThread);
7783}
7784
Andy Hungee58e4a2023-07-07 13:47:37 -07007785DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007786{
7787 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7788 mOutputTracks[i]->destroy();
7789 }
7790}
7791
Andy Hungee58e4a2023-07-07 13:47:37 -07007792void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007793{
7794 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007795 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007796 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007797 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007798 if (mMixerBufferValid) {
7799 memset(mMixerBuffer, 0, mMixerBufferSize);
7800 } else {
7801 memset(mSinkBuffer, 0, mSinkBufferSize);
7802 }
Eric Laurent81784c32012-11-19 14:55:58 -08007803 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007804 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007805 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007806 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007807 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007808}
7809
Andy Hungee58e4a2023-07-07 13:47:37 -07007810void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007811{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007812 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007813 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007814 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007815 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007816 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007817 }
7818 } else if (mBytesWritten != 0) {
7819 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7820 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007821 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007822 } else {
7823 // flush remaining overflow buffers in output tracks
7824 writeFrames = 0;
7825 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007826 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007827 }
7828}
7829
Andy Hungee58e4a2023-07-07 13:47:37 -07007830ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007831{
7832 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007833 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7834
7835 // Consider the first OutputTrack for timestamp and frame counting.
7836
7837 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7838 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7839 // we always claim success.
7840 if (i == 0) {
7841 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7842 ALOGD_IF(correction != 0 && writeFrames != 0,
7843 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7844 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7845 mFramesWritten -= correction;
7846 }
7847
7848 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007849 }
Andy Hungcf10d742020-04-28 15:38:24 -07007850 if (mStandby) {
7851 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007852 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007853 mStandby = false;
7854 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007855 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007856}
7857
Andy Hungee58e4a2023-07-07 13:47:37 -07007858void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007859{
7860 // DuplicatingThread implements standby by stopping all tracks
7861 for (size_t i = 0; i < outputTracks.size(); i++) {
7862 outputTracks[i]->stop();
7863 }
7864}
7865
Andy Hung8a5abfd2023-12-07 19:35:12 -08007866void DuplicatingThread::threadLoop_exit()
7867{
7868 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7869 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7870 // Do so here in the threadLoop_exit().
7871
7872 SortedVector <sp<IAfOutputTrack>> localTracks;
7873 {
7874 audio_utils::lock_guard l(mutex());
7875 localTracks = std::move(mOutputTracks);
7876 mOutputTracks.clear();
jiabinc62d6032024-09-03 23:39:57 +00007877 for (size_t i = 0; i < localTracks.size(); ++i) {
7878 localTracks[i]->destroy();
7879 }
Andy Hung8a5abfd2023-12-07 19:35:12 -08007880 }
7881 localTracks.clear();
7882 outputTracks.clear();
7883 PlaybackThread::threadLoop_exit();
7884}
7885
Andy Hungee58e4a2023-07-07 13:47:37 -07007886void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007887{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007888 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007889
7890 std::stringstream ss;
7891 const size_t numTracks = mOutputTracks.size();
7892 ss << " " << numTracks << " OutputTracks";
7893 if (numTracks > 0) {
7894 ss << ":";
7895 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007896 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007897 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007898 if (thread.get() != nullptr) {
7899 ss << thread.get() << ", " << thread->id();
7900 } else {
7901 ss << "null";
7902 }
7903 ss << ")";
7904 }
7905 }
7906 ss << "\n";
7907 std::string result = ss.str();
7908 write(fd, result.c_str(), result.size());
7909}
7910
Andy Hungee58e4a2023-07-07 13:47:37 -07007911void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007912{
7913 outputTracks = mOutputTracks;
7914}
7915
Andy Hungee58e4a2023-07-07 13:47:37 -07007916void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007917{
7918 outputTracks.clear();
7919}
7920
Andy Hungee58e4a2023-07-07 13:47:37 -07007921void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007922{
Andy Hung972bec12023-08-31 16:13:39 -07007923 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007924 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7925 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7926 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7927 const size_t frameCount =
7928 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7929 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7930 // from different OutputTracks and their associated MixerThreads (e.g. one may
7931 // nearly empty and the other may be dropping data).
7932
Svet Ganov33761132021-05-13 22:51:08 +00007933 // TODO b/182392769: use attribution source util, move to server edge
7934 AttributionSourceState attributionSource = AttributionSourceState();
7935 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007936 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007937 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007938 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007939 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007940 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007941 this,
7942 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007943 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007944 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007945 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007946 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007947 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7948 if (status != NO_ERROR) {
7949 ALOGE("addOutputTrack() initCheck failed %d", status);
7950 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007951 }
Andy Hung6b137d12024-08-27 22:35:17 +00007952 if (!audioserver_flags::portid_volume_management()) {
7953 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7954 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007955 mOutputTracks.add(outputTrack);
7956 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7957 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007958}
7959
Andy Hungee58e4a2023-07-07 13:47:37 -07007960void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007961{
Andy Hung972bec12023-08-31 16:13:39 -07007962 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007963 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7964 if (mOutputTracks[i]->thread() == thread) {
7965 mOutputTracks[i]->destroy();
7966 mOutputTracks.removeAt(i);
7967 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007968 // NO_THREAD_SAFETY_ANALYSIS
7969 // Lambda workaround: as thread != this
7970 // we can safely call the remote thread getOutput.
7971 const bool equalOutput =
7972 [&](){ return thread->getOutput() == mOutput; }();
7973 if (equalOutput) {
7974 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007975 }
Eric Laurent81784c32012-11-19 14:55:58 -08007976 return;
7977 }
7978 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007979 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007980}
7981
Andy Hungc5007f82023-08-29 14:26:09 -07007982// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007983void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007984{
7985 mWaitTimeMs = UINT_MAX;
7986 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007987 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007988 if (strong != 0) {
7989 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7990 if (waitTimeMs < mWaitTimeMs) {
7991 mWaitTimeMs = waitTimeMs;
7992 }
7993 }
7994 }
7995}
7996
Andy Hungee58e4a2023-07-07 13:47:37 -07007997bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007998{
7999 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07008000 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008001 if (thread == 0) {
8002 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
8003 outputTracks[i].get());
8004 return false;
8005 }
Andy Hung87c693c2023-07-06 20:56:16 -07008006 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08008007 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07008008 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08008009 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
8010 thread.get());
8011 return false;
8012 }
8013 }
8014 return true;
8015}
8016
Andy Hungee58e4a2023-07-07 13:47:37 -07008017void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07008018 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07008019{
Kevin Rocard12381092018-04-11 09:19:59 -07008020 for (auto& outputTrack : outputTracks) { // not mOutputTracks
8021 outputTrack->setMetadatas(metadata.tracks);
8022 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008023}
8024
Andy Hungee58e4a2023-07-07 13:47:37 -07008025uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08008026{
Andy Hung7a6a0f02023-11-29 13:42:08 -08008027 // return half the wait time in microseconds.
8028 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08008029}
8030
Andy Hungee58e4a2023-07-07 13:47:37 -07008031void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008032{
8033 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8034 updateWaitTime_l();
8035
8036 MixerThread::cacheParameters_l();
8037}
8038
Eric Laurentb3f315a2021-07-13 15:09:05 +02008039// ----------------------------------------------------------------------------
8040
Andy Hungee58e4a2023-07-07 13:47:37 -07008041/* static */
8042sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008043 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008044 AudioStreamOut* output,
8045 audio_io_handle_t id,
8046 bool systemReady,
8047 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008048 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008049}
8050
Andy Hung583043b2023-07-17 17:05:00 -07008051SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008052 AudioStreamOut* output,
8053 audio_io_handle_t id,
8054 bool systemReady,
8055 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008056 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008057{
8058}
8059
Andy Hungee58e4a2023-07-07 13:47:37 -07008060void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008061 // if mSupportedLatencyModes is empty, the HAL stream does not support
8062 // latency mode control and we can exit.
8063 if (mSupportedLatencyModes.empty()) {
8064 return;
8065 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008066 // Do not update the HAL latency mode if no track is active
8067 if (mActiveTracks.isEmpty()) {
8068 return;
8069 }
8070
Eric Laurent68a40a82022-05-03 18:15:04 +02008071 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8072 if (mSupportedLatencyModes.size() == 1) {
8073 // If the HAL only support one latency mode currently, confirm the choice
8074 latencyMode = mSupportedLatencyModes[0];
8075 } else if (mSupportedLatencyModes.size() > 1) {
8076 // Request low latency if:
8077 // - The low latency mode is requested by the spatializer controller
8078 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8079 // AND
8080 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008081 for (const auto& track : mActiveTracks) {
8082 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008083 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008084 break;
8085 }
8086 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008087 }
8088
8089 if (latencyMode != mSetLatencyMode) {
8090 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008091 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8092 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008093 if (status == NO_ERROR) {
8094 mSetLatencyMode = latencyMode;
8095 }
8096 }
8097}
8098
Andy Hungee58e4a2023-07-07 13:47:37 -07008099status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008100 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008101 return BAD_VALUE;
8102 }
Andy Hung972bec12023-08-31 16:13:39 -07008103 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008104 mRequestedLatencyMode = mode;
8105 return NO_ERROR;
8106}
8107
Andy Hungee58e4a2023-07-07 13:47:37 -07008108void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008109NO_THREAD_SAFETY_ANALYSIS
8110// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008111{
8112 bool hasVirtualizer = false;
8113 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008114 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008115 {
Andy Hung972bec12023-08-31 16:13:39 -07008116 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008117 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008118 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008119 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008120 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8121 }
8122
8123 finalDownMixer = mFinalDownMixer;
8124 mFinalDownMixer.clear();
8125 }
8126
8127 if (hasVirtualizer) {
8128 if (finalDownMixer != nullptr) {
8129 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008130 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008131 }
8132 finalDownMixer.clear();
8133 } else if (!hasDownMixer) {
8134 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008135 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008136 EFFECT_UIID_DOWNMIX, &descriptors);
8137 if (status != NO_ERROR) {
8138 return;
8139 }
8140 ALOG_ASSERT(!descriptors.empty(),
8141 "%s getDescriptors() returned no error but empty list", __func__);
8142
8143 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8144 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008145 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008146
8147 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8148 ALOGW("%s error creating downmixer %d", __func__, status);
8149 finalDownMixer.clear();
8150 } else {
8151 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008152 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008153 }
8154 }
8155
8156 {
Andy Hung972bec12023-08-31 16:13:39 -07008157 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008158 mFinalDownMixer = finalDownMixer;
8159 }
8160}
8161
Andy Hunge2514462023-12-06 14:59:24 -08008162void SpatializerThread::threadLoop_exit()
8163{
8164 // The Spatializer EffectHandle must be released on the PlaybackThread
8165 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8166 mFinalDownMixer.clear();
8167
8168 PlaybackThread::threadLoop_exit();
8169}
8170
Eric Laurent81784c32012-11-19 14:55:58 -08008171// ----------------------------------------------------------------------------
8172// Record
8173// ----------------------------------------------------------------------------
8174
Andy Hung583043b2023-07-17 17:05:00 -07008175sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008176 AudioStreamIn* input,
8177 audio_io_handle_t id,
8178 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008179 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008180}
8181
Andy Hung583043b2023-07-17 17:05:00 -07008182RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008183 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008184 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008185 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008186 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008187 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008188 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008189 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008190 mActiveTracks(&this->mLocalLog),
8191 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008192 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008193 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008194 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8195 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008196 // mFastCapture below
8197 , mFastCaptureFutex(0)
8198 // mInputSource
8199 // mPipeSink
8200 // mPipeSource
8201 , mPipeFramesP2(0)
8202 // mPipeMemory
8203 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008204 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008205 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008206{
Glenn Kastend7dca052015-03-05 16:05:54 -08008207 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008208 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008209
George Burgess IVa8f90c12020-05-14 11:27:19 -07008210 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008211 mIsMsdDevice = strcmp(
8212 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8213 }
8214
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008215 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008216
Andy Hungc8fddf32018-08-08 18:32:37 -07008217 // TODO: We may also match on address as well as device type for
8218 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008219 // TODO: This property should be ensure that only contains one single device type.
8220 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8221 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008222 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8223 : AUDIO_DEVICE_NONE));
8224
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008225 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008226 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008227 size_t numCounterOffers = 0;
8228 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008229#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008230 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008231#else
8232 (void)
8233#endif
8234 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008235 ALOG_ASSERT(index == 0);
8236
8237 // initialize fast capture depending on configuration
8238 bool initFastCapture;
8239 switch (kUseFastCapture) {
8240 case FastCapture_Never:
8241 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008242 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008243 break;
8244 case FastCapture_Always:
8245 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008246 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008247 break;
8248 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008249 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008250 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008251 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008252 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8253 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8254 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008255 break;
8256 // case FastCapture_Dynamic:
8257 }
8258
8259 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008260 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008261 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008262 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8263 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008264 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008265 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008266 const sp<MemoryDealer> roHeap(readOnlyHeap());
8267 sp<IMemory> pipeMemory;
8268 if ((roHeap == 0) ||
8269 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008270 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008271 ALOGE("not enough memory for pipe buffer size=%zu; "
8272 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8273 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8274 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008275 goto failed;
8276 }
8277 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8278 memset(pipeBuffer, 0, pipeSize);
8279 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008280 const NBAIO_Format offersFast[1] = {format};
8281 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008282 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008283 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008284 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008285 mPipeSink = pipe;
8286 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008287 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008288 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008289 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008290 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008291 mPipeSource = pipeReader;
8292 mPipeFramesP2 = pipeFramesP2;
8293 mPipeMemory = pipeMemory;
8294
8295 // create fast capture
8296 mFastCapture = new FastCapture();
8297 FastCaptureStateQueue *sq = mFastCapture->sq();
8298#ifdef STATE_QUEUE_DUMP
8299 // FIXME
8300#endif
8301 FastCaptureState *state = sq->begin();
8302 state->mCblk = NULL;
8303 state->mInputSource = mInputSource.get();
8304 state->mInputSourceGen++;
8305 state->mPipeSink = pipe;
8306 state->mPipeSinkGen++;
8307 state->mFrameCount = mFrameCount;
8308 state->mCommand = FastCaptureState::COLD_IDLE;
8309 // already done in constructor initialization list
8310 //mFastCaptureFutex = 0;
8311 state->mColdFutexAddr = &mFastCaptureFutex;
8312 state->mColdGen++;
8313 state->mDumpState = &mFastCaptureDumpState;
8314#ifdef TEE_SINK
8315 // FIXME
8316#endif
Andy Hung583043b2023-07-17 17:05:00 -07008317 mFastCaptureNBLogWriter =
8318 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008319 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8320 sq->end();
8321 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8322
8323 // start the fast capture
8324 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8325 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008326 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008327 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008328#ifdef AUDIO_WATCHDOG
8329 // FIXME
8330#endif
8331
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008332 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008333 }
Andy Hung8946a282018-04-19 20:04:56 -07008334#ifdef TEE_SINK
8335 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8336 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8337#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008338failed: ;
8339
8340 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008341}
8342
Andy Hungee58e4a2023-07-07 13:47:37 -07008343RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008344{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008345 if (mFastCapture != 0) {
8346 FastCaptureStateQueue *sq = mFastCapture->sq();
8347 FastCaptureState *state = sq->begin();
8348 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8349 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8350 if (old == -1) {
8351 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8352 }
8353 }
8354 state->mCommand = FastCaptureState::EXIT;
8355 sq->end();
8356 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8357 mFastCapture->join();
8358 mFastCapture.clear();
8359 }
Andy Hung583043b2023-07-17 17:05:00 -07008360 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8361 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008362 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008363}
8364
Andy Hungee58e4a2023-07-07 13:47:37 -07008365void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008366{
Glenn Kastend7dca052015-03-05 16:05:54 -08008367 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008368}
8369
Andy Hungee58e4a2023-07-07 13:47:37 -07008370void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008371{
8372 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008373 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008374 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008375 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008376 track->invalidate();
8377 }
8378 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008379 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008380}
8381
Andy Hungee58e4a2023-07-07 13:47:37 -07008382bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008383{
Eric Laurent81784c32012-11-19 14:55:58 -08008384 nsecs_t lastWarning = 0;
8385
8386 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008387
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008388reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008389 {
Andy Hung972bec12023-08-31 16:13:39 -07008390 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008391 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008392 }
8393
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008394 // used to request a deferred sleep, to be executed later while mutex is unlocked
8395 uint32_t sleepUs = 0;
8396
Andy Hung95c94a22023-10-20 16:41:18 -07008397 // timestamp correction enable is determined under lock, used in processing step.
8398 bool timestampCorrectionEnabled = false;
8399
Andy Hung446f4df2019-02-21 12:26:41 -08008400 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8401
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008402 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008403 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008404 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8405 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008406 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008407 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008408
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008409 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008410 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008411
Glenn Kasten735f45f2014-08-18 15:51:59 -07008412 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008413 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008414
Glenn Kasten735f45f2014-08-18 15:51:59 -07008415 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008416 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008417
Eric Laurent33403f02020-05-29 18:35:06 -07008418 bool silenceFastCapture = false;
8419
Andy Hungc5007f82023-08-29 14:26:09 -07008420 { // scope for mutex()
8421 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008422
Eric Laurent021cf962014-05-13 10:18:14 -07008423 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008424
Eric Laurent000a4192014-01-29 15:17:32 -08008425 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008426 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008427 if (exitPending()) {
8428 break;
8429 }
8430
Eric Laurent5c25d562016-07-13 17:17:45 -07008431 // sleep with mutex unlocked
8432 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008433 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008434 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008435 ATRACE_END();
8436 sleepUs = 0;
8437 continue;
8438 }
8439
Glenn Kasten2b806402013-11-20 16:37:38 -08008440 // if no active track(s), then standby and release wakelock
8441 size_t size = mActiveTracks.size();
8442 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008443 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008444 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008445 releaseWakeLock_l();
8446 ALOGV("RecordThread: loop stopping");
8447 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008448 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008449 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008450 goto reacquire_wakelock;
8451 }
8452
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008453 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008454 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008455 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008456 if (activeTrack) { // ensure track release is outside lock.
8457 oldActiveTracks.emplace_back(std::move(activeTrack));
8458 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008459 activeTrack = mActiveTracks[i];
8460 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008461 if (activeTrack->isFastTrack()) {
8462 ALOG_ASSERT(fastTrackToRemove == 0);
8463 fastTrackToRemove = activeTrack;
8464 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008465 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008466 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008467 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008468 continue;
8469 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008470
Andy Hung8d31fd22023-06-26 19:20:57 -07008471 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008472 switch (activeTrackState) {
8473
Andy Hung8d31fd22023-06-26 19:20:57 -07008474 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008475 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008476 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008477 if (activeTrack->isFastTrack()) {
8478 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8479 // Keep a ref on fast track to wait for FastCapture thread to get updated
8480 // state before potential track removal
8481 fastTrackToRemove = activeTrack;
8482 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008483 doBroadcast = true;
8484 size--;
8485 continue;
8486
Andy Hung8d31fd22023-06-26 19:20:57 -07008487 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008488 sleepUs = 10000;
8489 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008490 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008491 continue;
8492
Andy Hung8d31fd22023-06-26 19:20:57 -07008493 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008494 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008495 if (mStandby) {
8496 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008497 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008498 mStandby = false;
8499 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008500 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008501 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008502 break;
8503
Andy Hung8d31fd22023-06-26 19:20:57 -07008504 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008505 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008506 break;
8507
Andy Hung8d31fd22023-06-26 19:20:57 -07008508 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8509 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8510 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008511 default:
Andy Hungce685402018-10-05 17:23:27 -07008512 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8513 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008514 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008515
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008516 if (activeTrack->isFastTrack()) {
8517 ALOG_ASSERT(!mFastTrackAvail);
8518 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008519 // if the active fast track is silenced either:
8520 // 1) silence the whole capture from fast capture buffer if this is
8521 // the only active track
8522 // 2) invalidate this track: this will cause the client to reconnect and possibly
8523 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008524 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008525 if (activeTrack->isSilenced()) {
8526 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008527 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008528 } else {
8529 silenceFastCapture = true;
8530 }
8531 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008532 // Invalidate fast tracks if access to audio history is required as this is not
8533 // possible with fast tracks. Once the fast track has been invalidated, no new
8534 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8535 if (mMaxSharedAudioHistoryMs != 0) {
8536 invalidate = true;
8537 }
8538 if (invalidate) {
8539 activeTrack->invalidate();
8540 ALOG_ASSERT(fastTrackToRemove == 0);
8541 fastTrackToRemove = activeTrack;
8542 removeTrack_l(activeTrack);
8543 mActiveTracks.remove(activeTrack);
8544 size--;
8545 continue;
8546 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008547 fastTrack = activeTrack;
8548 }
Eric Laurent33403f02020-05-29 18:35:06 -07008549
8550 activeTracks.add(activeTrack);
8551 i++;
8552
Glenn Kasten9e982352013-08-14 14:39:50 -07008553 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008554
Andy Hungab65b182023-09-06 19:41:47 -07008555 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008556
Kevin Rocard069c2712018-03-29 19:09:14 -07008557 updateMetadata_l();
8558
Eric Laurent5c25d562016-07-13 17:17:45 -07008559 if (allStopped) {
8560 standbyIfNotAlreadyInStandby();
8561 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008562 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008563 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008564 }
8565
8566 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008567 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008568 if (sleepUs == 0) {
8569 sleepUs = kRecordThreadSleepUs;
8570 }
8571 continue;
8572 }
8573 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008574
Andy Hung95c94a22023-10-20 16:41:18 -07008575 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008576 lockEffectChains_l(effectChains);
8577 }
8578
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008579 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008580
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008581 size_t size = effectChains.size();
8582 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008583 // thread mutex is not locked, but effect chain is locked
8584 effectChains[i]->process_l();
8585 }
8586
Glenn Kasten735f45f2014-08-18 15:51:59 -07008587 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008588 if (mFastCapture != 0) {
8589 FastCaptureStateQueue *sq = mFastCapture->sq();
8590 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008591 bool didModify = false;
8592 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008593 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8594 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8595 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8596 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8597 if (old == -1) {
8598 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8599 }
8600 }
8601 state->mCommand = FastCaptureState::READ_WRITE;
8602#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008603 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008604 FastThreadDumpState::kSamplingNforLowRamDevice :
8605 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008606#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008607 didModify = true;
8608 }
8609 audio_track_cblk_t *cblkOld = state->mCblk;
8610 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8611 if (cblkNew != cblkOld) {
8612 state->mCblk = cblkNew;
8613 // block until acked if removing a fast track
8614 if (cblkOld != NULL) {
8615 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8616 }
8617 didModify = true;
8618 }
jiabin01c8f562018-07-19 17:47:28 -07008619 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8620 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8621 if (state->mFastPatchRecordBufferProvider != abp) {
8622 state->mFastPatchRecordBufferProvider = abp;
8623 state->mFastPatchRecordFormat = fastTrack == 0 ?
8624 AUDIO_FORMAT_INVALID : fastTrack->format();
8625 didModify = true;
8626 }
Eric Laurent33403f02020-05-29 18:35:06 -07008627 if (state->mSilenceCapture != silenceFastCapture) {
8628 state->mSilenceCapture = silenceFastCapture;
8629 didModify = true;
8630 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008631 sq->end(didModify);
8632 if (didModify) {
8633 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008634#if 0
8635 if (kUseFastCapture == FastCapture_Dynamic) {
8636 mNormalSource = mPipeSource;
8637 }
8638#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008639 }
8640 }
8641
Glenn Kasten735f45f2014-08-18 15:51:59 -07008642 // now run the fast track destructor with thread mutex unlocked
8643 fastTrackToRemove.clear();
8644
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008645 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8646 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8647 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8648 // If destination is non-contiguous, first read past the nominal end of buffer, then
8649 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008650
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008651 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008652 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008653 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008654
8655 // If an NBAIO source is present, use it to read the normal capture's data
8656 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008657 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008658
8659 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8660 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8661 // we immediately retry the read() to get data and prevent another overflow.
8662 for (int retries = 0; retries <= 2; ++retries) {
8663 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8664 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8665 framesToRead);
8666 if (framesRead != OVERRUN) break;
8667 }
8668
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008669 const ssize_t availableToRead = mPipeSource->availableToRead();
8670 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008671 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008672 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008673 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8674 "more frames to read than fifo size, %zd > %zu",
8675 availableToRead, mPipeFramesP2);
8676 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8677 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8678 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8679 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008680 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8681 }
8682 if (framesRead < 0) {
8683 status_t status = (status_t) framesRead;
8684 switch (status) {
8685 case OVERRUN:
8686 ALOGW("overrun on read from pipe");
8687 framesRead = 0;
8688 break;
8689 case NEGOTIATE:
8690 ALOGE("re-negotiation is needed");
8691 framesRead = -1; // Will cause an attempt to recover.
8692 break;
8693 default:
8694 ALOGE("unknown error %d on read from pipe", status);
8695 break;
8696 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008697 }
8698 // otherwise use the HAL / AudioStreamIn directly
8699 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008700 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008701 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008702 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008703 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008704 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008705 if (result < 0) {
8706 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008707 } else {
8708 framesRead = bytesRead / mFrameSize;
8709 }
8710 }
8711
Andy Hung446f4df2019-02-21 12:26:41 -08008712 const int64_t lastIoEndNs = systemTime(); // end IO timing
8713
Andy Hung3f0c9022016-01-15 17:49:46 -08008714 // Update server timestamp with server stats
8715 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008716 if (framesRead >= 0) {
8717 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8718 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8719 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008720
8721 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008722 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008723 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008724 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008725 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8726 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8727 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008728 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008729 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8730
8731 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008732 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008733 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008734 id(), (long long)time, (long long)position);
8735 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8736 position = correctedTimestamp.mFrames;
8737 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008738 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008739 id(), (long long)time, (long long)position);
8740 }
8741
Andy Hung3f0c9022016-01-15 17:49:46 -08008742 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8743 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8744 // Note: In general record buffers should tend to be empty in
8745 // a properly running pipeline.
8746 //
8747 // Also, it is not advantageous to call get_presentation_position during the read
8748 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008749 } else {
8750 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008751 }
8752 }
Andy Hunge6c37112019-02-26 17:38:10 -08008753
8754 // From the timestamp, input read latency is negative output write latency.
8755 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008756 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008757 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8758 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8759 mLatencyMs.add(latencyMs);
8760 }
8761
Andy Hung3f0c9022016-01-15 17:49:46 -08008762 // Use this to track timestamp information
8763 // ALOGD("%s", mTimestamp.toString().c_str());
8764
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008765 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008766 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008767 // Force input into standby so that it tries to recover at next read attempt
8768 inputStandBy();
8769 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008770 }
8771 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008772 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008773 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008774 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008775 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008776
Andy Hung8946a282018-04-19 20:04:56 -07008777#ifdef TEE_SINK
8778 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8779#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008780 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008781 {
8782 size_t part1 = mRsmpInFramesP2 - rear;
8783 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008784 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008785 (framesRead - part1) * mFrameSize);
8786 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008787 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008788 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008789
8790 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008791
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008792 // loop over each active track
8793 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008794 if (activeTrack) { // ensure track release is outside lock.
8795 oldActiveTracks.emplace_back(std::move(activeTrack));
8796 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008797 activeTrack = activeTracks[i];
8798
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008799 // skip fast tracks, as those are handled directly by FastCapture
8800 if (activeTrack->isFastTrack()) {
8801 continue;
8802 }
8803
Andy Hung73c02e42015-03-29 01:13:58 -07008804 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008805 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8806
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008807 enum {
8808 OVERRUN_UNKNOWN,
8809 OVERRUN_TRUE,
8810 OVERRUN_FALSE
8811 } overrun = OVERRUN_UNKNOWN;
8812
8813 // loop over getNextBuffer to handle circular sink
8814 for (;;) {
8815
Andy Hung8d31fd22023-06-26 19:20:57 -07008816 activeTrack->sinkBuffer().frameCount = ~0;
8817 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8818 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008819 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8820
Andy Hung73c02e42015-03-29 01:13:58 -07008821 // check available frames and handle overrun conditions
8822 // if the record track isn't draining fast enough.
8823 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008824 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008825 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008826 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008827 overrun = OVERRUN_TRUE;
8828 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008829 if (framesOut == 0 || framesIn == 0) {
8830 break;
8831 }
8832
Andy Hung6770c6f2015-04-07 13:43:36 -07008833 // Don't allow framesOut to be larger than what is possible with resampling
8834 // from framesIn.
8835 // This isn't strictly necessary but helps limit buffer resizing in
8836 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008837 if (audio_is_linear_pcm(activeTrack->format())) {
8838 framesOut = min(framesOut,
8839 destinationFramesPossible(
8840 framesIn, mSampleRate, activeTrack->sampleRate()));
8841 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008842
8843 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008844 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008845 // straight from RecordThread buffer to RecordTrack buffer.
8846 AudioBufferProvider::Buffer buffer;
8847 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008848 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008849 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008850 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008851 ALOGV_IF(buffer.frameCount != framesOut,
8852 "%s() read less than expected (%zu vs %zu)",
8853 __func__, buffer.frameCount, framesOut);
8854 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008855 memcpy(activeTrack->sinkBuffer().raw,
8856 buffer.raw, buffer.frameCount * mFrameSize);
8857 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008858 } else {
8859 framesOut = 0;
8860 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008861 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008862 }
8863 } else {
8864 // process frames from the RecordThread buffer provider to the RecordTrack
8865 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008866 framesOut = activeTrack->recordBufferConverter()->convert(
8867 activeTrack->sinkBuffer().raw,
8868 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008869 framesOut);
8870 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008871
8872 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8873 overrun = OVERRUN_FALSE;
8874 }
8875
Andy Hung93bb5732023-05-04 21:16:34 -07008876 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8877 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008878 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008879 if (framesToDrop == 0) {
8880 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008881 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008882 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008883 // Sanitize before releasing if the track has no access to the source data
8884 // An idle UID receives silence from non virtual devices until active
8885 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008886 memset(activeTrack->sinkBuffer().raw,
8887 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008888 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008889 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008890 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008891 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008892 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008893 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008894 }
8895 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008896
8897 switch (overrun) {
8898 case OVERRUN_TRUE:
8899 // client isn't retrieving buffers fast enough
8900 if (!activeTrack->setOverflow()) {
8901 nsecs_t now = systemTime();
8902 // FIXME should lastWarning per track?
8903 if ((now - lastWarning) > kWarningThrottleNs) {
8904 ALOGW("RecordThread: buffer overflow");
8905 lastWarning = now;
8906 }
8907 }
8908 break;
8909 case OVERRUN_FALSE:
8910 activeTrack->clearOverflow();
8911 break;
8912 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008913 break;
8914 }
8915
Andy Hung3f0c9022016-01-15 17:49:46 -08008916 // update frame information and push timestamp out
8917 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008918 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008919 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8920 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008921 }
8922
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008923unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008924 // enable changes in effect chain
8925 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008926 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008927 if (audio_has_proportional_frames(mFormat)
8928 && loopCount == lastLoopCountRead + 1) {
8929 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8930 const double jitterMs =
8931 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8932 {framesRead, readPeriodNs},
8933 {0, 0} /* lastTimestamp */, mSampleRate);
8934 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8935
Andy Hung972bec12023-08-31 16:13:39 -07008936 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008937 mIoJitterMs.add(jitterMs);
8938 mProcessTimeMs.add(processMs);
8939 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008940 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008941 // update timing info.
8942 mLastIoBeginNs = lastIoBeginNs;
8943 mLastIoEndNs = lastIoEndNs;
8944 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008945 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008946 mThreadloopExecutor.process(); // process any remaining deferred actions.
8947 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008948
Glenn Kasten93e471f2013-08-19 08:40:07 -07008949 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008950
8951 {
Andy Hung972bec12023-08-31 16:13:39 -07008952 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008953 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008954 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008955 track->invalidate();
8956 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008957 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008958 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008959 }
8960
8961 releaseWakeLock();
8962
8963 ALOGV("RecordThread %p exiting", this);
8964 return false;
8965}
8966
Andy Hungee58e4a2023-07-07 13:47:37 -07008967void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008968{
8969 if (!mStandby) {
8970 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008971 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008972 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008973 mStandby = true;
8974 }
8975}
8976
Andy Hungee58e4a2023-07-07 13:47:37 -07008977void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008978{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008979 // Idle the fast capture if it's currently running
8980 if (mFastCapture != 0) {
8981 FastCaptureStateQueue *sq = mFastCapture->sq();
8982 FastCaptureState *state = sq->begin();
8983 if (!(state->mCommand & FastCaptureState::IDLE)) {
8984 state->mCommand = FastCaptureState::COLD_IDLE;
8985 state->mColdFutexAddr = &mFastCaptureFutex;
8986 state->mColdGen++;
8987 mFastCaptureFutex = 0;
8988 sq->end();
8989 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8990 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8991#if 0
8992 if (kUseFastCapture == FastCapture_Dynamic) {
8993 // FIXME
8994 }
8995#endif
8996#ifdef AUDIO_WATCHDOG
8997 // FIXME
8998#endif
8999 } else {
9000 sq->end(false /*didModify*/);
9001 }
9002 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07009003 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009004 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07009005
9006 // If going into standby, flush the pipe source.
9007 if (mPipeSource.get() != nullptr) {
9008 const ssize_t flushed = mPipeSource->flush();
9009 if (flushed > 0) {
9010 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
9011 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
9012 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
9013 }
9014 }
Eric Laurent81784c32012-11-19 14:55:58 -08009015}
9016
Andy Hungc5007f82023-08-29 14:26:09 -07009017// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009018sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07009019 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009020 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009021 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08009022 audio_format_t format,
9023 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08009024 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08009025 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009026 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009027 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00009028 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07009029 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08009030 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08009031 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009032 audio_port_handle_t portId,
9033 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009034{
Glenn Kasten74935e42013-12-19 08:56:45 -08009035 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009036 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009037 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009038 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009039 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009040 audio_input_flags_t requestedFlags = *flags;
9041 uint32_t sampleRate;
9042
9043 lStatus = initCheck();
9044 if (lStatus != NO_ERROR) {
9045 ALOGE("createRecordTrack_l() audio driver not initialized");
9046 goto Exit;
9047 }
9048
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009049 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9050 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9051 lStatus = BAD_VALUE;
9052 goto Exit;
9053 }
9054
Eric Laurentec376dc2021-04-08 20:41:22 +02009055 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009056 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009057 lStatus = PERMISSION_DENIED;
9058 goto Exit;
9059 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009060 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009061 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009062 lStatus = BAD_VALUE;
9063 goto Exit;
9064 }
9065 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009066 if (*pSampleRate == 0) {
9067 *pSampleRate = mSampleRate;
9068 }
9069 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009070
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009071 // special case for FAST flag considered OK if fast capture is present and access to
9072 // audio history is not required
9073 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009074 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9075 }
9076
Eric Laurentf14db3c2017-12-08 14:20:36 -08009077 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009078 if ((*flags & inputFlags) != *flags) {
9079 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9080 " input flags (%08x)",
9081 *flags, inputFlags);
9082 *flags = (audio_input_flags_t)(*flags & inputFlags);
9083 }
Eric Laurent81784c32012-11-19 14:55:58 -08009084
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009085 // client expresses a preference for FAST and no access to audio history,
9086 // but we get the final say
9087 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009088 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009089 // we formerly checked for a callback handler (non-0 tid),
9090 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009091 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009092 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009093 // Frame count is not specified (0), or is less than or equal the pipe depth.
9094 // It is OK to provide a higher capacity than requested.
9095 // We will force it to mPipeFramesP2 below.
9096 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009097 // PCM data
9098 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009099 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009100 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009101 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009102 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009103 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009104 hasFastCapture() &&
9105 // there are sufficient fast track slots available
9106 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009107 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009108 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009109 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009110 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009111 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009112 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009113 audio_input_flags_t old = *flags;
9114 chain->checkInputFlagCompatibility(flags);
9115 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009116 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9117 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009118 }
9119 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009120 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009121 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9122 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009123 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009124 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9125 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009126 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009127 this, frameCount, mFrameCount, mPipeFramesP2,
9128 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009129 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009130 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009131 }
9132 }
9133
Eric Laurentf14db3c2017-12-08 14:20:36 -08009134 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9135 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9136 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9137 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9138 lStatus = BAD_TYPE;
9139 goto Exit;
9140 }
9141
Glenn Kasten74105912014-07-03 12:28:53 -07009142 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009143 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009144 // fast track: frame count is exactly the pipe depth
9145 frameCount = mPipeFramesP2;
9146 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009147 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009148 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009149 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9150 // or 20 ms if there is a fast capture
9151 // TODO This could be a roundupRatio inline, and const
9152 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9153 * sampleRate + mSampleRate - 1) / mSampleRate;
9154 // minimum number of notification periods is at least kMinNotifications,
9155 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9156 static const size_t kMinNotifications = 3;
9157 static const uint32_t kMinMs = 30;
9158 // TODO This could be a roundupRatio inline
9159 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9160 // TODO This could be a roundupRatio inline
9161 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9162 maxNotificationFrames;
9163 const size_t minFrameCount = maxNotificationFrames *
9164 max(kMinNotifications, minNotificationsByMs);
9165 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009166 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9167 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009168 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009169 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009170 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009171 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009172
Andy Hungc5007f82023-08-29 14:26:09 -07009173 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009174 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009175 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009176 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009177 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009178 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009179 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009180 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009181 }
Eric Laurent81784c32012-11-19 14:55:58 -08009182
Andy Hung8d31fd22023-06-26 19:20:57 -07009183 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009184 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009185 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009186 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009187 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009188
Glenn Kasten03003332013-08-06 15:40:54 -07009189 lStatus = track->initCheck();
9190 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009191 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009192 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009193 goto Exit;
9194 }
9195 mTracks.add(track);
9196
Eric Laurent05067782016-06-01 18:27:28 -07009197 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009198 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9199 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9200 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009201 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009202 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009203
9204 if (maxSharedAudioHistoryMs != 0) {
9205 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9206 }
Eric Laurent81784c32012-11-19 14:55:58 -08009207 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009208
Eric Laurent81784c32012-11-19 14:55:58 -08009209 lStatus = NO_ERROR;
9210
9211Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009212 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009213 return track;
9214}
9215
Andy Hungee58e4a2023-07-07 13:47:37 -07009216status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009217 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009218 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009219{
9220 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9221 sp<ThreadBase> strongMe = this;
9222 status_t status = NO_ERROR;
9223
9224 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009225 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009226 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009227 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009228 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009229 event, triggerSession,
9230 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009231 }
9232
9233 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009234 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009235 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009236 if (recordTrack->isInvalid()) {
9237 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009238 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9239 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009240 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009241 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009242 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009243 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9244 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009245 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009246 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009247 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009248 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009249 }
9250 return status;
9251 }
9252
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009253 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9254 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9255 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009256 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009257 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009258 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009259 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009260 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009261 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009262 if (recordTrack->isInvalid()) {
9263 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009264 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9265 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009266 // STARTING_2 forces destroy to call stopInput.
9267 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009268 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9269 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009270 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009271 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009272 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009273 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009274 // Someone else has changed state, let them take over,
9275 // leave mState in the new state.
9276 recordTrack->clearSyncStartEvent();
9277 return INVALID_OPERATION;
9278 }
9279 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009280 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009281 ALOGW("%s(%d): startInput failed, status %d",
9282 __func__, recordTrack->id(), status);
9283 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9284 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009285 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009286 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009287 return status;
9288 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009289 sendIoConfigEvent_l(
9290 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009291 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009292
9293 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9294
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009295 // Catch up with current buffer indices if thread is already running.
9296 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9297 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9298 // see previously buffered data before it called start(), but with greater risk of overrun.
9299
Andy Hung8d31fd22023-06-26 19:20:57 -07009300 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009301 if (!recordTrack->isDirect()) {
9302 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009303 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009304 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009305 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009306 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009307 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009308 return status;
9309 }
Eric Laurent81784c32012-11-19 14:55:58 -08009310}
9311
Andy Hungee58e4a2023-07-07 13:47:37 -07009312void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009313{
Andy Hungee58e4a2023-07-07 13:47:37 -07009314 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009315
9316 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009317 sp<IAfTrackBase> ptr =
9318 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9319 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009320 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009321 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009322 }
Eric Laurent81784c32012-11-19 14:55:58 -08009323 }
9324}
9325
Andy Hungee58e4a2023-07-07 13:47:37 -07009326bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009327 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009328 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009329 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009330 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009331 return false;
9332 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009333 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009334 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009335
Andy Hungabfab202019-03-07 19:45:54 -08009336 // NOTE: Waiting here is important to keep stop synchronous.
9337 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009338 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009339 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009340 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009341 }
Andy Hungce685402018-10-05 17:23:27 -07009342
Andy Hung8d31fd22023-06-26 19:20:57 -07009343 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009344 ALOGV("Record stopped OK");
9345 return true;
9346 }
Andy Hungce685402018-10-05 17:23:27 -07009347
9348 // don't handle anything - we've been invalidated or restarted and in a different state
9349 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009350 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009351 return false;
9352}
9353
Andy Hungee58e4a2023-07-07 13:47:37 -07009354bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009355{
9356 return false;
9357}
9358
Andy Hungee58e4a2023-07-07 13:47:37 -07009359status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009360{
9361#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9362 if (!isValidSyncEvent(event)) {
9363 return BAD_VALUE;
9364 }
9365
Glenn Kastend848eb42016-03-08 13:42:11 -08009366 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009367 status_t ret = NAME_NOT_FOUND;
9368
Andy Hung972bec12023-08-31 16:13:39 -07009369 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009370
9371 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009372 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009373 if (eventSession == track->sessionId()) {
9374 (void) track->setSyncEvent(event);
9375 ret = NO_ERROR;
9376 }
9377 }
9378 return ret;
9379#else
9380 return BAD_VALUE;
9381#endif
9382}
9383
Andy Hungee58e4a2023-07-07 13:47:37 -07009384status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009385 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009386{
9387 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009388 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009389 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009390 return NO_INIT;
9391 }
jiabin9ff780e2018-03-19 18:19:52 -07009392 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9393 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009394}
9395
Andy Hungee58e4a2023-07-07 13:47:37 -07009396status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009397 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009398{
Paul McLean12340082019-03-19 09:35:05 -06009399 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009400 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009401 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009402 return NO_INIT;
9403 }
Paul McLean12340082019-03-19 09:35:05 -06009404 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009405}
9406
Andy Hungee58e4a2023-07-07 13:47:37 -07009407status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009408{
Paul McLean12340082019-03-19 09:35:05 -06009409 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009410 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009411 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009412 return NO_INIT;
9413 }
Paul McLean12340082019-03-19 09:35:05 -06009414 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009415}
9416
Andy Hungee58e4a2023-07-07 13:47:37 -07009417status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009418 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9419 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009420 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009421 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9422}
9423
Andy Hungee58e4a2023-07-07 13:47:37 -07009424status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009425 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9426 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009427
Eric Laurentec376dc2021-04-08 20:41:22 +02009428 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9429 return BAD_VALUE;
9430 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009431
9432 if (sharedAudioStartMs < 0
9433 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009434 return BAD_VALUE;
9435 }
9436
Eric Laurent2407ce32021-04-26 14:56:03 +02009437 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9438 // As we cannot detect more than one wraparound, only accept values up current write position
9439 // after one wraparound
9440 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9441 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009442 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009443 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9444 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009445 // Bring the start frame position within the input buffer to match the documented
9446 // "best effort" behavior of the API.
9447 if (sharedOffset < 0) {
9448 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009449 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009450 sharedAudioStartFrames =
9451 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009452 }
9453
Eric Laurentec376dc2021-04-08 20:41:22 +02009454 mSharedAudioPackageName = sharedAudioPackageName;
9455 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009456 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009457 } else {
9458 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009459 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009460 }
9461 return NO_ERROR;
9462}
9463
Andy Hungee58e4a2023-07-07 13:47:37 -07009464void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009465 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9466 mSharedAudioStartFrames = -1;
9467 mSharedAudioPackageName = "";
9468}
9469
Andy Hungee58e4a2023-07-07 13:47:37 -07009470ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009471{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009472 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009473 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009474 }
9475 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009476 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009477 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009478 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009479 }
9480 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009481 MetadataUpdate change;
9482 change.recordMetadataUpdate = metadata.tracks;
9483 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009484}
9485
Andy Hungc5007f82023-08-29 14:26:09 -07009486// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009487void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009488{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009489 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009490 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009491
Eric Laurent81784c32012-11-19 14:55:58 -08009492 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009493 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009494 removeTrack_l(track);
9495 }
9496}
9497
Andy Hungee58e4a2023-07-07 13:47:37 -07009498void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009499{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009500 String8 result;
9501 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009502 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009503
Eric Laurent81784c32012-11-19 14:55:58 -08009504 mTracks.remove(track);
9505 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009506 if (track->isFastTrack()) {
9507 ALOG_ASSERT(!mFastTrackAvail);
9508 mFastTrackAvail = true;
9509 }
Eric Laurent81784c32012-11-19 14:55:58 -08009510}
9511
Andy Hungee58e4a2023-07-07 13:47:37 -07009512void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009513{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009514 AudioStreamIn *input = mInput;
9515 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9516 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009517 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009518 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009519 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009520 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009521 }
Andy Hungbfa64962017-06-12 14:43:19 -07009522
9523 if (input != nullptr) {
9524 dprintf(fd, " Hal stream dump:\n");
9525 (void)input->stream->dump(fd);
9526 }
9527
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009528 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009529 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009530
Glenn Kasten2f90c512015-12-02 11:40:09 -08009531 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9532 // while we are dumping it. It may be inconsistent, but it won't mutate!
9533 // This is a large object so we place it on the heap.
9534 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009535 const std::unique_ptr<FastCaptureDumpState> copy =
9536 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009537 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009538}
9539
Andy Hungee58e4a2023-07-07 13:47:37 -07009540void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009541{
Eric Laurent81784c32012-11-19 14:55:58 -08009542 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009543 size_t numtracks = mTracks.size();
9544 size_t numactive = mActiveTracks.size();
9545 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009546 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009547 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009548 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009549 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009550 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009551 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009552 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009553 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009554 if (track != 0) {
9555 bool active = mActiveTracks.indexOf(track) >= 0;
9556 if (active) {
9557 numactiveseen++;
9558 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009559 result.append(prefix);
9560 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009561 }
Eric Laurent81784c32012-11-19 14:55:58 -08009562 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009563 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009564 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009565 }
9566
Marco Nelissenb2208842014-02-07 14:00:50 -08009567 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009568 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009569 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009570 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009571 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009572 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009573 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009574 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009575 result.append(prefix);
9576 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009577 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009578 }
Eric Laurent81784c32012-11-19 14:55:58 -08009579
9580 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009581 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009582}
9583
Andy Hungee58e4a2023-07-07 13:47:37 -07009584void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009585{
Andy Hung972bec12023-08-31 16:13:39 -07009586 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009587 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009588 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009589 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009590 track->setSilenced(silenced);
9591 }
9592 }
9593}
Andy Hung73c02e42015-03-29 01:13:58 -07009594
Andy Hung8d31fd22023-06-26 19:20:57 -07009595void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009596{
Andy Hung87c693c2023-07-06 20:56:16 -07009597 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009598 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009599 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009600 const int32_t rear = recordThread->mRsmpInRear;
9601 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009602 if (mRecordTrack->startFrames() >= 0) {
9603 int32_t startFrames = mRecordTrack->startFrames();
9604 // Accept a recent wraparound of mRsmpInRear
9605 if (startFrames <= rear) {
9606 deltaFrames = rear - startFrames;
9607 } else {
9608 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009609 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009610 // start frame cannot be further in the past than start of resampling buffer
9611 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9612 deltaFrames = recordThread->mRsmpInFrames;
9613 }
9614 }
9615 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009616}
9617
Andy Hung8d31fd22023-06-26 19:20:57 -07009618void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009619 size_t *framesAvailable, bool *hasOverrun)
9620{
Andy Hung87c693c2023-07-06 20:56:16 -07009621 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009622 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009623 const int32_t rear = recordThread->mRsmpInRear;
9624 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009625 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009626
9627 size_t framesIn;
9628 bool overrun = false;
9629 if (filled < 0) {
9630 // should not happen, but treat like a massive overrun and re-sync
9631 framesIn = 0;
9632 mRsmpInFront = rear;
9633 overrun = true;
9634 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9635 framesIn = (size_t) filled;
9636 } else {
9637 // client is not keeping up with server, but give it latest data
9638 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009639 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9640 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009641 overrun = true;
9642 }
9643 if (framesAvailable != NULL) {
9644 *framesAvailable = framesIn;
9645 }
9646 if (hasOverrun != NULL) {
9647 *hasOverrun = overrun;
9648 }
9649}
9650
Eric Laurent81784c32012-11-19 14:55:58 -08009651// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009652status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009653 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009654{
Andy Hung87c693c2023-07-06 20:56:16 -07009655 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009656 if (threadBase == 0) {
9657 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009658 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009659 return NOT_ENOUGH_DATA;
9660 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009661 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009662 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009663 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009664 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009665 // FIXME should not be P2 (don't want to increase latency)
9666 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009667 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009668 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009669
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009670 front &= recordThread->mRsmpInFramesP2 - 1;
9671 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009672 if (part1 > (size_t) filled) {
9673 part1 = filled;
9674 }
9675 size_t ask = buffer->frameCount;
9676 ALOG_ASSERT(ask > 0);
9677 if (part1 > ask) {
9678 part1 = ask;
9679 }
9680 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009681 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009682 buffer->raw = NULL;
9683 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009684 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009685 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009686 }
9687
Andy Hung57446612015-04-19 23:56:46 -07009688 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009689 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009690 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009691 return NO_ERROR;
9692}
9693
9694// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009695void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009696 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009697{
Hongwei Wang95e37682019-04-12 11:13:36 -07009698 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009699 if (stepCount == 0) {
9700 return;
9701 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009702 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009703 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009704 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009705 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009706 buffer->frameCount = 0;
9707}
9708
Andy Hungee58e4a2023-07-07 13:47:37 -07009709void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009710{
Andy Hung972bec12023-08-31 16:13:39 -07009711 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009712 checkBtNrec_l();
9713}
9714
Andy Hungee58e4a2023-07-07 13:47:37 -07009715void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009716{
9717 // disable AEC and NS if the device is a BT SCO headset supporting those
9718 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009719 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009720 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009721 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9722 for (size_t i = 0; i < mEffectChains.size(); i++) {
9723 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9724 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9725 }
9726 }
9727}
9728
Andy Hung97a893e2015-03-29 01:03:07 -07009729
Andy Hungee58e4a2023-07-07 13:47:37 -07009730bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009731 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009732{
9733 bool reconfig = false;
9734
Eric Laurent10351942014-05-08 18:49:52 -07009735 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009736
Eric Laurent10351942014-05-08 18:49:52 -07009737 audio_format_t reqFormat = mFormat;
9738 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009739 // 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 +08009740 [[maybe_unused]] audio_channel_mask_t channelMask =
9741 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009742
9743 AudioParameter param = AudioParameter(keyValuePair);
9744 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009745
9746 // scope for AutoPark extends to end of method
9747 AutoPark<FastCapture> park(mFastCapture);
9748
Eric Laurent10351942014-05-08 18:49:52 -07009749 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9750 // channel count change can be requested. Do we mandate the first client defines the
9751 // HAL sampling rate and channel count or do we allow changes on the fly?
9752 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9753 samplingRate = value;
9754 reconfig = true;
9755 }
9756 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009757 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009758 status = BAD_VALUE;
9759 } else {
9760 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009761 reconfig = true;
9762 }
Eric Laurent10351942014-05-08 18:49:52 -07009763 }
9764 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9765 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009766 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009767 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009768 status = BAD_VALUE;
9769 } else {
9770 channelMask = mask;
9771 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009772 }
Eric Laurent10351942014-05-08 18:49:52 -07009773 }
9774 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9775 // do not accept frame count changes if tracks are open as the track buffer
9776 // size depends on frame count and correct behavior would not be guaranteed
9777 // if frame count is changed after track creation
9778 if (mActiveTracks.size() > 0) {
9779 status = INVALID_OPERATION;
9780 } else {
9781 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009782 }
Eric Laurent10351942014-05-08 18:49:52 -07009783 }
9784 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009785 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009786 }
9787 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9788 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009789 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009790 }
Glenn Kastene198c362013-08-13 09:13:36 -07009791
Eric Laurent10351942014-05-08 18:49:52 -07009792 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009793 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009794 if (status == INVALID_OPERATION) {
9795 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009796 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009797 }
9798 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009799 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009800 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9801 if (mInput->stream->getAudioProperties(&config) == OK &&
9802 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9803 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009804 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009805 status = NO_ERROR;
9806 }
Eric Laurent81784c32012-11-19 14:55:58 -08009807 }
Eric Laurent10351942014-05-08 18:49:52 -07009808 if (status == NO_ERROR) {
9809 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009810 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009811 }
9812 }
Eric Laurent81784c32012-11-19 14:55:58 -08009813 }
Eric Laurent10351942014-05-08 18:49:52 -07009814
Eric Laurent81784c32012-11-19 14:55:58 -08009815 return reconfig;
9816}
9817
Andy Hungee58e4a2023-07-07 13:47:37 -07009818String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009819{
Andy Hung972bec12023-08-31 16:13:39 -07009820 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009821 if (initCheck() == NO_ERROR) {
9822 String8 out_s8;
9823 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9824 return out_s8;
9825 }
Eric Laurent81784c32012-11-19 14:55:58 -08009826 }
Andy Hung920f6572022-10-06 12:09:49 -07009827 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009828}
9829
Andy Hungab65b182023-09-06 19:41:47 -07009830void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009831 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009832 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009833 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009834 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009835 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009836 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009837 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9838 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009839 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009840 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009841 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009842 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009843 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009844 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009845 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009846 break;
9847 }
Andy Hungab65b182023-09-06 19:41:47 -07009848 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009849}
9850
Andy Hungee58e4a2023-07-07 13:47:37 -07009851void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009852{
Dean Wheatley6c009512023-10-23 09:34:14 +11009853 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9854 mSampleRate = audioConfig.sample_rate;
9855 mChannelMask = audioConfig.channel_mask;
9856 if (!audio_is_input_channel(mChannelMask)) {
9857 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9858 }
9859
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009860 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009861
9862 // Get actual HAL format.
9863 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9864 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9865 // Get format from the shim, which will be different than the HAL format
9866 // if recording compressed audio from IEC61937 wrapped sources.
9867 mFormat = audioConfig.format;
9868 if (!audio_is_valid_format(mFormat)) {
9869 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9870 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009871 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009872 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9873 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009874 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009875 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009876 ALOGI("HAL format %#x is not linear pcm", mFormat);
9877 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009878 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009879 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9880 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009881 result = mInput->stream->getBufferSize(&mBufferSize);
9882 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009883 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009884 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9885 "mBufferSize=%zu, mFrameCount=%zu",
9886 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009887
Eric Laurentec376dc2021-04-08 20:41:22 +02009888 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9889 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009890 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009891
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009892 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9893 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009894
9895 audio_input_flags_t flags = mInput->flags;
9896 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9897 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009898 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009899 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9900 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9901 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9902 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9903 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9904 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009905}
9906
Andy Hungee58e4a2023-07-07 13:47:37 -07009907uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009908{
Andy Hung972bec12023-08-31 16:13:39 -07009909 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009910 uint32_t result;
9911 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9912 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009913 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009914 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009915}
9916
Andy Hungee58e4a2023-07-07 13:47:37 -07009917KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009918{
Glenn Kastend848eb42016-03-08 13:42:11 -08009919 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009920 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009921 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009922 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009923 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009924 if (ids.indexOfKey(sessionId) < 0) {
9925 ids.add(sessionId, true);
9926 }
9927 }
9928 return ids;
9929}
9930
Andy Hungee58e4a2023-07-07 13:47:37 -07009931AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009932{
Andy Hung972bec12023-08-31 16:13:39 -07009933 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009934 AudioStreamIn *input = mInput;
9935 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009936 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009937 return input;
9938}
9939
Andy Hungc5007f82023-08-29 14:26:09 -07009940// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009941sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009942{
9943 if (mInput == NULL) {
9944 return NULL;
9945 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009946 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009947}
9948
Andy Hungee58e4a2023-07-07 13:47:37 -07009949status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009950{
Eric Laurent81784c32012-11-19 14:55:58 -08009951 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009952 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009953 chain->setInBuffer(NULL);
9954 chain->setOutBuffer(NULL);
9955
9956 checkSuspendOnAddEffectChain_l(chain);
9957
Eric Laurent1b928682014-10-02 19:41:47 -07009958 // make sure enabled pre processing effects state is communicated to the HAL as we
9959 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009960 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009961
Eric Laurent81784c32012-11-19 14:55:58 -08009962 mEffectChains.add(chain);
9963
9964 return NO_ERROR;
9965}
9966
Andy Hungee58e4a2023-07-07 13:47:37 -07009967size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009968{
9969 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009970
9971 for (size_t i = 0; i < mEffectChains.size(); i++) {
9972 if (chain == mEffectChains[i]) {
9973 mEffectChains.removeAt(i);
9974 break;
9975 }
Eric Laurent81784c32012-11-19 14:55:58 -08009976 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009977 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009978}
9979
Andy Hungee58e4a2023-07-07 13:47:37 -07009980status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009981 audio_patch_handle_t *handle)
9982{
9983 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009984
9985 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009986 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009987 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009988 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009989 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009990 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009991 }
9992
Eric Laurentd8365c52017-07-16 15:27:05 -07009993 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009994
9995 // store new source and send to effects
9996 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9997 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009998 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009999 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -070010000 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010001 }
Eric Laurent1c333e22014-05-20 10:48:17 -070010002
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010003 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010004 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10005 status = hwDevice->createAudioPatch(patch->num_sources,
10006 patch->sources,
10007 patch->num_sinks,
10008 patch->sinks,
10009 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010010 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010011 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
10012 patch->sinks[0].ext.mix.usecase.source,
10013 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -070010014 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -070010015 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010016
jiabinc52b1ff2019-10-31 17:20:42 -070010017 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -070010018 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -070010019 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -070010020 }
Eric Laurent296fb132015-05-01 11:38:42 -070010021
Andy Hungc2b11cb2020-04-22 09:04:01 -070010022 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -070010023 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -070010024 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -070010025 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -070010026 // also dispatch to active AudioRecords
10027 for (const auto &track : mActiveTracks) {
10028 track->logEndInterval();
10029 track->logBeginInterval(pathSourcesAsString);
10030 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010031 // Force meteadata update after a route change
10032 mActiveTracks.setHasChanged();
10033
Eric Laurent1c333e22014-05-20 10:48:17 -070010034 return status;
10035}
10036
Andy Hungee58e4a2023-07-07 13:47:37 -070010037status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010038{
10039 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010040
jiabinc52b1ff2019-10-31 17:20:42 -070010041 mPatch = audio_patch{};
10042 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010043
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010044 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010045 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10046 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010047 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010048 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010049 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010050 // Force meteadata update after a route change
10051 mActiveTracks.setHasChanged();
10052
Eric Laurent1c333e22014-05-20 10:48:17 -070010053 return status;
10054}
10055
Andy Hungee58e4a2023-07-07 13:47:37 -070010056void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010057{
Andy Hung972bec12023-08-31 16:13:39 -070010058 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010059 mOutDevices = outDevices;
10060 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10061 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010062 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010063 }
10064}
10065
Andy Hungee58e4a2023-07-07 13:47:37 -070010066int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010067{
10068 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010069 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010070 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010071 int32_t oldestFront = mRsmpInRear;
10072 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010073 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010074 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010075 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010076 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010077 if (filled > maxFilled) {
10078 oldestFront = front;
10079 maxFilled = filled;
10080 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010081 }
Andy Hung920f6572022-10-06 12:09:49 -070010082 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010083 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10084 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010085 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010086}
10087
Andy Hungee58e4a2023-07-07 13:47:37 -070010088void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010089{
10090 if (offset == 0) {
10091 return;
10092 }
10093 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010094 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010095 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010096 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010097 }
10098}
10099
Andy Hungee58e4a2023-07-07 13:47:37 -070010100void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010101{
10102 // This is the formula for calculating the temporary buffer size.
10103 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10104 // 1 full output buffer, regardless of the alignment of the available input.
10105 // The value is somewhat arbitrary, and could probably be even larger.
10106 // A larger value should allow more old data to be read after a track calls start(),
10107 // without increasing latency.
10108 //
10109 // Note this is independent of the maximum downsampling ratio permitted for capture.
10110 size_t minRsmpInFrames = mFrameCount * 7;
10111
10112 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10113 // capture history available to another client using the same session ID:
10114 // dimension the resampler input buffer accordingly.
10115
10116 // Get oldest client read position: getOldestFront_l() must be called before altering
10117 // mRsmpInRear, or mRsmpInFrames
10118 int32_t previousFront = getOldestFront_l();
10119 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10120 int32_t previousRear = mRsmpInRear;
10121 mRsmpInRear = 0;
10122
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010123 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010124 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010125 "resizeInputBuffer_l() called with invalid max shared history %d",
10126 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010127 if (maxSharedAudioHistoryMs != 0) {
10128 // resizeInputBuffer_l should never be called with a non zero shared history if the
10129 // buffer was not already allocated
10130 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10131 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10132 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10133 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010134 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010135 return;
10136 }
10137 mRsmpInFrames = rsmpInFrames;
10138 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010139 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010140 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10141 // initialized
10142 if (mRsmpInFrames < minRsmpInFrames) {
10143 mRsmpInFrames = minRsmpInFrames;
10144 }
10145 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10146
10147 // TODO optimize audio capture buffer sizes ...
10148 // Here we calculate the size of the sliding buffer used as a source
10149 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10150 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10151 // be better to have it derived from the pipe depth in the long term.
10152 // The current value is higher than necessary. However it should not add to latency.
10153
10154 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10155 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10156
10157 void *rsmpInBuffer;
10158 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10159 // if posix_memalign fails, will segv here.
10160 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10161
10162 // Copy audio history if any from old buffer before freeing it
10163 if (previousRear != 0) {
10164 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10165 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10166
10167 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10168 previousFront &= previousRsmpInFramesP2 - 1;
10169 size_t part1 = previousRsmpInFramesP2 - previousFront;
10170 if (part1 > (size_t) unread) {
10171 part1 = unread;
10172 }
10173 if (part1 != 0) {
10174 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10175 part1 * mFrameSize);
10176 mRsmpInRear = part1;
10177 part1 = unread - part1;
10178 if (part1 != 0) {
10179 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10180 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10181 mRsmpInRear += part1;
10182 }
10183 }
10184 // Update front for all clients according to new rear
10185 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10186 } else {
10187 mRsmpInRear = 0;
10188 }
10189 free(mRsmpInBuffer);
10190 mRsmpInBuffer = rsmpInBuffer;
10191}
10192
Andy Hungee58e4a2023-07-07 13:47:37 -070010193void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010194{
Andy Hung972bec12023-08-31 16:13:39 -070010195 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010196 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010197 if (record->getSource()) {
10198 mSource = record->getSource();
10199 }
Eric Laurent83b88082014-06-20 18:31:16 -070010200}
10201
Andy Hungee58e4a2023-07-07 13:47:37 -070010202void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010203{
Andy Hung972bec12023-08-31 16:13:39 -070010204 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010205 if (mSource == record->getSource()) {
10206 mSource = mInput;
10207 }
Eric Laurent83b88082014-06-20 18:31:16 -070010208 destroyTrack_l(record);
10209}
10210
Andy Hungee58e4a2023-07-07 13:47:37 -070010211void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010212{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010213 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010214 config->role = AUDIO_PORT_ROLE_SINK;
10215 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10216 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010217 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10218 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10219 config->flags.input = mInput->flags;
10220 }
Eric Laurent83b88082014-06-20 18:31:16 -070010221}
Eric Laurent1c333e22014-05-20 10:48:17 -070010222
Eric Laurent6acd1d42017-01-04 14:23:29 -080010223// ----------------------------------------------------------------------------
10224// Mmap
10225// ----------------------------------------------------------------------------
10226
Andy Hung7aa7d102023-07-07 15:58:48 -070010227// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10228// MmapPlaybackThread or MmapCaptureThread instance.
10229class MmapThreadHandle : public MmapStreamInterface {
10230public:
10231 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10232 ~MmapThreadHandle() override;
10233
10234 // MmapStreamInterface virtuals
10235 status_t createMmapBuffer(int32_t minSizeFrames,
10236 struct audio_mmap_buffer_info* info) final;
10237 status_t getMmapPosition(struct audio_mmap_position* position) final;
10238 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10239 status_t start(const AudioClient& client,
10240 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10241 status_t stop(audio_port_handle_t handle) final;
10242 status_t standby() final;
10243 status_t reportData(const void* buffer, size_t frameCount) final;
10244private:
10245 const sp<IAfMmapThread> mThread;
10246};
10247
10248/* static */
10249sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10250 const sp<IAfMmapThread>& mmapThread) {
10251 return sp<MmapThreadHandle>::make(mmapThread);
10252}
10253
10254MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255 : mThread(thread)
10256{
Phil Burk9fabbf82017-08-03 12:02:00 -070010257 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258}
10259
Andy Hung7aa7d102023-07-07 15:58:48 -070010260// MmapStreamInterface could be directly implemented by MmapThread excepting this
10261// special handling on adapter dtor.
10262MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263{
Phil Burk9fabbf82017-08-03 12:02:00 -070010264 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265}
10266
Andy Hung7aa7d102023-07-07 15:58:48 -070010267status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010268 struct audio_mmap_buffer_info *info)
10269{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010270 return mThread->createMmapBuffer(minSizeFrames, info);
10271}
10272
Andy Hung7aa7d102023-07-07 15:58:48 -070010273status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010274{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010275 return mThread->getMmapPosition(position);
10276}
10277
Andy Hung7aa7d102023-07-07 15:58:48 -070010278status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010279 int64_t *timeNanos) {
10280 return mThread->getExternalPosition(position, timeNanos);
10281}
10282
Andy Hung7aa7d102023-07-07 15:58:48 -070010283status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010284 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285{
jiabind1f1cb62020-03-24 11:57:57 -070010286 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010287}
10288
Andy Hung7aa7d102023-07-07 15:58:48 -070010289status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010290{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 return mThread->stop(handle);
10292}
10293
Andy Hung7aa7d102023-07-07 15:58:48 -070010294status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010295{
Eric Laurent18b57012017-02-13 16:23:52 -080010296 return mThread->standby();
10297}
10298
Andy Hung7aa7d102023-07-07 15:58:48 -070010299status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10300{
jiabinfc791ee2023-02-15 19:43:40 +000010301 return mThread->reportData(buffer, frameCount);
10302}
10303
Eric Laurent6acd1d42017-01-04 14:23:29 -080010304
Andy Hungee58e4a2023-07-07 13:47:37 -070010305MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010306 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010307 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010308 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010309 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010310 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010311 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010312 mActiveTracks(&this->mLocalLog),
10313 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10314 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010315{
Eric Laurent18b57012017-02-13 16:23:52 -080010316 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010317 readHalParameters_l();
10318}
10319
Andy Hungee58e4a2023-07-07 13:47:37 -070010320void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010321{
10322 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10323}
10324
Andy Hungee58e4a2023-07-07 13:47:37 -070010325void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010326{
Andy Hung8d31fd22023-06-26 19:20:57 -070010327 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010328 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010329 {
Andy Hung972bec12023-08-31 16:13:39 -070010330 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010331 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010332 activeTracks.add(t);
10333 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010334 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010335 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010336 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337 stop(t->portId());
10338 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010339 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010341 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010343 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344 }
10345}
10346
10347
Andy Hung8d672e02023-09-15 18:19:28 -070010348void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349 audio_stream_type_t streamType __unused,
10350 audio_session_t sessionId,
10351 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010352 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 audio_port_handle_t portId)
10354{
10355 mAttr = *attr;
10356 mSessionId = sessionId;
10357 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010358 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010359 mPortId = portId;
10360}
10361
Andy Hungee58e4a2023-07-07 13:47:37 -070010362status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010363 struct audio_mmap_buffer_info *info)
10364{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010365 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010366 if (mHalStream == 0) {
10367 return NO_INIT;
10368 }
Eric Laurent18b57012017-02-13 16:23:52 -080010369 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370 return mHalStream->createMmapBuffer(minSizeFrames, info);
10371}
10372
Andy Hungee58e4a2023-07-07 13:47:37 -070010373status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010375 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 if (mHalStream == 0) {
10377 return NO_INIT;
10378 }
10379 return mHalStream->getMmapPosition(position);
10380}
10381
Andy Hungee58e4a2023-07-07 13:47:37 -070010382status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010383{
Eric Laurentdda206a2022-07-08 17:28:35 +020010384 // The HAL must receive track metadata before starting the stream
10385 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010386 status_t ret = mHalStream->start();
10387 if (ret != NO_ERROR) {
10388 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10389 return ret;
10390 }
Andy Hungcf10d742020-04-28 15:38:24 -070010391 if (mStandby) {
10392 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010393 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010394 mStandby = false;
10395 }
Eric Laurent331679c2018-04-16 17:03:16 -070010396 return NO_ERROR;
10397}
10398
Andy Hungee58e4a2023-07-07 13:47:37 -070010399status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010400 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401 audio_port_handle_t *handle)
10402{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010403 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010404 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010405 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406 if (mHalStream == 0) {
10407 return NO_INIT;
10408 }
10409
10410 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411
Eric Laurentdda206a2022-07-08 17:28:35 +020010412 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010413 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010414 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010415 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010416 }
10417
10418 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10419
10420 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010421 AttributionSourceState adjAttributionSource;
10422 if (!com::android::media::audio::audioserver_permissions()) {
10423 adjAttributionSource = afutils::checkAttributionSourcePackage(
10424 client.attributionSource);
10425 } else {
10426 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10427 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10428 client.attributionSource,
10429 mAfThreadCallback->getPermissionProvider()
10430 );
10431 if (!validatedRes.has_value()) {
10432 ALOGE("MMAP client package validation fail: %s",
10433 validatedRes.error().toString8().c_str());
10434 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10435 }
10436 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10437 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010438
Andy Hung3f49ebb2023-09-19 14:48:41 -070010439 const auto localSessionId = mSessionId;
10440 auto localAttr = mAttr;
Andy Hung6b137d12024-08-27 22:35:17 +000010441 float volume = 0.0f;
Eric Laurenta54f1282017-07-01 19:39:32 -070010442 if (isOutput()) {
10443 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10444 config.sample_rate = mSampleRate;
10445 config.channel_mask = mChannelMask;
10446 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010447 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010448 audio_output_flags_t flags =
10449 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010450 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010451 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010452 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010453 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010454 mutex().unlock();
10455 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10456 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010457 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010458 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010459 &config,
10460 flags,
10461 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010462 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010463 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010464 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +000010465 &isBitPerfect,
10466 &volume);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010467 mutex().lock();
10468 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010469 ALOGD_IF(!secondaryOutputs.empty(),
10470 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010471 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010472 audio_config_base_t config;
10473 config.sample_rate = mSampleRate;
10474 config.channel_mask = mChannelMask;
10475 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010476 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010477 mutex().unlock();
10478 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010479 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010480 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010481 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010482 &config,
10483 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10484 &deviceId,
10485 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010486 mutex().lock();
10487 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010488 }
10489 // APM should not chose a different input or output stream for the same set of attributes
10490 // and audo configuration
10491 if (ret != NO_ERROR || io != mId) {
10492 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10493 __FUNCTION__, ret, io, mId);
10494 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 }
10496
10497 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010498 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010499 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010500 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501 } else {
jiabin09609032022-06-15 19:26:01 +000010502 {
10503 // Add the track record before starting input so that the silent status for the
10504 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010505 setClientSilencedState_l(portId, false /*silenced*/);
10506 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010507 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010508 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010509 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010510 }
10511
10512 // abort if start is rejected by audio policy manager
10513 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010514 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010515 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010516 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010517 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010518 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010519 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010520 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521 }
Andy Hungc5007f82023-08-29 14:26:09 -070010522 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010523 } else {
10524 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010525 }
jiabin09609032022-06-15 19:26:01 +000010526 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010527 return PERMISSION_DENIED;
10528 }
10529
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010530 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010531 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10532 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010533 mChannelMask, mSessionId, isOutput(),
10534 client.attributionSource,
Andy Hung6b137d12024-08-27 22:35:17 +000010535 IPCThreadState::self()->getCallingPid(), portId,
10536 volume);
jiabin09609032022-06-15 19:26:01 +000010537 if (!isOutput()) {
10538 track->setSilenced_l(isClientSilenced_l(portId));
10539 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010540
Eric Laurent4eb58f12018-12-07 16:41:02 -080010541 if (isOutput()) {
10542 // force volume update when a new track is added
10543 mHalVolFloat = -1.0f;
10544 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010545 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010546 if (t->isSilenced_l()
10547 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010548 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010549 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010550 }
10551 }
10552
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010554 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010556 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010557 chain->incTrackCnt();
10558 chain->incActiveTrackCnt();
10559 }
10560
Andy Hungc2b11cb2020-04-22 09:04:01 -070010561 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010562 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010563
10564 if (mActiveTracks.size() == 1) {
10565 ret = exitStandby_l();
10566 }
10567
Eric Laurent6acd1d42017-01-04 14:23:29 -080010568 broadcast_l();
10569
Eric Laurentdda206a2022-07-08 17:28:35 +020010570 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010571
Eric Laurentdda206a2022-07-08 17:28:35 +020010572 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573}
10574
Andy Hungee58e4a2023-07-07 13:47:37 -070010575status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010578 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010579
10580 if (mHalStream == 0) {
10581 return NO_INIT;
10582 }
10583
Eric Laurenta54f1282017-07-01 19:39:32 -070010584 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010585 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010586 return NO_ERROR;
10587 }
10588
Andy Hung8d31fd22023-06-26 19:20:57 -070010589 sp<IAfMmapTrack> track;
10590 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010591 if (handle == t->portId()) {
10592 track = t;
10593 break;
10594 }
10595 }
10596 if (track == 0) {
10597 return BAD_VALUE;
10598 }
10599
10600 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010601 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602
Andy Hungc5007f82023-08-29 14:26:09 -070010603 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010604 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010605 AudioSystem::stopOutput(track->portId());
10606 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010608 AudioSystem::stopInput(track->portId());
10609 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010610 }
Andy Hungc5007f82023-08-29 14:26:09 -070010611 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010612
Andy Hung116bc262023-06-20 18:56:17 -070010613 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010614 if (chain != 0) {
10615 chain->decActiveTrackCnt();
10616 chain->decTrackCnt();
10617 }
10618
Eric Laurentdda206a2022-07-08 17:28:35 +020010619 if (mActiveTracks.isEmpty()) {
10620 mHalStream->stop();
10621 }
10622
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623 broadcast_l();
10624
Eric Laurent6acd1d42017-01-04 14:23:29 -080010625 return NO_ERROR;
10626}
10627
Andy Hungee58e4a2023-07-07 13:47:37 -070010628status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010629NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010630{
10631 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010632 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010633
10634 if (mHalStream == 0) {
10635 return NO_INIT;
10636 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010637 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010638 return INVALID_OPERATION;
10639 }
10640 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010641 if (!mStandby) {
10642 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010643 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010644 mStandby = true;
10645 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010646 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010647 return NO_ERROR;
10648}
10649
Andy Hungee58e4a2023-07-07 13:47:37 -070010650status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010651 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10652 return INVALID_OPERATION;
10653}
10654
Andy Hungee58e4a2023-07-07 13:47:37 -070010655void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010656{
10657 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10658 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10659 mFormat = mHALFormat;
10660 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10661 result = mHalStream->getFrameSize(&mFrameSize);
10662 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010663 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10664 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010665 result = mHalStream->getBufferSize(&mBufferSize);
10666 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10667 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010668
Andy Hungcf10d742020-04-28 15:38:24 -070010669 // TODO: make a readHalParameters call?
10670 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010671 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010672 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010673 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10674 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10675 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10676 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10677 /*
10678 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10679 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10680 (int32_t)mHapticChannelMask)
10681 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10682 (int32_t)mHapticChannelCount)
10683 */
10684 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010685 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010686 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10687 (int32_t)mFrameCount) // sic - added HAL
10688 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010689}
10690
Andy Hungee58e4a2023-07-07 13:47:37 -070010691bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692{
Andy Hungab65b182023-09-06 19:41:47 -070010693 {
10694 audio_utils::unique_lock _l(mutex());
10695 checkSilentMode_l();
10696 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697
10698 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10699
10700 while (!exitPending())
10701 {
Andy Hung116bc262023-06-20 18:56:17 -070010702 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010703
Andy Hung13850be2019-03-14 11:33:09 -070010704 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010705 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010706
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 if (mSignalPending) {
10708 // A signal was raised while we were unlocked
10709 mSignalPending = false;
10710 } else {
10711 if (mConfigEvents.isEmpty()) {
10712 // we're about to wait, flush the binder command buffer
10713 IPCThreadState::self()->flushCommands();
10714
10715 if (exitPending()) {
10716 break;
10717 }
10718
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010720 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010721 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010722 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010723
10724 checkSilentMode_l();
10725
10726 continue;
10727 }
10728 }
10729
10730 processConfigEvents_l();
10731
10732 processVolume_l();
10733
10734 checkInvalidTracks_l();
10735
Andy Hungab65b182023-09-06 19:41:47 -070010736 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737
Kevin Rocard069c2712018-03-29 19:09:14 -070010738 updateMetadata_l();
10739
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010741 } // release Thread lock
10742
Eric Laurent6acd1d42017-01-04 14:23:29 -080010743 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010744 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745 }
Andy Hung13850be2019-03-14 11:33:09 -070010746
10747 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010748 unlockEffectChains(effectChains);
10749 // Effect chains will be actually deleted here if they were removed from
10750 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010751 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010752 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010753 mThreadloopExecutor.process(); // process any remaining deferred actions.
10754 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010755
10756 threadLoop_exit();
10757
10758 if (!mStandby) {
10759 threadLoop_standby();
10760 mStandby = true;
10761 }
10762
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763 ALOGV("Thread %p type %d exiting", this, mType);
10764 return false;
10765}
10766
Andy Hungc5007f82023-08-29 14:26:09 -070010767// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010768bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010769 status_t& status)
10770{
10771 AudioParameter param = AudioParameter(keyValuePair);
10772 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010773 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010775 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010777 if (sendToHal) {
10778 status = mHalStream->setParameters(keyValuePair);
10779 } else {
10780 status = NO_ERROR;
10781 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010782
10783 return false;
10784}
10785
Andy Hungee58e4a2023-07-07 13:47:37 -070010786String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787{
Andy Hung972bec12023-08-31 16:13:39 -070010788 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010789 String8 out_s8;
10790 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10791 return out_s8;
10792 }
Andy Hung920f6572022-10-06 12:09:49 -070010793 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010794}
10795
Andy Hungab65b182023-09-06 19:41:47 -070010796void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010797 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010798 sp<AudioIoDescriptor> desc;
10799 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010800 switch (event) {
10801 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010802 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010803 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010804 isInput = true;
10805 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010806 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010807 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010808 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010809 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10810 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010811 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010812 case AUDIO_INPUT_CLOSED:
10813 case AUDIO_OUTPUT_CLOSED:
10814 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010815 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010816 break;
10817 }
Andy Hungab65b182023-09-06 19:41:47 -070010818 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819}
10820
Andy Hungee58e4a2023-07-07 13:47:37 -070010821status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010822 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010823NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824{
10825 status_t status = NO_ERROR;
10826
10827 // store new device and send to effects
10828 audio_devices_t type = AUDIO_DEVICE_NONE;
10829 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010830 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10831 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10832 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833 if (isOutput()) {
10834 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010835 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10836 && !mAudioHwDev->supportsAudioPatches(),
10837 "Enumerated device type(%#x) must not be used "
10838 "as it does not support audio patches",
10839 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010840 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010841 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10842 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010843 }
10844 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010845 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010846 } else {
10847 type = patch->sources[0].ext.device.type;
10848 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010849 numDevices = mPatch.num_sources;
10850 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010851 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010852 }
10853
10854 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010855 if (isOutput()) {
10856 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10857 } else {
10858 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10859 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010860 }
10861
jiabinc52b1ff2019-10-31 17:20:42 -070010862 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010863 // store new source and send to effects
10864 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10865 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10866 for (size_t i = 0; i < mEffectChains.size(); i++) {
10867 mEffectChains[i]->setAudioSource_l(mAudioSource);
10868 }
10869 }
10870 }
10871
jiabin78b86f22024-02-22 00:39:29 +000010872 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10873 // okay to notify the client earlier before the new patch creation.
10874 if (mDeviceId != deviceId) {
10875 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10876 // The aaudioservice handle the routing changed event asynchronously. In that case,
10877 // it is safe to hold the lock here.
10878 callback->onRoutingChanged(deviceId);
10879 }
10880 }
10881
Eric Laurent6acd1d42017-01-04 14:23:29 -080010882 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010883 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10884 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010886 audio_port_config port;
10887 std::optional<audio_source_t> source;
10888 if (isOutput()) {
10889 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010890 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010891 port = patch->sources[0];
10892 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010893 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010894 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010895 *handle = AUDIO_PATCH_HANDLE_NONE;
10896 }
10897
jiabinc52b1ff2019-10-31 17:20:42 -070010898 if (numDevices == 0 || mDeviceId != deviceId) {
10899 if (isOutput()) {
10900 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10901 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010902 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010903 } else {
10904 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10905 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10906 }
jiabinc52b1ff2019-10-31 17:20:42 -070010907 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010908 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010909 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010910 // Force meteadata update after a route change
10911 mActiveTracks.setHasChanged();
10912
Eric Laurent6acd1d42017-01-04 14:23:29 -080010913 return status;
10914}
10915
Andy Hungee58e4a2023-07-07 13:47:37 -070010916status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010917{
10918 status_t status = NO_ERROR;
10919
jiabinc52b1ff2019-10-31 17:20:42 -070010920 mPatch = audio_patch{};
10921 mOutDeviceTypeAddrs.clear();
10922 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923
10924 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10925 supportsAudioPatches : false;
10926
10927 if (supportsAudioPatches) {
10928 status = mHalDevice->releaseAudioPatch(handle);
10929 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010930 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010931 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010932 // Force meteadata update after a route change
10933 mActiveTracks.setHasChanged();
10934
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935 return status;
10936}
10937
Andy Hungee58e4a2023-07-07 13:47:37 -070010938void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010939NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010940{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010941 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942 if (isOutput()) {
10943 config->role = AUDIO_PORT_ROLE_SOURCE;
10944 config->ext.mix.hw_module = mAudioHwDev->handle();
10945 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10946 } else {
10947 config->role = AUDIO_PORT_ROLE_SINK;
10948 config->ext.mix.hw_module = mAudioHwDev->handle();
10949 config->ext.mix.usecase.source = mAudioSource;
10950 }
10951}
10952
Andy Hungee58e4a2023-07-07 13:47:37 -070010953status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954{
10955 audio_session_t session = chain->sessionId();
10956
10957 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10958 // Attach all tracks with same session ID to this chain.
10959 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010960 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010961 if (session == track->sessionId()) {
10962 chain->incTrackCnt();
10963 chain->incActiveTrackCnt();
10964 }
10965 }
10966
10967 chain->setThread(this);
10968 chain->setInBuffer(nullptr);
10969 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010970 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010971
10972 mEffectChains.add(chain);
10973 checkSuspendOnAddEffectChain_l(chain);
10974 return NO_ERROR;
10975}
10976
Andy Hungee58e4a2023-07-07 13:47:37 -070010977size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010978{
10979 audio_session_t session = chain->sessionId();
10980
10981 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10982
10983 for (size_t i = 0; i < mEffectChains.size(); i++) {
10984 if (chain == mEffectChains[i]) {
10985 mEffectChains.removeAt(i);
10986 // detach all active tracks from the chain
10987 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010988 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010989 if (session == track->sessionId()) {
10990 chain->decActiveTrackCnt();
10991 chain->decTrackCnt();
10992 }
10993 }
10994 break;
10995 }
10996 }
10997 return mEffectChains.size();
10998}
10999
Andy Hungee58e4a2023-07-07 13:47:37 -070011000void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011001{
11002 mHalStream->standby();
11003}
11004
Andy Hungee58e4a2023-07-07 13:47:37 -070011005void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011006{
Phil Burk7dce7282017-09-27 13:51:41 -070011007 // Do not call callback->onTearDown() because it is redundant for thread exit
11008 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080011009}
11010
Andy Hungee58e4a2023-07-07 13:47:37 -070011011status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011012{
11013 return BAD_VALUE;
11014}
11015
Andy Hungee58e4a2023-07-07 13:47:37 -070011016bool MmapThread::isValidSyncEvent(
11017 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011018{
11019 return false;
11020}
11021
Andy Hungee58e4a2023-07-07 13:47:37 -070011022status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080011023 const effect_descriptor_t *desc, audio_session_t sessionId)
11024{
11025 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080011026 if (audio_is_global_session(sessionId)) {
11027 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080011028 desc->name, mThreadName);
11029 return BAD_VALUE;
11030 }
11031
11032 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11033 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11034 desc->name);
11035 return BAD_VALUE;
11036 }
11037 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011038 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11039 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011040 return BAD_VALUE;
11041 }
11042
11043 // Only allow effects without processing load or latency
11044 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11045 return BAD_VALUE;
11046 }
11047
Andy Hung116bc262023-06-20 18:56:17 -070011048 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011049 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11050 return BAD_VALUE;
11051 }
11052
Eric Laurent6acd1d42017-01-04 14:23:29 -080011053 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011054}
11055
Andy Hungee58e4a2023-07-07 13:47:37 -070011056void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011057{
Andy Hung8d31fd22023-06-26 19:20:57 -070011058 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011060 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11061 // The aaudioservice handle the routing changed event asynchronously. In that case,
11062 // it is safe to hold the lock here.
11063 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
11064 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011065 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11066 mNoCallbackWarningCount++;
11067 }
11068 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011069 }
11070 }
11071}
11072
Andy Hungee58e4a2023-07-07 13:47:37 -070011073void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011074{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011075 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11076 mAttr.content_type, mAttr.usage, mAttr.source);
11077 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011078 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011079 dprintf(fd, " No active clients\n");
11080 }
11081}
11082
Andy Hungee58e4a2023-07-07 13:47:37 -070011083void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011084{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011085 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011086 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011087 dprintf(fd, " %zu Tracks\n", numtracks);
11088 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011089 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011090 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011091 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011093 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011094 result.append(prefix);
11095 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011096 }
11097 } else {
11098 dprintf(fd, "\n");
11099 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011100 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011101}
11102
Andy Hungee58e4a2023-07-07 13:47:37 -070011103/* static */
11104sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011105 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011106 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011107 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011108}
11109
11110MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011111 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011112 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011113 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011114 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011115 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011116{
11117 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11118 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011119 mMasterVolume = afThreadCallback->masterVolume_l();
11120 mMasterMute = afThreadCallback->masterMute_l();
Andy Hung6b137d12024-08-27 22:35:17 +000011121 if (!audioserver_flags::portid_volume_management()) {
11122 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11123 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11124 mStreamTypes[stream].volume = 0.0f;
11125 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11126 }
11127 // Audio patch and call assistant volume are always max
11128 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11129 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11130 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11131 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011132 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011133 if (mAudioHwDev) {
11134 if (mAudioHwDev->canSetMasterVolume()) {
11135 mMasterVolume = 1.0;
11136 }
11137
11138 if (mAudioHwDev->canSetMasterMute()) {
11139 mMasterMute = false;
11140 }
11141 }
11142}
11143
Andy Hungee58e4a2023-07-07 13:47:37 -070011144void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011145 audio_stream_type_t streamType,
11146 audio_session_t sessionId,
11147 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011148 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011149 audio_port_handle_t portId)
11150{
Andy Hung8d672e02023-09-15 18:19:28 -070011151 audio_utils::lock_guard l(mutex());
11152 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011153 mStreamType = streamType;
11154}
11155
Andy Hungee58e4a2023-07-07 13:47:37 -070011156AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011157{
Andy Hung972bec12023-08-31 16:13:39 -070011158 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011159 AudioStreamOut *output = mOutput;
11160 mOutput = NULL;
11161 return output;
11162}
11163
Andy Hungee58e4a2023-07-07 13:47:37 -070011164void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011165{
Andy Hung972bec12023-08-31 16:13:39 -070011166 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011167 // Don't apply master volume in SW if our HAL can do it for us.
11168 if (mAudioHwDev &&
11169 mAudioHwDev->canSetMasterVolume()) {
11170 mMasterVolume = 1.0;
11171 } else {
11172 mMasterVolume = value;
11173 }
11174}
11175
Andy Hungee58e4a2023-07-07 13:47:37 -070011176void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011177{
Andy Hung972bec12023-08-31 16:13:39 -070011178 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011179 // Don't apply master mute in SW if our HAL can do it for us.
11180 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11181 mMasterMute = false;
11182 } else {
11183 mMasterMute = muted;
11184 }
11185}
11186
Andy Hungee58e4a2023-07-07 13:47:37 -070011187void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011188{
Andy Hung972bec12023-08-31 16:13:39 -070011189 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011190 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011191 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011192 broadcast_l();
11193 }
11194}
11195
Andy Hungee58e4a2023-07-07 13:47:37 -070011196float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011197{
Andy Hung972bec12023-08-31 16:13:39 -070011198 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011199 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011200}
11201
Andy Hungee58e4a2023-07-07 13:47:37 -070011202void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011203{
Andy Hung972bec12023-08-31 16:13:39 -070011204 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011205 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011206 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011207 broadcast_l();
11208 }
11209}
11210
Andy Hung6b137d12024-08-27 22:35:17 +000011211status_t MmapPlaybackThread::setPortsVolume(
11212 const std::vector<audio_port_handle_t>& portIds, float volume) {
11213 audio_utils::lock_guard _l(mutex());
11214 for (const auto& portId : portIds) {
11215 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11216 if (portId == track->portId()) {
11217 track->setPortVolume(volume);
11218 break;
11219 }
11220 }
11221 }
11222 broadcast_l();
11223 return NO_ERROR;
11224}
11225
Andy Hungee58e4a2023-07-07 13:47:37 -070011226void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011227{
Andy Hung972bec12023-08-31 16:13:39 -070011228 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011229 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011230 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011231 track->invalidate();
11232 }
11233 broadcast_l();
11234 }
11235}
11236
Andy Hungee58e4a2023-07-07 13:47:37 -070011237void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011238{
Andy Hung972bec12023-08-31 16:13:39 -070011239 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011240 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011241 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011242 if (portIds.find(track->portId()) != portIds.end()) {
11243 track->invalidate();
11244 trackMatch = true;
11245 portIds.erase(track->portId());
11246 }
11247 if (portIds.empty()) {
11248 break;
11249 }
11250 }
11251 if (trackMatch) {
11252 broadcast_l();
11253 }
11254}
11255
Andy Hungee58e4a2023-07-07 13:47:37 -070011256void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011257NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011258{
Andy Hung6b137d12024-08-27 22:35:17 +000011259 float volume = 0;
11260 if (!audioserver_flags::portid_volume_management()) {
11261 if (mMasterMute || streamMuted_l()) {
11262 volume = 0;
11263 } else {
11264 volume = mMasterVolume * streamVolume_l();
11265 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011266 } else {
Andy Hung6b137d12024-08-27 22:35:17 +000011267 if (mMasterMute) {
11268 volume = 0;
11269 } else {
11270 // All mmap tracks are declared with the same audio attributes to the audio policy
11271 // manager. Hence, they follow the same routing / volume group. Any change of volume
11272 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11273 size_t numtracks = mActiveTracks.size();
11274 if (numtracks) {
11275 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11276 }
11277 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011278 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011279 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011280 // Convert volumes from float to 8.24
11281 uint32_t vol = (uint32_t)(volume * (1 << 24));
11282
11283 // Delegate volume control to effect in track effect chain if needed
11284 // only one effect chain can be present on DirectOutputThread, so if
11285 // there is one, the track is connected to it
11286 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011287 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011288 volume = (float)vol / (1 << 24);
11289 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011290 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011291 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11292 mHalVolFloat = volume; // HW volume control worked, so update value.
11293 mNoCallbackWarningCount = 0;
11294 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011295 sp<MmapStreamCallback> callback = mCallback.promote();
11296 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011297 mHalVolFloat = volume; // SW volume control worked, so update value.
11298 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011299 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011300 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011301 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011302 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011303 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11304 ALOGW("Could not set MMAP stream volume: no volume callback!");
11305 mNoCallbackWarningCount++;
11306 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011307 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011308 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011309 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011310 track->setMetadataHasChanged();
Andy Hung6b137d12024-08-27 22:35:17 +000011311 if (!audioserver_flags::portid_volume_management()) {
11312 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11313 /*muteState=*/{mMasterMute,
11314 streamVolume_l() == 0.f,
11315 streamMuted_l(),
11316 // TODO(b/241533526): adjust logic to include mute from AppOps
11317 false /*muteFromPlaybackRestricted*/,
11318 false /*muteFromClientVolume*/,
11319 false /*muteFromVolumeShaper*/});
11320 } else {
11321 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11322 /*muteState=*/{mMasterMute,
11323 track->getPortVolume() == 0.f,
11324 /* muteFromStreamMuted= */ false,
11325 // TODO(b/241533526): adjust logic to include mute from AppOps
11326 false /*muteFromPlaybackRestricted*/,
11327 false /*muteFromClientVolume*/,
11328 false /*muteFromVolumeShaper*/});
11329 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011330 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011331 }
11332}
11333
Andy Hungee58e4a2023-07-07 13:47:37 -070011334ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011335{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011336 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011337 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011338 }
11339 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011340 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011341 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011342 playback_track_metadata_v7_t trackMetadata;
11343 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011344 .usage = track->attributes().usage,
11345 .content_type = track->attributes().content_type,
11346 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011347 };
11348 trackMetadata.channel_mask = track->channelMask(),
11349 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11350 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011351 }
11352 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011353
11354 MetadataUpdate change;
11355 change.playbackMetadataUpdate = metadata.tracks;
11356 return change;
11357};
Kevin Rocard069c2712018-03-29 19:09:14 -070011358
Andy Hungee58e4a2023-07-07 13:47:37 -070011359void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011360{
11361 if (!mMasterMute) {
11362 char value[PROPERTY_VALUE_MAX];
11363 if (property_get("ro.audio.silent", value, "0") > 0) {
11364 char *endptr;
11365 unsigned long ul = strtoul(value, &endptr, 0);
11366 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011367 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011368 // The setprop command will not allow a property to be changed after
11369 // the first time it is set, so we don't have to worry about un-muting.
11370 setMasterMute_l(true);
11371 }
11372 }
11373 }
11374}
11375
Andy Hungee58e4a2023-07-07 13:47:37 -070011376void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011377{
11378 MmapThread::toAudioPortConfig(config);
11379 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11380 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11381 config->flags.output = mOutput->flags;
11382 }
11383}
11384
Andy Hungee58e4a2023-07-07 13:47:37 -070011385status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011386 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011387{
11388 if (mOutput == nullptr) {
11389 return NO_INIT;
11390 }
11391 struct timespec timestamp;
11392 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11393 if (status == NO_ERROR) {
11394 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11395 }
11396 return status;
11397}
11398
Andy Hungee58e4a2023-07-07 13:47:37 -070011399status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011400 // Send to MelProcessor for sound dose measurement.
11401 auto processor = mMelProcessor.load();
11402 if (processor) {
11403 processor->process(buffer, frameCount * mFrameSize);
11404 }
11405
jiabinfc791ee2023-02-15 19:43:40 +000011406 return NO_ERROR;
11407}
11408
Andy Hungc5007f82023-08-29 14:26:09 -070011409// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011410void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011411 const sp<audio_utils::MelProcessor>& processor)
11412{
11413 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011414 mMelProcessor.store(processor);
11415 if (processor) {
11416 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011417 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011418
11419 // no need to update output format for MMapPlaybackThread since it is
11420 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011421}
11422
Andy Hungc5007f82023-08-29 14:26:09 -070011423// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011424void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011425{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011426 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11427 auto melProcessor = mMelProcessor.load();
11428 if (melProcessor != nullptr) {
11429 melProcessor->pause();
11430 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011431}
11432
Andy Hungee58e4a2023-07-07 13:47:37 -070011433void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011434{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011435 MmapThread::dumpInternals_l(fd, args);
Andy Hung6b137d12024-08-27 22:35:17 +000011436 if (!audioserver_flags::portid_volume_management()) {
11437 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11438 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11439 } else {
11440 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11441 }
11442 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011443 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11444}
11445
Andy Hungee58e4a2023-07-07 13:47:37 -070011446/* static */
11447sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011448 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011449 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011450 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011451}
11452
11453MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011454 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011455 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011456 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011457 mInput(input)
11458{
11459 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11460 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11461}
11462
Andy Hungee58e4a2023-07-07 13:47:37 -070011463status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011464{
Phil Burkf054fc32018-12-06 09:45:59 -080011465 {
11466 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011467 if (mInput != nullptr && mInput->stream != nullptr) {
11468 mInput->stream->setGain(1.0f);
11469 }
11470 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011471 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011472}
11473
Andy Hungee58e4a2023-07-07 13:47:37 -070011474AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011475{
Andy Hung972bec12023-08-31 16:13:39 -070011476 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011477 AudioStreamIn *input = mInput;
11478 mInput = NULL;
11479 return input;
11480}
Kevin Rocard069c2712018-03-29 19:09:14 -070011481
Andy Hungee58e4a2023-07-07 13:47:37 -070011482void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011483{
11484 bool changed = false;
11485 bool silenced = false;
11486
11487 sp<MmapStreamCallback> callback = mCallback.promote();
11488 if (callback == 0) {
11489 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11490 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11491 mNoCallbackWarningCount++;
11492 }
11493 }
11494
11495 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11496 // track is silenced and unmute otherwise
11497 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11498 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11499 changed = true;
11500 silenced = mActiveTracks[i]->isSilenced_l();
11501 }
11502 }
11503
11504 if (changed) {
11505 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11506 }
11507}
11508
Andy Hungee58e4a2023-07-07 13:47:37 -070011509ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011510{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011511 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011512 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011513 }
11514 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011515 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011516 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011517 record_track_metadata_v7_t trackMetadata;
11518 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011519 .source = track->attributes().source,
11520 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011521 };
11522 trackMetadata.channel_mask = track->channelMask(),
11523 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11524 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011525 }
11526 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011527 MetadataUpdate change;
11528 change.recordMetadataUpdate = metadata.tracks;
11529 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011530}
11531
Andy Hungee58e4a2023-07-07 13:47:37 -070011532void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011533{
Andy Hung972bec12023-08-31 16:13:39 -070011534 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011535 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011536 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011537 mActiveTracks[i]->setSilenced_l(silenced);
11538 broadcast_l();
11539 }
11540 }
jiabin09609032022-06-15 19:26:01 +000011541 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011542}
11543
Andy Hungee58e4a2023-07-07 13:47:37 -070011544void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011545{
11546 MmapThread::toAudioPortConfig(config);
11547 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11548 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11549 config->flags.input = mInput->flags;
11550 }
11551}
11552
Andy Hungee58e4a2023-07-07 13:47:37 -070011553status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011554 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011555{
11556 if (mInput == nullptr) {
11557 return NO_INIT;
11558 }
11559 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11560}
11561
jiabinc658e452022-10-21 20:52:21 +000011562// ----------------------------------------------------------------------------
11563
Andy Hungee58e4a2023-07-07 13:47:37 -070011564/* static */
11565sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011566 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011567 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011568 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011569}
11570
Andy Hung583043b2023-07-17 17:05:00 -070011571BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011572 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011573 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011574
Andy Hungee58e4a2023-07-07 13:47:37 -070011575PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011576 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011577 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11578 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011579 float volumeLeft = 1.0f;
11580 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011581 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11582 bitPerfectTrack != nullptr) {
11583 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011584 mAudioMixer->setParameter(
11585 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11586 mAudioMixer->setParameter(
11587 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11588 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011589 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011590 mIsBitPerfect = true;
11591 } else {
11592 mIsBitPerfect = false;
11593 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11594 // active.
11595 for (const auto& track : mActiveTracks) {
11596 const int trackId = track->id();
11597 mAudioMixer->setParameter(
11598 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11599 }
11600 }
jiabin76d94692022-12-15 21:51:21 +000011601 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11602 mVolumeLeft = volumeLeft;
11603 mVolumeRight = volumeRight;
11604 setVolumeForOutput_l(volumeLeft, volumeRight);
11605 }
jiabinc658e452022-10-21 20:52:21 +000011606 return result;
11607}
11608
Andy Hungee58e4a2023-07-07 13:47:37 -070011609void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011610 MixerThread::threadLoop_mix();
11611 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11612}
11613
jiabin220eea12024-05-17 17:55:20 +000011614void BitPerfectThread::setTracksInternalMute(
11615 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11616 for (auto& track : mTracks) {
11617 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11618 track->setInternalMute(it->second);
11619 tracksInternalMute->erase(it);
11620 }
11621 }
11622}
11623
11624sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11625 if (com::android::media::audioserver::
11626 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11627 sp<IAfTrack> bitPerfectTrack = nullptr;
11628 bool allOtherTracksMuted = true;
11629 // Return the bit perfect track if all other tracks are muted
11630 for (const auto& track : mActiveTracks) {
11631 if (track->isBitPerfect()) {
11632 bitPerfectTrack = track;
11633 } else if (track->getFinalVolume() != 0.f) {
11634 allOtherTracksMuted = false;
11635 if (bitPerfectTrack != nullptr) {
11636 break;
11637 }
11638 }
11639 }
11640 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11641 } else {
11642 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11643 return mActiveTracks[0];
11644 }
11645 }
11646 return nullptr;
11647}
11648
Glenn Kasten63238ef2015-03-02 15:50:29 -080011649} // namespace android