blob: 078f0d20e692d008edd2f41f56d2651b8d802040 [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
Atneya Nairf94040f2024-10-07 16:00:49 -070030#include <afutils/FallibleLockGuard.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070031#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)
Eric Laurent81784c32012-11-19 14:55:58 -08001045{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001046 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1047 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1048
Atneya Nairf94040f2024-10-07 16:00:49 -07001049 {
1050 afutils::FallibleLockGuard l{mutex()};
1051 if (!l) {
1052 dprintf(fd, " Thread may be deadlocked\n");
1053 }
1054 dumpBase_l(fd, args);
1055 dumpInternals_l(fd, args);
1056 dumpTracks_l(fd, args);
1057 dumpEffectChains_l(fd, args);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001058 }
1059
1060 dprintf(fd, " Local log:\n");
Atneya Nairaa3afcb2024-10-08 16:36:19 -07001061 const auto logHeader = this->getLocalLogHeader();
1062 write(fd, logHeader.data(), logHeader.length());
Atneya Nair0423af92024-10-07 21:23:29 -07001063 mLocalLog.dump(fd, " " /* prefix */);
Andy Hungafc51db2022-04-08 17:33:40 -07001064
1065 // --all does the statistics
1066 bool dumpAll = false;
1067 for (const auto &arg : args) {
1068 if (arg == String16("--all")) {
1069 dumpAll = true;
1070 }
1071 }
1072 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001073 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001074 if (!sched.empty()) {
1075 (void)write(fd, sched.c_str(), sched.size());
1076 }
1077 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001078}
1079
Andy Hungee58e4a2023-07-07 13:47:37 -07001080void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001081{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001082 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001083 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001084 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001085 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001086 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1087 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001088 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001089 dprintf(fd, " Channel count: %u\n", mChannelCount);
1090 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001091 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001092 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1093 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001094 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001095 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001096 size_t numConfig = mConfigEvents.size();
1097 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001098 const size_t SIZE = 256;
1099 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001100 for (size_t i = 0; i < numConfig; i++) {
1101 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001102 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001103 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001104 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001105 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001106 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001107 }
Andy Hung293558a2017-03-21 12:19:20 -07001108 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001109 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001110 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001111 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001112 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001113 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001114
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001115 // Dump timestamp statistics for the Thread types that support it.
1116 if (mType == RECORD
1117 || mType == MIXER
1118 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001119 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001120 || mType == OFFLOAD
1121 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001122 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001123 dprintf(fd, " Timestamp corrected: %s\n",
1124 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001125 }
1126
Andy Hung446f4df2019-02-21 12:26:41 -08001127 if (mLastIoBeginNs > 0) { // MMAP may not set this
1128 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1129 isOutput() ? "write" : "read",
1130 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1131 }
1132
1133 if (mProcessTimeMs.getN() > 0) {
1134 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1135 }
1136
1137 if (mIoJitterMs.getN() > 0) {
1138 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1139 isOutput() ? "write" : "read",
1140 mIoJitterMs.toString().c_str());
1141 }
1142
Andy Hunge6c37112019-02-26 17:38:10 -08001143 if (mLatencyMs.getN() > 0) {
1144 dprintf(fd, " Threadloop %s latency stats: %s\n",
1145 isOutput() ? "write" : "read",
1146 mLatencyMs.toString().c_str());
1147 }
Robert Wu06db0a32021-08-10 19:05:34 +00001148
1149 if (mMonopipePipeDepthStats.getN() > 0) {
1150 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1151 isOutput() ? "write" : "read",
1152 mMonopipePipeDepthStats.toString().c_str());
1153 }
Eric Laurent81784c32012-11-19 14:55:58 -08001154}
1155
Andy Hungee58e4a2023-07-07 13:47:37 -07001156void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001157{
1158 const size_t SIZE = 256;
1159 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001160
Marco Nelissenb2208842014-02-07 14:00:50 -08001161 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001162 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001163 write(fd, buffer, strlen(buffer));
1164
Marco Nelissenb2208842014-02-07 14:00:50 -08001165 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001166 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001167 if (chain != 0) {
1168 chain->dump(fd, args);
1169 }
1170 }
1171}
1172
Andy Hungee58e4a2023-07-07 13:47:37 -07001173void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001174{
Andy Hung972bec12023-08-31 16:13:39 -07001175 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001176 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001177}
1178
Andy Hungee58e4a2023-07-07 13:47:37 -07001179String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001180{
1181 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001182 case MIXER:
1183 return String16("AudioMix");
1184 case DIRECT:
1185 return String16("AudioDirectOut");
1186 case DUPLICATING:
1187 return String16("AudioDup");
1188 case RECORD:
1189 return String16("AudioIn");
1190 case OFFLOAD:
1191 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001192 case MMAP_PLAYBACK:
1193 return String16("MmapPlayback");
1194 case MMAP_CAPTURE:
1195 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001196 case SPATIALIZER:
1197 return String16("AudioSpatial");
jiabin10b2fb82024-09-03 17:51:35 +00001198 case BIT_PERFECT:
1199 return String16("AudioBitPerfect");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001200 default:
1201 ALOG_ASSERT(false);
1202 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001203 }
1204}
1205
Andy Hungee58e4a2023-07-07 13:47:37 -07001206void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001207{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001208 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001209 if (mPowerManager != 0) {
1210 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001211 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001212 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1213 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001214 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001215 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001216 {} /* workSource */,
1217 {} /* historyTag */);
1218 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001219 mWakeLockToken = binder;
Andy Hung88a7afe2024-08-12 20:00:46 -07001220 if (media::psh_utils::AudioPowerManager::enabled()) {
1221 mThreadToken = media::psh_utils::createAudioThreadToken(
1222 getTid(), String8(getWakeLockTag()).c_str());
1223 }
Eric Laurent81784c32012-11-19 14:55:58 -08001224 }
Chris Ye6597d732020-02-28 22:38:25 -08001225 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001226 }
Wei Jia3f273d12015-11-24 09:06:49 -08001227
Andy Hung3f0c9022016-01-15 17:49:46 -08001228 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001229 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1230 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001231}
1232
Andy Hungee58e4a2023-07-07 13:47:37 -07001233void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001234{
Andy Hung972bec12023-08-31 16:13:39 -07001235 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001236 releaseWakeLock_l();
1237}
1238
Andy Hungee58e4a2023-07-07 13:47:37 -07001239void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001240{
Andy Hung3f0c9022016-01-15 17:49:46 -08001241 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001242 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001243 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001244 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001245 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001246 }
1247 mWakeLockToken.clear();
1248 }
Andy Hung88a7afe2024-08-12 20:00:46 -07001249 mThreadToken.reset();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001250}
1251
Andy Hungee58e4a2023-07-07 13:47:37 -07001252void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001253 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001254 // use checkService() to avoid blocking if power service is not up yet
1255 sp<IBinder> binder =
1256 defaultServiceManager()->checkService(String16("power"));
1257 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001258 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001259 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001260 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001261 binder->linkToDeath(mDeathRecipient);
1262 }
1263 }
1264}
1265
Andy Hungee58e4a2023-07-07 13:47:37 -07001266void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001267 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001268
1269#if !LOG_NDEBUG
1270 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001271 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001272 s << uid << " ";
1273 }
1274 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1275#endif
1276
Andy Hung438e7572015-12-14 15:51:17 -08001277 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1278 if (mSystemReady) {
1279 ALOGE("no wake lock to update, but system ready!");
1280 } else {
1281 ALOGW("no wake lock to update, system not ready yet");
1282 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001283 return;
1284 }
1285 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001286 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001287 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1288 mWakeLockToken, uidsAsInt);
1289 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001290 }
1291}
1292
Andy Hungee58e4a2023-07-07 13:47:37 -07001293void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001294{
Andy Hung972bec12023-08-31 16:13:39 -07001295 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001296 releaseWakeLock_l();
1297 mPowerManager.clear();
1298}
1299
Andy Hungee58e4a2023-07-07 13:47:37 -07001300void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001301 const DeviceDescriptorBaseVector& outDevices __unused)
1302{
1303 ALOGE("%s should only be called in RecordThread", __func__);
1304}
1305
Andy Hungee58e4a2023-07-07 13:47:37 -07001306void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001307{
1308 ALOGE("%s should only be called in RecordThread", __func__);
1309}
1310
Andy Hungee58e4a2023-07-07 13:47:37 -07001311void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001312{
1313 sp<ThreadBase> thread = mThread.promote();
1314 if (thread != 0) {
1315 thread->clearPowerManager();
1316 }
1317 ALOGW("power manager service died !!!");
1318}
1319
Andy Hungee58e4a2023-07-07 13:47:37 -07001320void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001321 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001322{
Andy Hung116bc262023-06-20 18:56:17 -07001323 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001324 if (chain != 0) {
1325 if (type != NULL) {
1326 chain->setEffectSuspended_l(type, suspend);
1327 } else {
1328 chain->setEffectSuspendedAll_l(suspend);
1329 }
1330 }
1331
1332 updateSuspendedSessions_l(type, suspend, sessionId);
1333}
1334
Andy Hungee58e4a2023-07-07 13:47:37 -07001335void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001336{
1337 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1338 if (index < 0) {
1339 return;
1340 }
1341
1342 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1343 mSuspendedSessions.valueAt(index);
1344
1345 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001346 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001347 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001348 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001349 chain->setEffectSuspendedAll_l(true);
1350 } else {
1351 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1352 desc->mType.timeLow);
1353 chain->setEffectSuspended_l(&desc->mType, true);
1354 }
1355 }
1356 }
1357}
1358
Andy Hungee58e4a2023-07-07 13:47:37 -07001359void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001360 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001361 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001362{
1363 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1364
1365 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1366
1367 if (suspend) {
1368 if (index >= 0) {
1369 sessionEffects = mSuspendedSessions.valueAt(index);
1370 } else {
1371 mSuspendedSessions.add(sessionId, sessionEffects);
1372 }
1373 } else {
1374 if (index < 0) {
1375 return;
1376 }
1377 sessionEffects = mSuspendedSessions.valueAt(index);
1378 }
1379
1380
Andy Hung116bc262023-06-20 18:56:17 -07001381 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001382 if (type != NULL) {
1383 key = type->timeLow;
1384 }
1385 index = sessionEffects.indexOfKey(key);
1386
1387 sp<SuspendedSessionDesc> desc;
1388 if (suspend) {
1389 if (index >= 0) {
1390 desc = sessionEffects.valueAt(index);
1391 } else {
1392 desc = new SuspendedSessionDesc();
1393 if (type != NULL) {
1394 desc->mType = *type;
1395 }
1396 sessionEffects.add(key, desc);
1397 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1398 }
1399 desc->mRefCount++;
1400 } else {
1401 if (index < 0) {
1402 return;
1403 }
1404 desc = sessionEffects.valueAt(index);
1405 if (--desc->mRefCount == 0) {
1406 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1407 sessionEffects.removeItemsAt(index);
1408 if (sessionEffects.isEmpty()) {
1409 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1410 sessionId);
1411 mSuspendedSessions.removeItem(sessionId);
1412 }
1413 }
1414 }
1415 if (!sessionEffects.isEmpty()) {
1416 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1417 }
1418}
1419
Andy Hungee58e4a2023-07-07 13:47:37 -07001420void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001421 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001422 bool threadLocked)
1423NO_THREAD_SAFETY_ANALYSIS // manual locking
1424{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001425 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001426 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001427 }
Eric Laurent81784c32012-11-19 14:55:58 -08001428
Eric Laurent81784c32012-11-19 14:55:58 -08001429 if (mType != RECORD) {
1430 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1431 // another session. This gives the priority to well behaved effect control panels
1432 // and applications not using global effects.
1433 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1434 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001435 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001436 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1437 }
1438 }
1439
Eric Laurent6b446ce2019-12-13 10:56:31 -08001440 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001441 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001442 }
1443}
1444
Andy Hungc5007f82023-08-29 14:26:09 -07001445// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001446status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001447 const effect_descriptor_t *desc, audio_session_t sessionId)
1448{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001449 // No global output effect sessions on record threads
1450 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1451 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001452 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1453 desc->name, mThreadName);
1454 return BAD_VALUE;
1455 }
1456 // only pre processing effects on record thread
1457 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1458 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1459 desc->name, mThreadName);
1460 return BAD_VALUE;
1461 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001462
1463 // always allow effects without processing load or latency
1464 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1465 return NO_ERROR;
1466 }
1467
Eric Laurent4c415062016-06-17 16:14:16 -07001468 audio_input_flags_t flags = mInput->flags;
1469 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1470 if (flags & AUDIO_INPUT_FLAG_RAW) {
1471 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1472 desc->name, mThreadName);
1473 return BAD_VALUE;
1474 }
1475 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1476 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1477 desc->name, mThreadName);
1478 return BAD_VALUE;
1479 }
1480 }
jiabineb3bda02020-06-30 14:07:03 -07001481
Andy Hung116bc262023-06-20 18:56:17 -07001482 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001483 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1484 return BAD_VALUE;
1485 }
Eric Laurent4c415062016-06-17 16:14:16 -07001486 return NO_ERROR;
1487}
1488
Andy Hungc5007f82023-08-29 14:26:09 -07001489// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001490status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001491 const effect_descriptor_t *desc, audio_session_t sessionId)
1492{
1493 // no preprocessing on playback threads
1494 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001495 ALOGW("%s: pre processing effect %s created on playback"
1496 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001497 return BAD_VALUE;
1498 }
1499
Eric Laurent3e4de772017-07-16 16:55:08 -07001500 // always allow effects without processing load or latency
1501 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1502 return NO_ERROR;
1503 }
1504
Andy Hung116bc262023-06-20 18:56:17 -07001505 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001506 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1507 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001508 return BAD_VALUE;
1509 }
1510
Eric Laurent4eb45d02023-12-20 12:07:17 +01001511 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001512 && mType != SPATIALIZER) {
1513 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1514 __func__, mType);
1515 return BAD_VALUE;
1516 }
1517
Eric Laurent4c415062016-06-17 16:14:16 -07001518 switch (mType) {
1519 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001520 audio_output_flags_t flags = mOutput->flags;
1521 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1522 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1523 // global effects are applied only to non fast tracks if they are SW
1524 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1525 break;
1526 }
1527 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1528 // only post processing on output stage session
1529 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001530 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1531 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001532 return BAD_VALUE;
1533 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001534 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1535 // only post processing on output stage session
1536 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001537 ALOGW("%s: non post processing effect %s not allowed on device session",
1538 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001539 return BAD_VALUE;
1540 }
Eric Laurent4c415062016-06-17 16:14:16 -07001541 } else {
1542 // no restriction on effects applied on non fast tracks
1543 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1544 break;
1545 }
1546 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001547
Eric Laurent4c415062016-06-17 16:14:16 -07001548 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001549 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001550 return BAD_VALUE;
1551 }
1552 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001553 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1554 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001555 return BAD_VALUE;
1556 }
1557 }
1558 } break;
1559 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001560 // nothing actionable on offload threads, if the effect:
1561 // - is offloadable: the effect can be created
1562 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1563 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001564 break;
1565 case DIRECT:
1566 // Reject any effect on Direct output threads for now, since the format of
1567 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001568 ALOGW("%s: effect %s on DIRECT output thread %s",
1569 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001570 return BAD_VALUE;
1571 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001572 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001573 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1574 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001575 return BAD_VALUE;
1576 }
1577 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001578 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1579 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001580 return BAD_VALUE;
1581 }
1582 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001583 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1584 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001585 return BAD_VALUE;
1586 }
1587 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001588 case SPATIALIZER:
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001589 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are supported on spatializer mixer, but only
1590 // the spatialized track have global effects applied for now.
Eric Laurentb62d0362021-10-26 17:40:18 +02001591 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1592 // are supported and added after the spatializer.
1593 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001594 ALOGD("%s: global effect %s on spatializer thread %s", __func__, desc->name,
1595 mThreadName);
Eric Laurentb62d0362021-10-26 17:40:18 +02001596 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1597 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001598 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001599 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1600 break;
1601 }
1602 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1603 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1604 __func__, desc->name);
1605 return BAD_VALUE;
1606 }
1607 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1608 // only post processing on output stage session
1609 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1610 ALOGW("%s: non post processing effect %s not allowed on device session",
1611 __func__, desc->name);
1612 return BAD_VALUE;
1613 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001614 }
1615 break;
jiabinc658e452022-10-21 20:52:21 +00001616 case BIT_PERFECT:
1617 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1618 // Allow HW accelerated effects of tunnel type
1619 break;
1620 }
1621 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1622 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1623 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1624 // 3) there is any bit-perfect track with the given session id.
1625 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1626 sessionId == AUDIO_SESSION_DEVICE) {
1627 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1628 __func__, desc->name, mThreadName);
1629 return BAD_VALUE;
1630 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1631 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1632 __func__, desc->name, sessionId);
1633 return BAD_VALUE;
1634 }
1635 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001636 default:
1637 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1638 }
1639
1640 return NO_ERROR;
1641}
1642
Andy Hungc5007f82023-08-29 14:26:09 -07001643// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001644sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001645 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001646 const sp<IEffectClient>& effectClient,
1647 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001648 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001649 effect_descriptor_t *desc,
1650 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001651 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001652 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001653 bool probe,
1654 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001655{
Andy Hung116bc262023-06-20 18:56:17 -07001656 sp<IAfEffectModule> effect;
1657 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001658 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001659 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001660 bool chainCreated = false;
1661 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001662 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001663
1664 lStatus = initCheck();
1665 if (lStatus != NO_ERROR) {
1666 ALOGW("createEffect_l() Audio driver not initialized.");
1667 goto Exit;
1668 }
1669
Eric Laurent81784c32012-11-19 14:55:58 -08001670 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1671
Andy Hungc5007f82023-08-29 14:26:09 -07001672 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001673 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001674
Eric Laurent4c415062016-06-17 16:14:16 -07001675 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001676 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001677 goto Exit;
1678 }
1679
Eric Laurent81784c32012-11-19 14:55:58 -08001680 // check for existing effect chain with the requested audio session
1681 chain = getEffectChain_l(sessionId);
1682 if (chain == 0) {
1683 // create a new chain for this session
1684 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001685 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001686 addEffectChain_l(chain);
1687 chain->setStrategy(getStrategyForSession_l(sessionId));
1688 chainCreated = true;
1689 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001690 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001691 }
1692
1693 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1694
1695 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001696 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001697 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001698 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001699 if (lStatus != NO_ERROR) {
1700 goto Exit;
1701 }
1702 effectCreated = true;
1703
jiabinc52b1ff2019-10-31 17:20:42 -07001704 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001705 effect->setDevices(outDeviceTypeAddrs());
1706 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001707 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001708 effect->setAudioSource(mAudioSource);
1709 }
jiabin1319f5a2021-03-30 22:21:24 +00001710 if (effect->isHapticGenerator()) {
1711 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1712 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001713 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001714 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001715 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001716 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001717 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001718 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001719 }
1720 }
Eric Laurent81784c32012-11-19 14:55:58 -08001721 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001722 handle = IAfEffectHandle::create(
1723 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001724 lStatus = handle->initCheck();
1725 if (lStatus == OK) {
1726 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001727 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001728 }
Eric Laurent81784c32012-11-19 14:55:58 -08001729 if (enabled != NULL) {
1730 *enabled = (int)effect->isEnabled();
1731 }
1732 }
1733
1734Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001735 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001736 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001737 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001738 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001739 }
Eric Laurent81784c32012-11-19 14:55:58 -08001740 if (chainCreated) {
1741 removeEffectChain_l(chain);
1742 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001743 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001744 }
1745
Glenn Kasten9156ef32013-08-06 15:39:08 -07001746 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001747 return handle;
1748}
1749
Andy Hungee58e4a2023-07-07 13:47:37 -07001750void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001751 bool unpinIfLast)
1752{
1753 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001754 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001755 {
Andy Hung972bec12023-08-31 16:13:39 -07001756 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001757 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001758 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001759 return;
1760 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001761 effect = effectBase->asEffectModule();
1762 if (effect == nullptr) {
1763 return;
1764 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001765 // restore suspended effects if the disconnected handle was enabled and the last one.
1766 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1767 if (remove) {
1768 removeEffect_l(effect, true);
1769 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001770 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001771 }
1772 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001773 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001774 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001775 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001776 }
1777 }
1778}
1779
Andy Hungee58e4a2023-07-07 13:47:37 -07001780void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001781 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001782 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001783 broadcast_l();
1784 }
1785 if (!effect->isOffloadable()) {
1786 if (mType == ThreadBase::OFFLOAD) {
1787 PlaybackThread *t = (PlaybackThread *)this;
1788 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1789 }
1790 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001791 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001792 }
1793 }
1794}
1795
Andy Hungee58e4a2023-07-07 13:47:37 -07001796void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001797 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001798 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001799 broadcast_l();
1800 }
1801}
1802
Andy Hungee58e4a2023-07-07 13:47:37 -07001803sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001804 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001805{
Andy Hung972bec12023-08-31 16:13:39 -07001806 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001807 return getEffect_l(sessionId, effectId);
1808}
1809
Andy Hungee58e4a2023-07-07 13:47:37 -07001810sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001811 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001812{
Andy Hung116bc262023-06-20 18:56:17 -07001813 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001814 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1815}
1816
Andy Hungee58e4a2023-07-07 13:47:37 -07001817std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001818{
Andy Hung116bc262023-06-20 18:56:17 -07001819 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001820 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001821}
1822
Andy Hung972bec12023-08-31 16:13:39 -07001823// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1824// ThreadBase::mutex() held
1825status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001826{
1827 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001828 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001829 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001830 bool chainCreated = false;
1831
Eric Laurent5baf2af2013-09-12 17:37:00 -07001832 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001833 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1834 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001835
Eric Laurent81784c32012-11-19 14:55:58 -08001836 if (chain == 0) {
1837 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001838 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001839 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001840 addEffectChain_l(chain);
1841 chain->setStrategy(getStrategyForSession_l(sessionId));
1842 chainCreated = true;
1843 }
Andy Hung972bec12023-08-31 16:13:39 -07001844 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001845
1846 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001847 ALOGW("%s: %p effect %s already present in chain %p",
1848 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001849 return BAD_VALUE;
1850 }
1851
Shunkai Yaod125e402024-01-20 03:19:06 +00001852 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001853
Shunkai Yao29d10572024-03-19 04:31:47 +00001854 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001855 if (status != NO_ERROR) {
1856 if (chainCreated) {
1857 removeEffectChain_l(chain);
1858 }
1859 return status;
1860 }
1861
jiabin8f278ee2019-11-11 12:16:27 -08001862 effect->setDevices(outDeviceTypeAddrs());
1863 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001864 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001865 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001866
Eric Laurent81784c32012-11-19 14:55:58 -08001867 return NO_ERROR;
1868}
1869
Andy Hungee58e4a2023-07-07 13:47:37 -07001870void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001871
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001872 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001873 effect_descriptor_t desc = effect->desc();
1874 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1875 detachAuxEffect_l(effect->id());
1876 }
1877
Andy Hung116bc262023-06-20 18:56:17 -07001878 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001879 if (chain != 0) {
1880 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001881 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001882 removeEffectChain_l(chain);
1883 }
1884 } else {
1885 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1886 }
1887}
1888
Shunkai Yaof4847652024-01-12 00:25:20 +00001889void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1890 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001891{
1892 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001893 for (const auto& effectChain : effectChains) {
1894 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001895 }
1896}
1897
Shunkai Yaof4847652024-01-12 00:25:20 +00001898void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1899 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001900{
Shunkai Yaof4847652024-01-12 00:25:20 +00001901 for (const auto& effectChain : effectChains) {
1902 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001903 }
1904}
1905
Andy Hungee58e4a2023-07-07 13:47:37 -07001906sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001907{
Andy Hung972bec12023-08-31 16:13:39 -07001908 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001909 return getEffectChain_l(sessionId);
1910}
1911
Andy Hungee58e4a2023-07-07 13:47:37 -07001912sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001913 const
Eric Laurent81784c32012-11-19 14:55:58 -08001914{
1915 size_t size = mEffectChains.size();
1916 for (size_t i = 0; i < size; i++) {
1917 if (mEffectChains[i]->sessionId() == sessionId) {
1918 return mEffectChains[i];
1919 }
1920 }
1921 return 0;
1922}
1923
Andy Hungee58e4a2023-07-07 13:47:37 -07001924void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001925{
Andy Hung972bec12023-08-31 16:13:39 -07001926 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001927 size_t size = mEffectChains.size();
1928 for (size_t i = 0; i < size; i++) {
1929 mEffectChains[i]->setMode_l(mode);
1930 }
1931}
1932
Andy Hungee58e4a2023-07-07 13:47:37 -07001933void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001934{
1935 config->type = AUDIO_PORT_TYPE_MIX;
1936 config->ext.mix.handle = mId;
1937 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001938 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001939 config->channel_mask = mChannelMask;
1940 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1941 AUDIO_PORT_CONFIG_FORMAT;
1942}
1943
Andy Hungee58e4a2023-07-07 13:47:37 -07001944void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001945{
Andy Hung972bec12023-08-31 16:13:39 -07001946 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001947 if (mSystemReady) {
1948 return;
1949 }
1950 mSystemReady = true;
1951
1952 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1953 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1954 }
1955 mPendingConfigEvents.clear();
1956}
1957
Andy Hungdae27702016-10-31 14:01:16 -07001958template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001959ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001960 ssize_t index = mActiveTracks.indexOf(track);
1961 if (index >= 0) {
1962 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1963 return index;
1964 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001965 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001966 mActiveTracksGeneration++;
1967 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001968 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001969 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001970 return mActiveTracks.add(track);
1971}
1972
1973template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001974ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001975 ssize_t index = mActiveTracks.remove(track);
1976 if (index < 0) {
1977 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1978 return index;
1979 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001980 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001981 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001982 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001983 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001984 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001985#ifdef TEE_SINK
1986 track->dumpTee(-1 /* fd */, "_REMOVE");
1987#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001988 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001989 return index;
1990}
1991
1992template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001993void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001994 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001995 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001996 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001997 }
1998 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001999 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07002000 mActiveTracks.clear();
2001 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07002002}
2003
2004template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07002005void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07002006 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002007 // Updates ActiveTracks client uids to the thread wakelock.
2008 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2009 thread->updateWakeLockUids_l(getWakeLockUids());
2010 mLastActiveTracksGeneration = mActiveTracksGeneration;
2011 }
Andy Hungdae27702016-10-31 14:01:16 -07002012}
Eric Laurent83b88082014-06-20 18:31:16 -07002013
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002014template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002015bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002016 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002017 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002018
2019 for (const sp<T> &track : mActiveTracks) {
2020 // Do not short-circuit as all hasChanged states must be reset
2021 // as all the metadata are going to be sent
2022 hasChanged |= track->readAndClearHasChanged();
2023 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002024 return hasChanged;
2025}
2026
2027template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002028void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002029 const char *funcName, const sp<T> &track) const {
2030 if (mLocalLog != nullptr) {
2031 String8 result;
2032 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002033 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002034 }
2035}
2036
Andy Hungee58e4a2023-07-07 13:47:37 -07002037void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002038{
2039 // Thread could be blocked waiting for async
2040 // so signal it to handle state changes immediately
2041 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2042 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2043 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002044 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002045}
2046
Andy Hungd0979812019-02-21 15:51:44 -08002047// Call only from threadLoop() or when it is idle.
2048// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002049void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002050NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002051{
2052 // Do not log if we have no stats.
2053 // We choose the timestamp verifier because it is the most likely item to be present.
2054 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2055 if (nstats == 0) {
2056 return;
2057 }
2058
2059 // Don't log more frequently than once per 12 hours.
2060 // We use BOOTTIME to include suspend time.
2061 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2062 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2063 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2064 return;
2065 }
2066
2067 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2068 mLastRecordedTimeNs = timeNs;
2069
Ray Essickf27e9872019-12-07 06:28:46 -08002070 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002071
2072#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2073
2074 // thread configuration
2075 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2076 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2077 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2078 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2079 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2080 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2081 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002082 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2083 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002084
2085 // thread statistics
2086 if (mIoJitterMs.getN() > 0) {
2087 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2088 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2089 }
2090 if (mProcessTimeMs.getN() > 0) {
2091 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2092 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2093 }
2094 const auto tsjitter = mTimestampVerifier.getJitterMs();
2095 if (tsjitter.getN() > 0) {
2096 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2097 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2098 }
2099 if (mLatencyMs.getN() > 0) {
2100 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2101 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2102 }
Robert Wu06db0a32021-08-10 19:05:34 +00002103 if (mMonopipePipeDepthStats.getN() > 0) {
2104 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2105 mMonopipePipeDepthStats.getMean());
2106 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2107 mMonopipePipeDepthStats.getStdDev());
2108 }
Andy Hungd0979812019-02-21 15:51:44 -08002109
2110 item->selfrecord();
2111}
2112
Andy Hungee58e4a2023-07-07 13:47:37 -07002113product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002114{
Andy Hung583043b2023-07-17 17:05:00 -07002115 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002116 return PRODUCT_STRATEGY_NONE;
2117 }
2118 return AudioSystem::getStrategyForStream(stream);
2119}
2120
Andy Hungc5007f82023-08-29 14:26:09 -07002121// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002122void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002123 const sp<audio_utils::MelProcessor>& /*processor*/)
2124{
2125 // Do nothing
2126 ALOGW("%s: ThreadBase does not support CSD", __func__);
2127}
2128
Andy Hungc5007f82023-08-29 14:26:09 -07002129// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002130void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002131{
2132 // Do nothing
2133 ALOGW("%s: ThreadBase does not support CSD", __func__);
2134}
2135
Eric Laurent81784c32012-11-19 14:55:58 -08002136// ----------------------------------------------------------------------------
2137// Playback
2138// ----------------------------------------------------------------------------
2139
Andy Hung583043b2023-07-17 17:05:00 -07002140PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002141 AudioStreamOut* output,
2142 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002143 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002144 bool systemReady,
2145 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002146 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002147 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002148 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002149 mMixerBuffer(NULL),
2150 mMixerBufferSize(0),
2151 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2152 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002153 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002154 mEffectBuffer(NULL),
2155 mEffectBufferSize(0),
2156 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2157 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002158 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002159 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002160 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002161 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002162 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002163 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002164 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002165 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002166 mMixerStatus(MIXER_IDLE),
2167 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002168 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002169 mBytesRemaining(0),
2170 mCurrentWriteLength(0),
2171 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002172 mWriteAckSequence(0),
2173 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002174 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002175 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002176 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002177 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002178 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002179 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002180 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002181{
Glenn Kastend7dca052015-03-05 16:05:54 -08002182 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002183 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002184
Andy Hungc5007f82023-08-29 14:26:09 -07002185 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002186 // it would be safer to explicitly pass initial masterVolume/masterMute as
2187 // parameter.
2188 //
2189 // If the HAL we are using has support for master volume or master mute,
2190 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2191 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002192 mMasterVolume = afThreadCallback->masterVolume_l();
2193 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002194 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002195 if (mOutput->audioHwDev->canSetMasterVolume()) {
2196 mMasterVolume = 1.0;
2197 }
2198
2199 if (mOutput->audioHwDev->canSetMasterMute()) {
2200 mMasterMute = false;
2201 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002202 mIsMsdDevice = strcmp(
2203 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002204 }
2205
Eric Laurentf1f22e72021-07-13 14:04:14 +02002206 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2207 mMixerChannelMask = mixerConfig->channel_mask;
2208 }
2209
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002210 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002211
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002212 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002213 && mMixerChannelMask != mChannelMask) {
2214 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2215 mChannelMask, mMixerChannelMask);
2216 }
2217
Andy Hungc8fddf32018-08-08 18:32:37 -07002218 // TODO: We may also match on address as well as device type for
2219 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002220 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002221 // TODO: This property should be ensure that only contains one single device type.
2222 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2223 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002224 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2225 : AUDIO_DEVICE_NONE));
2226 }
Andy Hung6b137d12024-08-27 22:35:17 +00002227 if (!audioserver_flags::portid_volume_management()) {
2228 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2229 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2230 mStreamTypes[stream].volume = 0.0f;
2231 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2232 }
2233 // Audio patch and call assistant volume are always max
2234 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2235 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2236 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2237 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002238 }
Eric Laurent81784c32012-11-19 14:55:58 -08002239}
2240
Andy Hungee58e4a2023-07-07 13:47:37 -07002241PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002242{
Andy Hung583043b2023-07-17 17:05:00 -07002243 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002244 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002245 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002246 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002247 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002248}
2249
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002250// Thread virtuals
2251
Andy Hungee58e4a2023-07-07 13:47:37 -07002252void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002253{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002254 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002255 ALOGE("The stream is not open yet"); // This should not happen.
2256 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002257 // Callbacks take strong or weak pointers as a parameter.
2258 // Since PlaybackThread passes itself as a callback handler, it can only
2259 // be done outside of the constructor. Creating weak and especially strong
2260 // pointers to a refcounted object in its own constructor is strongly
2261 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2262 // Even if a function takes a weak pointer, it is possible that it will
2263 // need to convert it to a strong pointer down the line.
2264 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2265 mOutput->stream->setCallback(this) == OK) {
2266 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002267 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002268 }
2269
jiabinf6eb4c32020-02-25 14:06:25 -08002270 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002271 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002272 }
2273 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002274 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002275 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002276}
2277
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002278// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002279void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002280{
2281 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002282 status_t result = mOutput->stream->exit();
2283 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002284}
2285
Andy Hungee58e4a2023-07-07 13:47:37 -07002286void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002287{
Eric Laurent81784c32012-11-19 14:55:58 -08002288 String8 result;
Andy Hung6b137d12024-08-27 22:35:17 +00002289 if (!audioserver_flags::portid_volume_management()) {
2290 result.appendFormat(" Stream volumes in dB: ");
2291 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2292 const stream_type_t *st = &mStreamTypes[i];
2293 if (i > 0) {
2294 result.appendFormat(", ");
2295 }
2296 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2297 if (st->mute) {
2298 result.append("M");
2299 }
Eric Laurent81784c32012-11-19 14:55:58 -08002300 }
2301 }
2302 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002303 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002304 result.clear();
2305
Eric Laurent81784c32012-11-19 14:55:58 -08002306 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2307 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002308 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002309 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002310
2311 size_t numtracks = mTracks.size();
2312 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002313 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002314 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002315 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002316 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002317 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002318 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002319 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002321 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002322 if (track != 0) {
2323 bool active = mActiveTracks.indexOf(track) >= 0;
2324 if (active) {
2325 numactiveseen++;
2326 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002327 result.append(prefix);
2328 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002329 }
2330 }
2331 } else {
2332 result.append("\n");
2333 }
2334 if (numactiveseen != numactive) {
2335 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002336 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002337 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002338 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002339 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002340 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002341 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002342 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002343 result.append(prefix);
2344 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002345 }
2346 }
2347 }
2348
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002349 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002350}
2351
Andy Hungee58e4a2023-07-07 13:47:37 -07002352void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002353{
Andy Hung04cb8f72020-03-20 13:44:33 -07002354 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002355 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002356 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2357 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002358 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2359 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2360 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2361 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002362 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002363 dprintf(fd, " Total writes: %d\n", mNumWrites);
2364 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2365 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002366 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002367 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002368 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002369 AudioStreamOut *output = mOutput;
2370 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002371 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002372 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002373 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2374 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2375 if (mPipeSink.get() != nullptr) {
2376 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2377 }
2378 if (output != nullptr) {
2379 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002380 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002381 }
Eric Laurent81784c32012-11-19 14:55:58 -08002382}
2383
Andy Hungc5007f82023-08-29 14:26:09 -07002384// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002385sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002386 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002387 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002388 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002389 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002390 audio_format_t format,
2391 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002392 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002393 size_t *pNotificationFrameCount,
2394 uint32_t notificationsPerBuffer,
2395 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002396 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002397 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002398 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002399 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002400 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002401 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002402 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002403 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002404 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002405 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002406 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00002407 audio_output_flags_t *afTrackFlags,
2408 float volume)
Eric Laurent81784c32012-11-19 14:55:58 -08002409{
Glenn Kasten74935e42013-12-19 08:56:45 -08002410 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002411 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002412 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002413 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002414 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002415 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002416 uint32_t sampleRate;
2417
2418 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2419 lStatus = BAD_VALUE;
2420 goto Exit;
2421 }
Eric Laurent21da6472017-11-09 16:29:26 -08002422
2423 if (*pSampleRate == 0) {
2424 *pSampleRate = mSampleRate;
2425 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002426 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002427
2428 // special case for FAST flag considered OK if fast mixer is present
2429 if (hasFastMixer()) {
2430 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2431 }
2432
2433 // Check if requested flags are compatible with output stream flags
2434 if ((*flags & outputFlags) != *flags) {
2435 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2436 *flags, outputFlags);
2437 *flags = (audio_output_flags_t)(*flags & outputFlags);
2438 }
Eric Laurent81784c32012-11-19 14:55:58 -08002439
jiabinc658e452022-10-21 20:52:21 +00002440 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002441 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002442 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002443 if (chain.get() != nullptr) {
2444 // Bit-perfect is required according to the configuration and preferred mixer
2445 // attributes, but it is not in the output flag from the client's request. Explicitly
2446 // adding bit-perfect flag to check the compatibility
2447 audio_output_flags_t flagsToCheck =
2448 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2449 chain->checkOutputFlagCompatibility(&flagsToCheck);
2450 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2451 ALOGE("%s cannot create track as there is data-processing effect attached to "
2452 "given session id(%d)", __func__, sessionId);
2453 lStatus = BAD_VALUE;
2454 goto Exit;
2455 }
2456 *flags = flagsToCheck;
2457 }
2458 }
2459
Eric Laurent81784c32012-11-19 14:55:58 -08002460 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002461 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002462 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002463 // PCM data
2464 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002465 // TODO: extract as a data library function that checks that a computationally
2466 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002467 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002468 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2469 (channelMask == AUDIO_CHANNEL_OUT_MONO
2470 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002471 // hardware sample rate
2472 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002473 // normal mixer has an associated fast mixer
2474 hasFastMixer() &&
2475 // there are sufficient fast track slots available
2476 (mFastTrackAvailMask != 0)
2477 // FIXME test that MixerThread for this fast track has a capable output HAL
2478 // FIXME add a permission test also?
2479 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002480 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2481 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002482 // read the fast track multiplier property the first time it is needed
2483 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2484 if (ok != 0) {
2485 ALOGE("%s pthread_once failed: %d", __func__, ok);
2486 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002487 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002488 }
Eric Laurent4c415062016-06-17 16:14:16 -07002489
2490 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002491 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002492 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002493 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002494 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002495 AUDIO_SESSION_OUTPUT_STAGE,
2496 AUDIO_SESSION_OUTPUT_MIX,
2497 sessionId,
2498 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002499 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002500 if (chain.get() != nullptr) {
2501 audio_output_flags_t old = *flags;
2502 chain->checkOutputFlagCompatibility(flags);
2503 if (old != *flags) {
2504 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2505 (int)session, (int)old, (int)*flags);
2506 }
Eric Laurent4c415062016-06-17 16:14:16 -07002507 }
2508 }
2509 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002510 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002511 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2512 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002513 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002514 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002515 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002516 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002517 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002518 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002519 audio_is_linear_pcm(format), channelMask, sampleRate,
2520 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002521 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002522 }
2523 }
Eric Laurent21da6472017-11-09 16:29:26 -08002524
2525 if (!audio_has_proportional_frames(format)) {
2526 if (sharedBuffer != 0) {
2527 // Same comment as below about ignoring frameCount parameter for set()
2528 frameCount = sharedBuffer->size();
2529 } else if (frameCount == 0) {
2530 frameCount = mNormalFrameCount;
2531 }
2532 if (notificationFrameCount != frameCount) {
2533 notificationFrameCount = frameCount;
2534 }
2535 } else if (sharedBuffer != 0) {
2536 // FIXME: Ensure client side memory buffers need
2537 // not have additional alignment beyond sample
2538 // (e.g. 16 bit stereo accessed as 32 bit frame).
2539 size_t alignment = audio_bytes_per_sample(format);
2540 if (alignment & 1) {
2541 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2542 alignment = 1;
2543 }
2544 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2545 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2546 if (channelCount > 1) {
2547 // More than 2 channels does not require stronger alignment than stereo
2548 alignment <<= 1;
2549 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002550 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002551 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002552 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002553 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002554 goto Exit;
2555 }
Eric Laurent21da6472017-11-09 16:29:26 -08002556
2557 // When initializing a shared buffer AudioTrack via constructors,
2558 // there's no frameCount parameter.
2559 // But when initializing a shared buffer AudioTrack via set(),
2560 // there _is_ a frameCount parameter. We silently ignore it.
2561 frameCount = sharedBuffer->size() / frameSize;
2562 } else {
2563 size_t minFrameCount = 0;
2564 // For fast tracks we try to respect the application's request for notifications per buffer.
2565 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2566 if (notificationsPerBuffer > 0) {
2567 // Avoid possible arithmetic overflow during multiplication.
2568 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2569 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2570 notificationsPerBuffer, mFrameCount);
2571 } else {
2572 minFrameCount = mFrameCount * notificationsPerBuffer;
2573 }
2574 }
2575 } else {
2576 // For normal PCM streaming tracks, update minimum frame count.
2577 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2578 // cover audio hardware latency.
2579 // This is probably too conservative, but legacy application code may depend on it.
2580 // If you change this calculation, also review the start threshold which is related.
2581 uint32_t latencyMs = latency_l();
2582 if (latencyMs == 0) {
2583 ALOGE("Error when retrieving output stream latency");
2584 lStatus = UNKNOWN_ERROR;
2585 goto Exit;
2586 }
2587
2588 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2589 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2590
Eric Laurent81784c32012-11-19 14:55:58 -08002591 }
Eric Laurent21da6472017-11-09 16:29:26 -08002592 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002593 frameCount = minFrameCount;
2594 }
Eric Laurent81784c32012-11-19 14:55:58 -08002595 }
Eric Laurent21da6472017-11-09 16:29:26 -08002596
2597 // Make sure that application is notified with sufficient margin before underrun.
2598 // The client can divide the AudioTrack buffer into sub-buffers,
2599 // and expresses its desire to server as the notification frame count.
2600 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2601 size_t maxNotificationFrames;
2602 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2603 // notify every HAL buffer, regardless of the size of the track buffer
2604 maxNotificationFrames = mFrameCount;
2605 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002606 // Triple buffer the notification period for a triple buffered mixer period;
2607 // otherwise, double buffering for the notification period is fine.
2608 //
2609 // TODO: This should be moved to AudioTrack to modify the notification period
2610 // on AudioTrack::setBufferSizeInFrames() changes.
2611 const int nBuffering =
2612 (uint64_t{frameCount} * mSampleRate)
2613 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2614
Eric Laurent21da6472017-11-09 16:29:26 -08002615 maxNotificationFrames = frameCount / nBuffering;
2616 // If client requested a fast track but this was denied, then use the smaller maximum.
2617 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2618 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2619 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2620 maxNotificationFrames = maxNotificationFramesFastDenied;
2621 }
2622 }
2623 }
2624 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2625 if (notificationFrameCount == 0) {
2626 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2627 maxNotificationFrames, frameCount);
2628 } else {
2629 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2630 notificationFrameCount, maxNotificationFrames, frameCount);
2631 }
2632 notificationFrameCount = maxNotificationFrames;
2633 }
2634 }
2635
Glenn Kasten74935e42013-12-19 08:56:45 -08002636 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002637 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002638
Glenn Kastenc3df8382014-03-13 15:05:25 -07002639 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002640 case BIT_PERFECT:
2641 if (isBitPerfect) {
2642 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2643 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2644 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2645 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2646 mChannelMask);
2647 lStatus = BAD_VALUE;
2648 goto Exit;
2649 }
2650 }
2651 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002652
2653 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002654 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002655 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002656 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2657 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002658 sampleRate, format, channelMask, mOutput, mFormat);
2659 lStatus = BAD_VALUE;
2660 goto Exit;
2661 }
2662 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002663 break;
2664
2665 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002667 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2668 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 sampleRate, format, channelMask, mOutput, mFormat);
2670 lStatus = BAD_VALUE;
2671 goto Exit;
2672 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002673 break;
2674
2675 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002676 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002677 ALOGE("createTrack_l() Bad parameter: format %#x \""
2678 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002679 format, mOutput, mFormat);
2680 lStatus = BAD_VALUE;
2681 goto Exit;
2682 }
Andy Hungcd044842014-08-07 11:04:34 -07002683 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002684 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2685 lStatus = BAD_VALUE;
2686 goto Exit;
2687 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002688 break;
2689
Eric Laurent81784c32012-11-19 14:55:58 -08002690 }
2691
2692 lStatus = initCheck();
2693 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002694 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002695 goto Exit;
2696 }
2697
Andy Hungc5007f82023-08-29 14:26:09 -07002698 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002699 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002700
2701 // all tracks in same audio session must share the same routing strategy otherwise
2702 // conflicts will happen when tracks are moved from one output to another by audio policy
2703 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002704 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002705 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002706 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002707 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002708 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002709 if (sessionId == t->sessionId() && strategy != actual) {
2710 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2711 strategy, actual);
2712 lStatus = BAD_VALUE;
2713 goto Exit;
2714 }
2715 }
2716 }
2717
Deeraj Soman2b515232024-05-14 12:58:24 +05302718 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2719 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002720 // dynamic audio policy.
2721 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302722 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002723 audio_output_flags_t trackFlags = *flags;
2724 if (mType == DIRECT) {
2725 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302726 } else if (mType == OFFLOAD) {
2727 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2728 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002729 }
jiabin94ed47c2023-07-27 23:34:20 +00002730 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002731
Andy Hung8d31fd22023-06-26 19:20:57 -07002732 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002733 channelMask, frameCount,
2734 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002735 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002736 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Andy Hung6b137d12024-08-27 22:35:17 +00002737 speed, isSpatialized, isBitPerfect, volume);
Glenn Kasten03003332013-08-06 15:40:54 -07002738
Glenn Kasten03003332013-08-06 15:40:54 -07002739 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2740 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002741 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002742 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002743 goto Exit;
2744 }
2745 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002746 {
Andy Hung972bec12023-08-31 16:13:39 -07002747 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002748 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002749 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002750 }
2751 }
Eric Laurent81784c32012-11-19 14:55:58 -08002752
Andy Hung116bc262023-06-20 18:56:17 -07002753 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002754 if (chain != 0) {
2755 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2756 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002757 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002758 chain->incTrackCnt();
2759 }
2760
Eric Laurent05067782016-06-01 18:27:28 -07002761 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002762 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2763 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2764 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002765 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002766 }
2767 }
2768
2769 lStatus = NO_ERROR;
2770
2771Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002772 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002773 return track;
2774}
2775
Andy Hung1bc088a2018-02-09 15:57:31 -08002776template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002777ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002778{
Andy Hungc0691382018-09-12 18:01:57 -07002779 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002780 const ssize_t index = mTracks.remove(track);
2781 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002782 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002783 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002784 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002785 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002786 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002787 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002788 }
2789 return index;
2790}
2791
Andy Hungee58e4a2023-07-07 13:47:37 -07002792uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
2794 return latency;
2795}
2796
Andy Hungee58e4a2023-07-07 13:47:37 -07002797uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002798{
Andy Hung972bec12023-08-31 16:13:39 -07002799 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002800 return latency_l();
2801}
Andy Hungee58e4a2023-07-07 13:47:37 -07002802uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002803NO_THREAD_SAFETY_ANALYSIS
2804// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002805{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002806 uint32_t latency;
2807 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2808 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002809 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002810 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002811}
2812
Andy Hungee58e4a2023-07-07 13:47:37 -07002813void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002814{
Andy Hung972bec12023-08-31 16:13:39 -07002815 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002816 // Don't apply master volume in SW if our HAL can do it for us.
2817 if (mOutput && mOutput->audioHwDev &&
2818 mOutput->audioHwDev->canSetMasterVolume()) {
2819 mMasterVolume = 1.0;
2820 } else {
2821 mMasterVolume = value;
2822 }
2823}
2824
Andy Hungee58e4a2023-07-07 13:47:37 -07002825void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002826{
2827 mMasterBalance.store(balance);
2828}
2829
Andy Hungee58e4a2023-07-07 13:47:37 -07002830void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002831{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002832 if (isDuplicating()) {
2833 return;
2834 }
Andy Hung972bec12023-08-31 16:13:39 -07002835 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002836 // Don't apply master mute in SW if our HAL can do it for us.
2837 if (mOutput && mOutput->audioHwDev &&
2838 mOutput->audioHwDev->canSetMasterMute()) {
2839 mMasterMute = false;
2840 } else {
2841 mMasterMute = muted;
2842 }
2843}
2844
Andy Hungee58e4a2023-07-07 13:47:37 -07002845void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002846{
Andy Hung972bec12023-08-31 16:13:39 -07002847 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002848 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002849 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002850}
2851
Andy Hungee58e4a2023-07-07 13:47:37 -07002852void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002853{
Andy Hung972bec12023-08-31 16:13:39 -07002854 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002855 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002856 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002857}
2858
Andy Hungee58e4a2023-07-07 13:47:37 -07002859float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002860{
Andy Hung972bec12023-08-31 16:13:39 -07002861 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002862 return mStreamTypes[stream].volume;
2863}
2864
Andy Hung6b137d12024-08-27 22:35:17 +00002865status_t PlaybackThread::setPortsVolume(
2866 const std::vector<audio_port_handle_t>& portIds, float volume) {
2867 audio_utils::lock_guard _l(mutex());
2868 for (const auto& portId : portIds) {
2869 for (size_t i = 0; i < mTracks.size(); i++) {
2870 sp<IAfTrack> track = mTracks[i].get();
2871 if (portId == track->portId()) {
2872 track->setPortVolume(volume);
2873 break;
2874 }
2875 }
2876 }
2877 broadcast_l();
2878 return NO_ERROR;
2879}
2880
Andy Hungee58e4a2023-07-07 13:47:37 -07002881void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002882{
2883 mOutput->stream->setVolume(left, right);
2884}
2885
Andy Hungc5007f82023-08-29 14:26:09 -07002886// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002887status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002888{
2889 status_t status = ALREADY_EXISTS;
2890
Eric Laurent81784c32012-11-19 14:55:58 -08002891 if (mActiveTracks.indexOf(track) < 0) {
2892 // the track is newly added, make sure it fills up all its
2893 // buffers before playing. This is to ensure the client will
2894 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002895 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002896 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002897 // Because the track is not on the ActiveTracks,
2898 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002899 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002900 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002901 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002902 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002903 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002905 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002906 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002907 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002908 }
2909 return INVALID_OPERATION;
2910 }
2911 // abort if start is rejected by audio policy manager
2912 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002913 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2914 // current playback thread is reopened, which may happen when clients set preferred
2915 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2916 // immediately.
2917 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002918 }
2919#ifdef ADD_BATTERY_DATA
2920 // to track the speaker usage
2921 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2922#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002923 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 }
2925
Eric Laurent51716182016-02-29 18:00:56 -08002926 // set retry count for buffer fill
2927 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002928 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002929 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002930 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002931 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002932 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002933 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002934 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002935 track->retryCount() = kMaxTrackStartupRetries;
2936 track->fillingStatus() =
2937 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002938 }
2939
Andy Hung116bc262023-06-20 18:56:17 -07002940 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002941 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2942 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002943 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002944 // Unlock due to VibratorService will lock for this call and will
2945 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002946 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002947 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002948 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002949 std::optional<media::AudioVibratorInfo> vibratorInfo;
2950 {
2951 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2952 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002953 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002954 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002955 }
Andy Hungc5007f82023-08-29 14:26:09 -07002956 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002957 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002958 if (vibratorInfo) {
2959 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2960 }
2961
jiabin57303cc2018-12-18 15:45:57 -08002962 // Haptic playback should be enabled by vibrator service.
2963 if (track->getHapticPlaybackEnabled()) {
2964 // Disable haptic playback of all active track to ensure only
2965 // one track playing haptic if current track should play haptic.
2966 for (const auto &t : mActiveTracks) {
2967 t->setHapticPlaybackEnabled(false);
2968 }
jiabin245cdd92018-12-07 17:55:15 -08002969 }
jiabine70bc7f2020-06-30 22:07:55 -07002970
2971 // Set haptic intensity for effect
2972 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002973 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002974 }
jiabin245cdd92018-12-07 17:55:15 -08002975 }
2976
Andy Hung8d31fd22023-06-26 19:20:57 -07002977 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002978 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002979
2980 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2981 // all key changes are complete. It is possible that the threadLoop will begin
2982 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002983 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002984
Eric Laurentd0107bc2013-06-11 14:38:48 -07002985 if (chain != 0) {
2986 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2987 track->sessionId());
2988 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002989 }
2990
Andy Hungc2b11cb2020-04-22 09:04:01 -07002991 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002992 status = NO_ERROR;
2993 }
2994
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002995 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002996 return status;
2997}
2998
Andy Hungee58e4a2023-07-07 13:47:37 -07002999bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003000{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08003002 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003003 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07003004 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003005 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08003006 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07003007 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07003008 if (track->isPausePending()) {
3009 track->pauseAck();
3010 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003011 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003012 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003013
3014 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003015}
3016
Andy Hungee58e4a2023-07-07 13:47:37 -07003017void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003018{
3019 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003020
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003021 String8 result;
3022 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003023 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003024
Eric Laurent81784c32012-11-19 14:55:58 -08003025 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003026 {
Andy Hung972bec12023-08-31 16:13:39 -07003027 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003028 mAudioTrackCallbacks.erase(track);
3029 }
Eric Laurent81784c32012-11-19 14:55:58 -08003030 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003031 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003032 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003033 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3034 mFastTrackAvailMask |= 1 << index;
3035 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003036 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003037 }
Andy Hung116bc262023-06-20 18:56:17 -07003038 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003039 if (chain != 0) {
3040 chain->decTrackCnt();
3041 }
3042}
3043
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003044std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3045{
3046 std::set<int32_t> result;
3047 for (const auto& t : mTracks) {
3048 if (t->isExternalTrack()) {
3049 result.insert(t->portId());
3050 }
3051 }
3052 return result;
3053}
3054
3055std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3056{
3057 audio_utils::lock_guard _l(mutex());
3058 return getTrackPortIds_l();
3059}
3060
Andy Hungee58e4a2023-07-07 13:47:37 -07003061String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003062{
Andy Hung972bec12023-08-31 16:13:39 -07003063 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003064 String8 out_s8;
3065 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3066 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003067 }
Andy Hung920f6572022-10-06 12:09:49 -07003068 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003069}
3070
Andy Hungee58e4a2023-07-07 13:47:37 -07003071status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003072 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003073 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003074 return NO_INIT;
3075 }
3076 return mOutput->stream->selectPresentation(presentationId, programId);
3077}
3078
Andy Hungab65b182023-09-06 19:41:47 -07003079void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003080 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003081 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003082 sp<AudioIoDescriptor> desc;
3083 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003084 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003085 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003086 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003087 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003088 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3089 mSampleRate, mFormat, mChannelMask,
3090 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3091 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003092 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003093 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003094 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003095 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003096 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003097 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003098 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003099 break;
3100 }
Andy Hungab65b182023-09-06 19:41:47 -07003101 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003102}
3103
Andy Hungee58e4a2023-07-07 13:47:37 -07003104void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003106 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107}
3108
Andy Hungee58e4a2023-07-07 13:47:37 -07003109void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003111 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003112}
3113
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003114void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003115{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003116 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003117}
3118
Andy Hungee58e4a2023-07-07 13:47:37 -07003119void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003120 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003121{
Andy Hungee58e4a2023-07-07 13:47:37 -07003122 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003123 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003124 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003125 if (playbackThread == nullptr) {
3126 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3127 return;
3128 }
3129
jiabinf6eb4c32020-02-25 14:06:25 -08003130 audio_utils::metadata::Data metadata =
3131 audio_utils::metadata::dataFromByteString(metadataBs);
3132 if (metadata.empty()) {
3133 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3134 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3135 (int)metadataBs.size());
3136 return;
3137 }
3138
3139 audio_utils::metadata::ByteString metaDataStr =
3140 audio_utils::metadata::byteStringFromData(metadata);
3141 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003142 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003143 for (const auto& callbackPair : mAudioTrackCallbacks) {
3144 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003145 }
3146 }).detach();
3147}
3148
Andy Hungee58e4a2023-07-07 13:47:37 -07003149void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003150{
Andy Hung972bec12023-08-31 16:13:39 -07003151 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003152 // reject out of sequence requests
3153 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3154 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003155 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156 }
3157}
3158
Andy Hungee58e4a2023-07-07 13:47:37 -07003159void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160{
Andy Hung972bec12023-08-31 16:13:39 -07003161 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003162 // reject out of sequence requests
3163 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003164 // Register discontinuity when HW drain is completed because that can cause
3165 // the timestamp frame position to reset to 0 for direct and offload threads.
3166 // (Out of sequence requests are ignored, since the discontinuity would be handled
3167 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003168 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003169 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003170 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003171 }
3172}
3173
Andy Hungee58e4a2023-07-07 13:47:37 -07003174void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003175NO_THREAD_SAFETY_ANALYSIS
3176// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003177{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003178 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003179 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3180 mSampleRate = audioConfig.sample_rate;
3181 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003182 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003183 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003184 }
Andy Hung81994d62023-07-20 21:44:14 -07003185 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003186 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3187 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003188 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003189
3190 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3191 mMixerChannelMask = mChannelMask;
3192 }
3193
Andy Hunge5412692014-05-16 11:25:07 -07003194 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003195 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003196
Eric Laurentf1f22e72021-07-13 14:04:14 +02003197 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3198
Phil Burkca5e6142015-07-14 09:42:29 -07003199 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003200 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003201 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003202 // Get format from the shim, which will be different than the HAL format
3203 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003204 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003205 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003206 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003207 }
Andy Hung81994d62023-07-20 21:44:14 -07003208 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003209 LOG_FATAL("HAL format %#x not supported for mixed output",
3210 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003211 }
Phil Burk062e67a2015-02-11 13:40:50 -08003212 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003213 result = mOutput->stream->getBufferSize(&mBufferSize);
3214 LOG_ALWAYS_FATAL_IF(result != OK,
3215 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003216 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003217 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003218 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003219 mFrameCount);
3220 }
3221
Eric Laurentd1f69b02014-12-15 14:33:13 -08003222 mHwSupportsPause = false;
3223 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003224 bool supportsPause = false, supportsResume = false;
3225 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3226 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003227 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003228 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003229 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003230 } else if (supportsResume) {
3231 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003232 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003233 }
3234 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003235 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3236 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3237 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003238
Andy Hungfbfc3952015-01-15 13:33:51 -08003239 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3240 // For best precision, we use float instead of the associated output
3241 // device format (typically PCM 16 bit).
3242
3243 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3244 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3245 mBufferSize = mFrameSize * mFrameCount;
3246
3247 // TODO: We currently use the associated output device channel mask and sample rate.
3248 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3249 // (if a valid mask) to avoid premature downmix.
3250 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3251 // instead of the output device sample rate to avoid loss of high frequency information.
3252 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3253 }
3254
Andy Hung09a50072014-02-27 14:30:47 -08003255 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003256 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003257 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003258 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3259 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003260 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3261 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003262
Eric Laurent81784c32012-11-19 14:55:58 -08003263 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3264 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3265 maxNormalFrameCount = maxNormalFrameCount & ~15;
3266 if (maxNormalFrameCount < minNormalFrameCount) {
3267 maxNormalFrameCount = minNormalFrameCount;
3268 }
3269 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3270 if (multiplier <= 1.0) {
3271 multiplier = 1.0;
3272 } else if (multiplier <= 2.0) {
3273 if (2 * mFrameCount <= maxNormalFrameCount) {
3274 multiplier = 2.0;
3275 } else {
3276 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3277 }
3278 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003279 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003280 }
3281 }
3282 mNormalFrameCount = multiplier * mFrameCount;
3283 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003284 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003285 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3286 }
Andy Hungab65b182023-09-06 19:41:47 -07003287 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3288 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003289
Andy Hung08fb1742015-05-31 23:22:10 -07003290 // Check if we want to throttle the processing to no more than 2x normal rate
3291 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003292 mThreadThrottleTimeMs = 0;
3293 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003294 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3295
Andy Hung010a1a12014-03-13 13:57:33 -07003296 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3297 // Originally this was int16_t[] array, need to remove legacy implications.
3298 free(mSinkBuffer);
3299 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003300
Andy Hung5b10a202014-03-13 13:59:29 -07003301 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3302 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3303 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003304 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003305
Andy Hung69aed5f2014-02-25 17:24:40 -08003306 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3307 // drives the output.
3308 free(mMixerBuffer);
3309 mMixerBuffer = NULL;
3310 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003311 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003312 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003313 * audio_bytes_per_sample(mMixerBufferFormat);
3314 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3315 }
Andy Hung98ef9782014-03-04 14:46:50 -08003316 free(mEffectBuffer);
3317 mEffectBuffer = NULL;
3318 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003319 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003320 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003321 * audio_bytes_per_sample(mEffectBufferFormat);
3322 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3323 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003324
Eric Laurentb62d0362021-10-26 17:40:18 +02003325 if (mType == SPATIALIZER) {
3326 free(mPostSpatializerBuffer);
3327 mPostSpatializerBuffer = nullptr;
3328 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3329 * audio_bytes_per_sample(mEffectBufferFormat);
3330 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3331 }
3332
Mikhail Naganov55773032020-10-01 15:08:13 -07003333 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3334 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003335 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3336 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003337 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003338
Eric Laurent81784c32012-11-19 14:55:58 -08003339 // force reconfiguration of effect chains and engines to take new buffer size and audio
3340 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003341 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003342 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3343 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003344 // create a copy of mEffectChains as calling moveEffectChain_ll()
3345 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003346 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003347 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003348 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003349 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003350 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003351
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003352 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003353 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003354 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003355 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003356 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3357 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3358 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3359 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3360 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3361 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3362 (int32_t)mHapticChannelMask)
3363 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3364 (int32_t)mHapticChannelCount)
3365 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003366 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003367 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3368 (int32_t)mFrameCount) // sic - added HAL
3369 ;
3370 uint32_t latencyMs;
3371 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3372 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3373 }
3374 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003375}
3376
Andy Hungee58e4a2023-07-07 13:47:37 -07003377ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003378{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003379 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003380 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003381 }
3382 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003383 static const bool stereo_spatialization_property =
3384 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3385 const bool stereo_spatialization_enabled =
3386 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3387 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003388 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3389 for (const sp<IAfTrack>& track : mActiveTracks) {
3390 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3391 allSessionsMetadata[track->sessionId()];
3392 auto backInserter = std::back_inserter(sessionMetadata);
3393 // No track is invalid as this is called after prepareTrack_l in the same
3394 // critical section
3395 track->copyMetadataTo(backInserter);
3396 }
3397 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3398 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3399 metadata.tracks.insert(metadata.tracks.end(),
3400 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3401 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3402 chain->sendMetadata_l(sessionTrackMetadata, {});
3403 }
3404 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3405 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3406 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3407 }
3408 }
3409 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3410 chain->sendMetadata_l(metadata.tracks, {});
3411 }
3412 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3413 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3414 }
3415 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3416 chain->sendMetadata_l(metadata.tracks, {});
3417 }
3418 } else {
3419 auto backInserter = std::back_inserter(metadata.tracks);
3420 for (const sp<IAfTrack>& track : mActiveTracks) {
3421 // No track is invalid as this is called after prepareTrack_l in the same
3422 // critical section
3423 track->copyMetadataTo(backInserter);
3424 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003425 }
Kevin Rocard12381092018-04-11 09:19:59 -07003426 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003427 MetadataUpdate change;
3428 change.playbackMetadataUpdate = metadata.tracks;
3429 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003430}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003431
Andy Hungee58e4a2023-07-07 13:47:37 -07003432void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003433 const StreamOutHalInterface::SourceMetadata& metadata)
3434{
3435 mOutput->stream->updateSourceMetadata(metadata);
3436};
3437
Andy Hungee58e4a2023-07-07 13:47:37 -07003438status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003439 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003440{
3441 if (halFrames == NULL || dspFrames == NULL) {
3442 return BAD_VALUE;
3443 }
Andy Hung972bec12023-08-31 16:13:39 -07003444 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003445 if (initCheck() != NO_ERROR) {
3446 return INVALID_OPERATION;
3447 }
Andy Hung818e7a32016-02-16 18:08:07 -08003448 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003449 *halFrames = framesWritten;
3450
3451 if (isSuspended()) {
3452 // return an estimation of rendered frames when the output is suspended
3453 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003454 *dspFrames = (uint32_t)
3455 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003456 return NO_ERROR;
3457 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003458 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003459 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003460 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003461 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003462 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003463 }
3464}
3465
Andy Hungee58e4a2023-07-07 13:47:37 -07003466product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003467{
3468 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3469 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3470 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003471 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003472 }
3473 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003474 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003475 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003476 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003477 }
3478 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003479 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003480}
3481
3482
Andy Hungee58e4a2023-07-07 13:47:37 -07003483AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003484{
Andy Hung972bec12023-08-31 16:13:39 -07003485 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003486 return mOutput;
3487}
3488
Andy Hungee58e4a2023-07-07 13:47:37 -07003489AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003490{
Andy Hung972bec12023-08-31 16:13:39 -07003491 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003492 AudioStreamOut *output = mOutput;
3493 mOutput = NULL;
3494 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3495 // must push a NULL and wait for ack
3496 mOutputSink.clear();
3497 mPipeSink.clear();
3498 mNormalSink.clear();
3499 return output;
3500}
3501
Andy Hungc5007f82023-08-29 14:26:09 -07003502// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003503sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003504{
3505 if (mOutput == NULL) {
3506 return NULL;
3507 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003508 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003509}
3510
Andy Hungee58e4a2023-07-07 13:47:37 -07003511uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003512{
3513 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3514}
3515
Andy Hungee58e4a2023-07-07 13:47:37 -07003516status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003517{
3518 if (!isValidSyncEvent(event)) {
3519 return BAD_VALUE;
3520 }
3521
Andy Hung972bec12023-08-31 16:13:39 -07003522 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003523
3524 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003525 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003526 if (event->triggerSession() == track->sessionId()) {
3527 (void) track->setSyncEvent(event);
3528 return NO_ERROR;
3529 }
3530 }
3531
3532 return NAME_NOT_FOUND;
3533}
3534
Andy Hungee58e4a2023-07-07 13:47:37 -07003535bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003536{
3537 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3538}
3539
Andy Hungee58e4a2023-07-07 13:47:37 -07003540void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003541 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003542{
Andy Hungfe726a62018-09-27 15:17:25 -07003543 // Miscellaneous track cleanup when removed from the active list,
3544 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003546 for (const auto& track : tracksToRemove) {
3547 if (track->isExternalTrack()) {
3548 // to track the speaker usage
3549 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003550 }
3551 }
Andy Hungfe726a62018-09-27 15:17:25 -07003552#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003553}
3554
Andy Hungee58e4a2023-07-07 13:47:37 -07003555void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003556{
3557 if (!mMasterMute) {
3558 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003559 if (mOutDeviceTypeAddrs.empty()) {
3560 ALOGD("ro.audio.silent is ignored since no output device is set");
3561 return;
3562 }
Andy Hungab65b182023-09-06 19:41:47 -07003563 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003564 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3565 return;
3566 }
Eric Laurent81784c32012-11-19 14:55:58 -08003567 if (property_get("ro.audio.silent", value, "0") > 0) {
3568 char *endptr;
3569 unsigned long ul = strtoul(value, &endptr, 0);
3570 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003571 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003572 // The setprop command will not allow a property to be changed after
3573 // the first time it is set, so we don't have to worry about un-muting.
3574 setMasterMute_l(true);
3575 }
3576 }
3577 }
3578}
3579
3580// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003581ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003582{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003583 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003584 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003585 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003586 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003587
3588 // If an NBAIO sink is present, use it to write the normal mixer's submix
3589 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003590
Andy Hung010a1a12014-03-13 13:57:33 -07003591 const size_t count = mBytesRemaining / mFrameSize;
3592
Simon Wilson2d590962012-11-29 15:18:50 -08003593 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003594 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003595 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003596 if (screenState != mScreenState) {
3597 mScreenState = screenState;
3598 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3599 if (pipe != NULL) {
3600 pipe->setAvgFrames((mScreenState & 1) ?
3601 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3602 }
3603 }
Andy Hung010a1a12014-03-13 13:57:33 -07003604 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003605 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003606
Eric Laurent81784c32012-11-19 14:55:58 -08003607 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003608 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003609
Andy Hung8946a282018-04-19 20:04:56 -07003610#ifdef TEE_SINK
3611 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3612#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003613 } else {
3614 bytesWritten = framesWritten;
3615 }
3616 // otherwise use the HAL / AudioStreamOut directly
3617 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003619
Eric Laurentbfb1b832013-01-07 09:53:42 -08003620 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003621 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3622 mWriteAckSequence += 2;
3623 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003624 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003625 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003626 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003627 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003628 // FIXME We should have an implementation of timestamps for direct output threads.
3629 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003630 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003631 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003632
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633 if (mUseAsyncWrite &&
3634 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3635 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003636 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003637 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003638 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003639 }
Eric Laurent81784c32012-11-19 14:55:58 -08003640 }
3641
Eric Laurent81784c32012-11-19 14:55:58 -08003642 mNumWrites++;
3643 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003644 if (mStandby) {
3645 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003646 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003647 mStandby = false;
3648 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 return bytesWritten;
3650}
3651
Andy Hungc5007f82023-08-29 14:26:09 -07003652// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003653void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003654 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003655{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003656 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003657 if (outputSink != nullptr) {
3658 outputSink->startMelComputation(processor);
3659 }
Vlad Popab042ee62022-10-20 18:05:00 +02003660}
3661
Andy Hungc5007f82023-08-29 14:26:09 -07003662// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003663void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003664{
3665 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003666 if (outputSink != nullptr) {
3667 outputSink->stopMelComputation();
3668 }
Vlad Popab042ee62022-10-20 18:05:00 +02003669}
3670
Andy Hungee58e4a2023-07-07 13:47:37 -07003671void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003672{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003673 bool supportsDrain = false;
3674 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003675 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3676 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003677 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3678 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003679 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003680 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003682 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003683 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003684 }
3685}
3686
Andy Hungee58e4a2023-07-07 13:47:37 -07003687void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003688{
Eric Laurent275e8e92014-11-30 15:14:47 -08003689 {
Andy Hung972bec12023-08-31 16:13:39 -07003690 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003691 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003692 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003693 track->invalidate();
3694 }
Andy Hungdae27702016-10-31 14:01:16 -07003695 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3696 // After we exit there are no more track changes sent to BatteryNotifier
3697 // because that requires an active threadLoop.
3698 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3699 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003700 }
Eric Laurent81784c32012-11-19 14:55:58 -08003701}
3702
3703/*
3704The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003705 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003706 - mActiveSleepTimeUs from activeSleepTimeUs()
3707 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003708 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3709 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003710 - maxPeriod from frame count and sample rate (MIXER only)
3711
3712The parameters that affect these derived values are:
3713 - frame count
3714 - frame size
3715 - sample rate
3716 - device type: A2DP or not
3717 - device latency
3718 - format: PCM or not
3719 - active sleep time
3720 - idle sleep time
3721*/
3722
Andy Hungee58e4a2023-07-07 13:47:37 -07003723void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003724{
Andy Hung25c2dac2014-02-27 14:56:00 -08003725 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003726 mActiveSleepTimeUs = activeSleepTimeUs();
3727 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003728
Andy Hung8fe87eb2023-07-20 21:31:38 -07003729 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003730
Eric Laurent42537be2016-01-08 17:16:42 -08003731 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3732 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003733 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003734 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3735 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3736 }
3737 }
Eric Laurent81784c32012-11-19 14:55:58 -08003738}
3739
Andy Hungee58e4a2023-07-07 13:47:37 -07003740bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003741{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003742 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003743 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003744 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003745 size_t size = mTracks.size();
3746 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003747 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003748 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003749 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003750 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003751 }
3752 }
Eric Laurent13084622016-05-17 10:51:49 -07003753 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003754}
3755
Andy Hungee58e4a2023-07-07 13:47:37 -07003756void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003757{
Andy Hung972bec12023-08-31 16:13:39 -07003758 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003759 invalidateTracks_l(streamType);
3760}
3761
Andy Hungee58e4a2023-07-07 13:47:37 -07003762void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003763 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003764 invalidateTracks_l(portIds);
3765}
3766
Andy Hungee58e4a2023-07-07 13:47:37 -07003767bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003768 bool trackMatch = false;
3769 const size_t size = mTracks.size();
3770 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003771 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003772 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3773 t->invalidate();
3774 portIds.erase(t->portId());
3775 trackMatch = true;
3776 }
3777 if (portIds.empty()) {
3778 break;
3779 }
3780 }
3781 return trackMatch;
3782}
3783
jiabinf042b9b2021-05-07 23:46:28 +00003784// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003785IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003786 audio_port_handle_t trackPortId) {
3787 for (size_t i = 0; i < mTracks.size(); i++) {
3788 if (mTracks[i]->portId() == trackPortId) {
3789 return mTracks[i].get();
3790 }
3791 }
3792 return nullptr;
3793}
3794
Andy Hungee58e4a2023-07-07 13:47:37 -07003795status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003796{
Glenn Kastend848eb42016-03-08 13:42:11 -08003797 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003798 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003799 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003800
Andy Hungd3639922022-04-28 18:00:49 -07003801 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003802 if (!audio_is_global_session(session)) {
3803 // player sessions on a spatializer output will use a dedicated input buffer and
3804 // will either output multi channel to mEffectBuffer if the track is spatilaized
3805 // or stereo to mPostSpatializerBuffer if not spatialized.
3806 uint32_t channelMask;
3807 bool isSessionSpatialized =
3808 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3809 if (isSessionSpatialized) {
3810 channelMask = mMixerChannelMask;
3811 } else {
3812 channelMask = mChannelMask;
3813 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003814 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003815 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003816 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003817 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003818 &halInBuffer);
3819 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003820
Andy Hung583043b2023-07-17 17:05:00 -07003821 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003822 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3823 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3824 &halOutBuffer);
3825 if (result != OK) return result;
3826
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003827 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003828
Mikhail Naganov022b9952017-01-04 16:36:51 -08003829 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3830 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003831 } else {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003832 status_t result = INVALID_OPERATION;
3833 // Buffer configuration for global sessions on a SPATIALIZER thread:
3834 // - AUDIO_SESSION_OUTPUT_MIX session uses the mEffectBuffer as input and output buffer
3835 // - AUDIO_SESSION_OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3836 // mPostSpatializerBuffer as output buffer
3837 // - AUDIO_SESSION_DEVICE session uses the mPostSpatializerBuffer as input and output
3838 // buffer
3839 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_OUTPUT_STAGE) {
3840 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3841 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3842 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003843
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003844 if (session == AUDIO_SESSION_OUTPUT_MIX) {
3845 halOutBuffer = halInBuffer;
3846 }
3847 }
3848
3849 if (session == AUDIO_SESSION_OUTPUT_STAGE || session == AUDIO_SESSION_DEVICE) {
3850 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3851 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3852 if (result != OK) return result;
3853
3854 if (session == AUDIO_SESSION_DEVICE) {
3855 halInBuffer = halOutBuffer;
3856 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003857 }
3858 }
3859 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003860 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003861 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3862 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3863 &halInBuffer);
3864 if (result != OK) return result;
3865 halOutBuffer = halInBuffer;
3866 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3867 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003868 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003869 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003870 // Only one effect chain can be present in direct output thread and it uses
3871 // the sink buffer as input
3872 if (mType != DIRECT) {
3873 size_t numSamples = mNormalFrameCount
3874 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3875 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003876 const status_t allocateStatus =
3877 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003878 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003879 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003880 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003881
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003882 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003883 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3884 buffer, session);
3885 }
3886 }
3887 }
3888
3889 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003890 // Attach all tracks with same session ID to this chain.
3891 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003892 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003893 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003894 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3895 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003896 track->setMainBuffer(buffer);
3897 chain->incTrackCnt();
3898 }
3899 }
3900
3901 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003902 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003903 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003904 ALOGV("addEffectChain_l() activating track %p on session %d",
3905 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003906 chain->incActiveTrackCnt();
3907 }
3908 }
3909 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003910
Eric Laurentaaa44472014-09-12 17:41:50 -07003911 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003912 chain->setInBuffer(halInBuffer);
3913 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003914 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3915 // chains list in order to be processed last as it contains output device effects.
3916 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3917 // processing effects specific to an output stream before effects applied to all streams
3918 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003919 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3920 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003921 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003922 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003923 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003924 // Effect chain for other sessions are inserted at beginning of effect
3925 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003926 // sessions is not important.
3927 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003928 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3929 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003930 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003931 size_t size = mEffectChains.size();
3932 size_t i = 0;
3933 for (i = 0; i < size; i++) {
3934 if (mEffectChains[i]->sessionId() < session) {
3935 break;
3936 }
3937 }
3938 mEffectChains.insertAt(chain, i);
3939 checkSuspendOnAddEffectChain_l(chain);
3940
3941 return NO_ERROR;
3942}
3943
Andy Hungee58e4a2023-07-07 13:47:37 -07003944size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003945{
Glenn Kastend848eb42016-03-08 13:42:11 -08003946 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003947
3948 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3949
3950 for (size_t i = 0; i < mEffectChains.size(); i++) {
3951 if (chain == mEffectChains[i]) {
3952 mEffectChains.removeAt(i);
3953 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003954 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003955 if (session == track->sessionId()) {
3956 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3957 chain.get(), session);
3958 chain->decActiveTrackCnt();
3959 }
3960 }
3961
3962 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003963 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003964 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003965 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003966 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003967 chain->decTrackCnt();
3968 }
3969 }
3970 break;
3971 }
3972 }
3973 return mEffectChains.size();
3974}
3975
Andy Hungee58e4a2023-07-07 13:47:37 -07003976status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003977 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003978{
Andy Hung972bec12023-08-31 16:13:39 -07003979 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003980 return attachAuxEffect_l(track, EffectId);
3981}
3982
Andy Hungee58e4a2023-07-07 13:47:37 -07003983status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003984 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003985{
3986 status_t status = NO_ERROR;
3987
3988 if (EffectId == 0) {
3989 track->setAuxBuffer(0, NULL);
3990 } else {
3991 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003992 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003993 if (effect != 0) {
3994 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3995 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3996 } else {
3997 status = INVALID_OPERATION;
3998 }
3999 } else {
4000 status = BAD_VALUE;
4001 }
4002 }
4003 return status;
4004}
4005
Andy Hungee58e4a2023-07-07 13:47:37 -07004006void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08004007{
4008 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004009 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004010 if (track->auxEffectId() == effectId) {
4011 attachAuxEffect_l(track, 0);
4012 }
4013 }
4014}
4015
Andy Hungee58e4a2023-07-07 13:47:37 -07004016bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07004017NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08004018{
Andy Hung78d8d952023-05-30 18:10:23 -07004019 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08004020
Andy Hung077d62e2023-10-03 10:49:34 -07004021 if (mType == SPATIALIZER) {
4022 const pid_t tid = getTid();
4023 if (tid == -1) { // odd: we are here, we must be a running thread.
4024 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4025 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004026 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4027 if (priorityBoost > 0) {
4028 stream()->setHalThreadPriority(priorityBoost);
4029 }
Andy Hung077d62e2023-10-03 10:49:34 -07004030 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004031 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4032 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4033 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4034 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4035 // only on ARC.
4036 const pid_t tid = getTid();
4037 if (tid == -1) {
4038 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4039 } else {
4040 const status_t status = requestPriority(getpid(),
4041 tid,
4042 kPriorityPlaybackThreadArc,
4043 false /* isForApp */,
4044 true /* asynchronous */);
4045 if (status != OK) {
4046 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4047 status);
4048 } else {
4049 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4050 }
4051 }
Andy Hung077d62e2023-10-03 10:49:34 -07004052 }
4053
Andy Hung8d31fd22023-06-26 19:20:57 -07004054 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004055
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004056 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004057 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004058
4059 // MIXER
4060 nsecs_t lastWarning = 0;
4061
4062 // DUPLICATING
4063 // FIXME could this be made local to while loop?
4064 writeFrames = 0;
4065
Andy Hung3f2cee62024-09-17 14:17:15 -07004066 {
4067 audio_utils::lock_guard l(mutex());
4068
4069 cacheParameters_l();
4070 checkSilentMode_l();
4071 }
4072
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004073 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004074
Andy Hungd3639922022-04-28 18:00:49 -07004075 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004076 sleepTimeShift = 0;
4077 }
4078
4079 CpuStats cpuStats;
4080 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4081
4082 acquireWakeLock();
4083
Glenn Kasteneef598c2017-04-03 14:41:13 -07004084 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4085 // thread associated with this PlaybackThread.
4086 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4087 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004088 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4089 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004090 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004091 const char *logString = NULL;
4092
rago1bb90822017-05-02 18:31:48 -07004093 // Estimated time for next buffer to be written to hal. This is used only on
4094 // suspended mode (for now) to help schedule the wait time until next iteration.
4095 nsecs_t timeLoopNextNs = 0;
4096
Andy Hung2dbffc22018-08-08 18:50:41 -07004097 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004098
Eric Laurentb3f315a2021-07-13 15:09:05 +02004099 sendCheckOutputStageEffectsEvent();
4100
Andy Hung446f4df2019-02-21 12:26:41 -08004101 // loopCount is used for statistics and diagnostics.
4102 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004103 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004104 // Log merge requests are performed during AudioFlinger binder transactions, but
4105 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004106 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004107
Eric Laurent81784c32012-11-19 14:55:58 -08004108 cpuStats.sample(myName);
4109
Andy Hung116bc262023-06-20 18:56:17 -07004110 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004111 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004112 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004113 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004114
Andy Hung2dbffc22018-08-08 18:50:41 -07004115 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4116 //
Andy Hungc5007f82023-08-29 14:26:09 -07004117 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004118 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004119 // Here, we try for the AF lock, but do not block on it as the latency
4120 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004121 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004122 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004123 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004124 status_t status = INVALID_OPERATION;
4125 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004126 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004127 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004128 && swPatches.size() > 0) {
4129 status = swPatches[0].getLatencyMs_l(&latencyMs);
4130 downstreamPatchHandle = swPatches[0].getPatchHandle();
4131 }
4132 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004133 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004134 lastDownstreamPatchHandle = downstreamPatchHandle;
4135 }
4136 if (status == OK) {
4137 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004138 // latency of 5 seconds).
4139 const double minLatency = 0., maxLatency = 5000.;
4140 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004141 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004142 } else {
4143 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004144 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004145 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004146 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004147 }
Andy Hung583043b2023-07-17 17:05:00 -07004148 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004149 }
4150 } else {
4151 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4152 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004153 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004154 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4155 }
4156 }
4157
Eric Laurentb3f315a2021-07-13 15:09:05 +02004158 if (mCheckOutputStageEffects.exchange(false)) {
4159 checkOutputStageEffects();
4160 }
4161
Vlad Popa7e81cea2023-01-19 16:34:16 +01004162 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004163 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004164
Andy Hungc5007f82023-08-29 14:26:09 -07004165 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004166
Eric Laurent021cf962014-05-13 10:18:14 -07004167 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004168 if (mCheckOutputStageEffects.load()) {
4169 continue;
4170 }
Eric Laurent10351942014-05-08 18:49:52 -07004171
Andy Hungc5007f82023-08-29 14:26:09 -07004172 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004173 if (logString != NULL) {
4174 mNBLogWriter->logTimestamp();
4175 mNBLogWriter->log(logString);
4176 logString = NULL;
4177 }
4178
Dean Wheatley12473e92021-03-18 23:00:55 +11004179 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004180
Eric Laurent81784c32012-11-19 14:55:58 -08004181 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004182 if (mSignalPending) {
4183 // A signal was raised while we were unlocked
4184 mSignalPending = false;
4185 } else if (waitingAsyncCallback_l()) {
4186 if (exitPending()) {
4187 break;
4188 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004189 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004190 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004191 releaseWakeLock_l();
4192 released = true;
4193 }
Andy Hung10cbff12017-02-21 17:30:14 -08004194
4195 const int64_t waitNs = computeWaitTimeNs_l();
4196 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004197 std::cv_status cvstatus =
4198 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4199 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004200 mSignalPending = true; // if timeout recheck everything
4201 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004202 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004203 if (released) {
4204 acquireWakeLock_l();
4205 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004206 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4207 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004208
4209 continue;
4210 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004211 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004212 isSuspended()) {
4213 // put audio hardware into standby after short delay
4214 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004215
4216 threadLoop_standby();
4217
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004218 // This is where we go into standby
4219 if (!mStandby) {
4220 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004221 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004222 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004223 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004224 }
Andy Hungd0979812019-02-21 15:51:44 -08004225 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004226 }
4227
Eric Tan39ec8d62018-07-24 09:49:29 -07004228 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004229 // we're about to wait, flush the binder command buffer
4230 IPCThreadState::self()->flushCommands();
4231
4232 clearOutputTracks();
4233
4234 if (exitPending()) {
4235 break;
4236 }
4237
4238 releaseWakeLock_l();
4239 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004240 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004241 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004242 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004243 acquireWakeLock_l();
4244
4245 mMixerStatus = MIXER_IDLE;
4246 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4247 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004248 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004249 checkSilentMode_l();
4250
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004251 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4252 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004253 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004254 sleepTimeShift = 0;
4255 }
4256
4257 continue;
4258 }
4259 }
Eric Laurent81784c32012-11-19 14:55:58 -08004260 // mMixerStatusIgnoringFastTracks is also updated internally
4261 mMixerStatus = prepareTracks_l(&tracksToRemove);
4262
Andy Hungab65b182023-09-06 19:41:47 -07004263 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004264
Vlad Popa7e81cea2023-01-19 16:34:16 +01004265 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004266
Andy Hungf302e812024-01-26 11:55:15 -08004267 // Acquire a local copy of active tracks with lock (release w/o lock).
4268 //
4269 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4270 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4271 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4272 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4273
4274 setHalLatencyMode_l();
4275
4276 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4277 // so this is done before we lock our effect chains.
4278 for (const auto& track : mActiveTracks) {
4279 track->updateTeePatches_l();
4280 }
4281
4282 // signal actual start of output stream when the render position reported by
4283 // the kernel starts moving.
4284 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4285 && (mKernelPositionOnStandby
4286 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4287 mHalStarted = true;
4288 mWaitHalStartCV.notify_all();
4289 }
4290
Eric Laurent81784c32012-11-19 14:55:58 -08004291 // prevent any changes in effect chain list and in each effect chain
4292 // during mixing and effect process as the audio buffers could be deleted
4293 // or modified if an effect is created or deleted
4294 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004295
4296 // Determine which session to pick up haptic data.
4297 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004298 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004299 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004300 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004301 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004302 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004303 if (effectChain != nullptr
4304 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004305 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004306 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004307 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004308 break;
4309 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004310 if (activeHapticSessionId == AUDIO_SESSION_NONE
4311 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004312 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004313 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004314 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004315 }
4316 }
4317 }
Andy Hungc5007f82023-08-29 14:26:09 -07004318 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004319
Eric Laurentbfb1b832013-01-07 09:53:42 -08004320 if (mBytesRemaining == 0) {
4321 mCurrentWriteLength = 0;
4322 if (mMixerStatus == MIXER_TRACKS_READY) {
4323 // threadLoop_mix() sets mCurrentWriteLength
4324 threadLoop_mix();
4325 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4326 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004327 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004328 // must be written to HAL
4329 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004330 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004331 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004332
4333 // Tally underrun frames as we are inserting 0s here.
4334 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004335 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004336 && !track->isStopped()
4337 && !track->isPaused()
4338 && !track->isTerminated()) {
4339 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4340 __func__, track->id(), track->getTrackStateAsString(),
4341 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004342 track->audioTrackServerProxy()->tallyUnderrunFrames(
4343 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004344 }
4345 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004346 }
4347 }
Andy Hung98ef9782014-03-04 14:46:50 -08004348 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004349 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004350 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004351 // or mSinkBuffer (if there are no effects and there is no data already copied to
4352 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004353 //
4354 // This is done pre-effects computation; if effects change to
4355 // support higher precision, this needs to move.
4356 //
4357 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004358 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004359 uint32_t mixerChannelCount = mEffectBufferValid ?
4360 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004361 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004362 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4363 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4364
David Li88ee0902022-06-22 10:01:21 +08004365 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4366 // do these processes after effects are applied.
4367 if (!mEffectBufferValid) {
4368 // mono blend occurs for mixer threads only (not direct or offloaded)
4369 // and is handled here if we're going directly to the sink.
4370 if (requireMonoBlend()) {
4371 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4372 mNormalFrameCount, true /*limit*/);
4373 }
Andy Hung2ddee192015-12-18 17:34:44 -08004374
David Li88ee0902022-06-22 10:01:21 +08004375 if (!hasFastMixer()) {
4376 // Balance must take effect after mono conversion.
4377 // We do it here if there is no FastMixer.
4378 // mBalance detects zero balance within the class for speed
4379 // (not needed here).
4380 mBalance.setBalance(mMasterBalance.load());
4381 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4382 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004383 }
4384
Andy Hung98ef9782014-03-04 14:46:50 -08004385 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004386 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004387
4388 // If we're going directly to the sink and there are haptic channels,
4389 // we should adjust channels as the sample data is partially interleaved
4390 // in this case.
4391 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4392 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4393 mChannelCount + mHapticChannelCount,
4394 audio_bytes_per_sample(format),
4395 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4396 }
Andy Hung98ef9782014-03-04 14:46:50 -08004397 }
4398
Eric Laurentbfb1b832013-01-07 09:53:42 -08004399 mBytesRemaining = mCurrentWriteLength;
4400 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004401 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4402 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4403 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4404 mBytesWritten += mBytesRemaining;
4405 mFramesWritten += framesRemaining;
4406 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004407 mBytesRemaining = 0;
4408 }
Eric Laurent81784c32012-11-19 14:55:58 -08004409
Eric Laurentbfb1b832013-01-07 09:53:42 -08004410 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004411 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004412 for (size_t i = 0; i < effectChains.size(); i ++) {
4413 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004414 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004415 if (activeHapticSessionId != AUDIO_SESSION_NONE
4416 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004417 // Haptic data is active in this case, copy it directly from
4418 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004419 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4420 audio_channel_count_from_out_mask(mMixerChannelMask) :
4421 mChannelCount;
4422 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4423 hapticSessionChannelCount = mChannelCount;
4424 }
4425
jiabin47affe52019-04-04 18:02:07 -07004426 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004427 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004428 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004429 memcpy_by_audio_format(
4430 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004431 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004432 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004433 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004434 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004435 }
Eric Laurent81784c32012-11-19 14:55:58 -08004436 }
4437 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004438 // Process effect chains for offloaded thread even if no audio
4439 // was read from audio track: process only updates effect state
4440 // and thus does have to be synchronized with audio writes but may have
4441 // to be called while waiting for async write callback
4442 if (mType == OFFLOAD) {
4443 for (size_t i = 0; i < effectChains.size(); i ++) {
4444 effectChains[i]->process_l();
4445 }
4446 }
Eric Laurent81784c32012-11-19 14:55:58 -08004447
Andy Hung98ef9782014-03-04 14:46:50 -08004448 // Only if the Effects buffer is enabled and there is data in the
4449 // Effects buffer (buffer valid), we need to
4450 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004451 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004452 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004453 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004454 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004455 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004456 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004457 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004458 }
4459
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004460 if (!hasFastMixer()) {
4461 // Balance must take effect after mono conversion.
4462 // We do it here if there is no FastMixer.
4463 // mBalance detects zero balance within the class for speed (not needed here).
4464 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004465 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004466 }
4467
Eric Laurentb62d0362021-10-26 17:40:18 +02004468 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4469 // mPostSpatializerBuffer if the haptics track is spatialized.
4470 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4471 // For other thread types, the haptics channels are already in mEffectBuffer.
4472 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4473 const size_t srcBufferSize = mNormalFrameCount *
4474 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4475 mEffectBufferFormat);
4476 const size_t dstBufferSize = mNormalFrameCount
4477 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4478
4479 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4480 mEffectBufferFormat,
4481 (uint8_t*)mEffectBuffer + srcBufferSize,
4482 mEffectBufferFormat,
4483 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004484 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004485 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4486 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4487 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4488 // Clamp PCM float values more than this distance from 0 to insulate
4489 // a HAL which doesn't handle NaN correctly.
4490 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4491 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4492 static_cast<const float*>(effectBuffer),
4493 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4494 } else {
4495 memcpy_by_audio_format(mSinkBuffer, mFormat,
4496 effectBuffer, mEffectBufferFormat, framesToCopy);
4497 }
jiabin245cdd92018-12-07 17:55:15 -08004498 // The sample data is partially interleaved when haptic channels exist,
4499 // we need to adjust channels here.
4500 if (mHapticChannelCount > 0) {
4501 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4502 mChannelCount + mHapticChannelCount,
4503 audio_bytes_per_sample(mFormat),
4504 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4505 }
Andy Hung98ef9782014-03-04 14:46:50 -08004506 }
4507
Eric Laurent81784c32012-11-19 14:55:58 -08004508 // enable changes in effect chain
4509 unlockEffectChains(effectChains);
4510
Vlad Popafce10862023-02-03 10:37:07 +01004511 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004512 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004513 metadataUpdate.playbackMetadataUpdate);
4514 }
4515
Eric Laurentbfb1b832013-01-07 09:53:42 -08004516 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004517 // mSleepTimeUs == 0 means we must write to audio hardware
4518 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004519 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004520 // writePeriodNs is updated >= 0 when ret > 0.
4521 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004523 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004524 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004525 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004526 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004527 if (ret < 0) {
4528 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004529 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004530 mBytesWritten += ret;
4531 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004532 const int64_t frames = ret / mFrameSize;
4533 mFramesWritten += frames;
4534
4535 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4536 // process information relating to write time.
4537 if (audio_has_proportional_frames(mFormat)) {
4538 // we are in a continuous mixing cycle
4539 if (mMixerStatus == MIXER_TRACKS_READY &&
4540 loopCount == lastLoopCountWritten + 1) {
4541
4542 const double jitterMs =
4543 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4544 {frames, writePeriodNs},
4545 {0, 0} /* lastTimestamp */, mSampleRate);
4546 const double processMs =
4547 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4548
Andy Hung972bec12023-08-31 16:13:39 -07004549 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004550 mIoJitterMs.add(jitterMs);
4551 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004552
4553 if (mPipeSink.get() != nullptr) {
4554 // Using the Monopipe availableToWrite, we estimate the current
4555 // buffer size.
4556 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4557 const ssize_t
4558 availableToWrite = mPipeSink->availableToWrite();
4559 const size_t pipeFrames = monoPipe->maxFrames();
4560 const size_t
4561 remainingFrames = pipeFrames - max(availableToWrite, 0);
4562 mMonopipePipeDepthStats.add(remainingFrames);
4563 }
Andy Hung446f4df2019-02-21 12:26:41 -08004564 }
4565
4566 // write blocked detection
4567 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004568 if ((mType == MIXER || mType == SPATIALIZER)
4569 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004570 mNumDelayedWrites++;
4571 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4572 ATRACE_NAME("underrun");
4573 ALOGW("write blocked for %lld msecs, "
4574 "%d delayed writes, thread %d",
4575 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4576 mNumDelayedWrites, mId);
4577 lastWarning = lastIoEndNs;
4578 }
4579 }
4580 }
4581 // update timing info.
4582 mLastIoBeginNs = lastIoBeginNs;
4583 mLastIoEndNs = lastIoEndNs;
4584 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004585 }
4586 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4587 (mMixerStatus == MIXER_DRAIN_ALL)) {
4588 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004589 }
Andy Hungd3639922022-04-28 18:00:49 -07004590 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004591
4592 if (mThreadThrottle
4593 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004594 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004595 // Limit MixerThread data processing to no more than twice the
4596 // expected processing rate.
4597 //
4598 // This helps prevent underruns with NuPlayer and other applications
4599 // which may set up buffers that are close to the minimum size, or use
4600 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4601 //
4602 // The throttle smooths out sudden large data drains from the device,
4603 // e.g. when it comes out of standby, which often causes problems with
4604 // (1) mixer threads without a fast mixer (which has its own warm-up)
4605 // (2) minimum buffer sized tracks (even if the track is full,
4606 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004607 //
4608 // Total time spent in last processing cycle equals time spent in
4609 // 1. threadLoop_write, as well as time spent in
4610 // 2. threadLoop_mix (significant for heavy mixing, especially
4611 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004612
Andy Hung446f4df2019-02-21 12:26:41 -08004613 // it's OK if deltaMs is an overestimate.
4614
4615 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004616
Ivan Lozanoea04d392017-11-07 14:37:07 -08004617 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004618 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004619 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004620
Andy Hung08fb1742015-05-31 23:22:10 -07004621 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004622 // notify of throttle start on verbose log
4623 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4624 "mixer(%p) throttle begin:"
4625 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004626 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004627 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004628 // Throttle must be attributed to the previous mixer loop's write time
4629 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004630 // This also ensures proper timing statistics.
4631 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004632 } else {
4633 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4634 if (diff > 0) {
4635 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004636 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004637 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004638 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004639 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004640 outDeviceTypes_l(),
4641 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004642 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004643 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4644 }
Andy Hung08fb1742015-05-31 23:22:10 -07004645 }
4646 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004647 }
Eric Laurent81784c32012-11-19 14:55:58 -08004648
Eric Laurentbfb1b832013-01-07 09:53:42 -08004649 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004650 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004651 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004652 // suspended requires accurate metering of sleep time.
4653 if (isSuspended()) {
4654 // advance by expected sleepTime
4655 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4656 const nsecs_t nowNs = systemTime();
4657
4658 // compute expected next time vs current time.
4659 // (negative deltas are treated as delays).
4660 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4661 if (deltaNs < -kMaxNextBufferDelayNs) {
4662 // Delays longer than the max allowed trigger a reset.
4663 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4664 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4665 timeLoopNextNs = nowNs + deltaNs;
4666 } else if (deltaNs < 0) {
4667 // Delays within the max delay allowed: zero the delta/sleepTime
4668 // to help the system catch up in the next iteration(s)
4669 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4670 deltaNs = 0;
4671 }
4672 // update sleep time (which is >= 0)
4673 mSleepTimeUs = deltaNs / 1000;
4674 }
Eric Laurente93cc032016-05-05 10:15:10 -07004675 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004676 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004677 }
Glenn Kastene7754022014-10-31 12:11:26 -07004678 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004679 }
Eric Laurent81784c32012-11-19 14:55:58 -08004680 }
4681
4682 // Finally let go of removed track(s), without the lock held
4683 // since we can't guarantee the destructors won't acquire that
4684 // same lock. This will also mutate and push a new fast mixer state.
4685 threadLoop_removeTracks(tracksToRemove);
4686 tracksToRemove.clear();
4687
4688 // FIXME I don't understand the need for this here;
4689 // it was in the original code but maybe the
4690 // assignment in saveOutputTracks() makes this unnecessary?
4691 clearOutputTracks();
4692
4693 // Effect chains will be actually deleted here if they were removed from
4694 // mEffectChains list during mixing or effects processing
4695 effectChains.clear();
4696
4697 // FIXME Note that the above .clear() is no longer necessary since effectChains
4698 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004699
4700 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004701 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004702 mThreadloopExecutor.process(); // process any remaining deferred actions.
4703 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004704
Eric Laurentbfb1b832013-01-07 09:53:42 -08004705 threadLoop_exit();
4706
Eric Laurentcf817a22014-08-04 20:36:31 -07004707 if (!mStandby) {
4708 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004709 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004710 }
4711
4712 releaseWakeLock();
4713
4714 ALOGV("Thread %p type %d exiting", this, mType);
4715 return false;
4716}
4717
Andy Hungee58e4a2023-07-07 13:47:37 -07004718void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004719{
Dean Wheatley12473e92021-03-18 23:00:55 +11004720 if (mStandby) {
4721 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4722 return;
4723 } else if (mHwPaused) {
4724 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4725 return;
4726 }
4727
4728 // Gather the framesReleased counters for all active tracks,
4729 // and associate with the sink frames written out. We need
4730 // this to convert the sink timestamp to the track timestamp.
4731 bool kernelLocationUpdate = false;
4732 ExtendedTimestamp timestamp; // use private copy to fetch
4733
4734 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4735 // HAL may be draining some small duration buffered data for fade out.
4736 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4737 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4738 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4739 mSampleRate);
4740
Andy Hungab65b182023-09-06 19:41:47 -07004741 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004742 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4743 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4744 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4745 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4746 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4747 = correctedTimestamp.mFrames;
4748 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4749 = correctedTimestamp.mTimeNs;
4750 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4751 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4752 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4753
4754 // Note: Downstream latency only added if timestamp correction enabled.
4755 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4756 const int64_t newPosition =
4757 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4758 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4759 // prevent retrograde
4760 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4761 newPosition,
4762 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4763 - mSuspendedFrames));
4764 }
4765 }
4766
4767 // We always fetch the timestamp here because often the downstream
4768 // sink will block while writing.
4769
4770 // We keep track of the last valid kernel position in case we are in underrun
4771 // and the normal mixer period is the same as the fast mixer period, or there
4772 // is some error from the HAL.
4773 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4774 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4775 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4776 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4777 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4778
4779 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4780 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4781 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4782 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4783 }
4784
4785 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4786 kernelLocationUpdate = true;
4787 } else {
4788 ALOGVV("getTimestamp error - no valid kernel position");
4789 }
4790
4791 // copy over kernel info
4792 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4793 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4794 + mSuspendedFrames; // add frames discarded when suspended
4795 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4796 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4797 } else {
4798 mTimestampVerifier.error();
4799 }
4800
4801 // mFramesWritten for non-offloaded tracks are contiguous
4802 // even after standby() is called. This is useful for the track frame
4803 // to sink frame mapping.
4804 bool serverLocationUpdate = false;
4805 if (mFramesWritten != mLastFramesWritten) {
4806 serverLocationUpdate = true;
4807 mLastFramesWritten = mFramesWritten;
4808 }
4809 // Only update timestamps if there is a meaningful change.
4810 // Either the kernel timestamp must be valid or we have written something.
4811 if (kernelLocationUpdate || serverLocationUpdate) {
4812 if (serverLocationUpdate) {
4813 // use the time before we called the HAL write - it is a bit more accurate
4814 // to when the server last read data than the current time here.
4815 //
4816 // If we haven't written anything, mLastIoBeginNs will be -1
4817 // and we use systemTime().
4818 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4819 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004820 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004821 }
4822
Andy Hung8d31fd22023-06-26 19:20:57 -07004823 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004824 if (!t->isFastTrack()) {
4825 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004826 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004827 mFramesWritten,
4828 mSampleRate,
4829 mTimestamp);
4830 }
4831 }
4832 }
4833
4834 if (audio_has_proportional_frames(mFormat)) {
4835 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4836 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4837 mLatencyMs.add(latencyMs);
4838 }
4839 }
4840#if 0
4841 // logFormat example
4842 if (z % 100 == 0) {
4843 timespec ts;
4844 clock_gettime(CLOCK_MONOTONIC, &ts);
4845 LOGT("This is an integer %d, this is a float %f, this is my "
4846 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4847 LOGT("A deceptive null-terminated string %\0");
4848 }
4849 ++z;
4850#endif
4851}
4852
Andy Hungc5007f82023-08-29 14:26:09 -07004853// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004854void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004855NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004856{
Andy Hung6c498e92023-12-05 17:28:17 -08004857 if (tracksToRemove.empty()) return;
4858
4859 // Block all incoming TrackHandle requests until we are finished with the release.
4860 setThreadBusy_l(true);
4861
Andy Hungfe726a62018-09-27 15:17:25 -07004862 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004863 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004864 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004865 if (chain != 0) {
4866 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4867 __func__, track->id(), chain.get(), track->sessionId());
4868 chain->decActiveTrackCnt();
4869 }
Andy Hung6c498e92023-12-05 17:28:17 -08004870
Andy Hungfe726a62018-09-27 15:17:25 -07004871 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004872 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004873 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004874 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004875 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004876 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004877 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004878 }
Andy Hung6c498e92023-12-05 17:28:17 -08004879 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004880 }
jiabineb3bda02020-06-30 14:07:03 -07004881 if (mHapticChannelCount > 0 &&
4882 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004883 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004884 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004885 // Unlock due to VibratorService will lock for this call and will
4886 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004887 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004888 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004889
4890 // When the track is stop, set the haptic intensity as MUTE
4891 // for the HapticGenerator effect.
4892 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004893 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004894 }
jiabin245cdd92018-12-07 17:55:15 -08004895 }
Andy Hung6c498e92023-12-05 17:28:17 -08004896
4897 // Under lock, the track is removed from the active tracks list.
4898 //
4899 // Once the track is no longer active, the TrackHandle may directly
4900 // modify it as the threadLoop() is no longer responsible for its maintenance.
4901 // Do not modify the track from threadLoop after the mutex is unlocked
4902 // if it is not active.
4903 mActiveTracks.remove(track);
4904
4905 if (track->isTerminated()) {
4906 // remove from our tracks vector
4907 removeTrack_l(track);
4908 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004909 }
Andy Hung6c498e92023-12-05 17:28:17 -08004910
4911 // Allow incoming TrackHandle requests. We still hold the mutex,
4912 // so pending TrackHandle requests will occur after we unlock it.
4913 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004914}
Eric Laurent81784c32012-11-19 14:55:58 -08004915
Andy Hungee58e4a2023-07-07 13:47:37 -07004916status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004917{
4918 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004919 ExtendedTimestamp ets;
4920 status_t status = mNormalSink->getTimestamp(ets);
4921 if (status == NO_ERROR) {
4922 status = ets.getBestTimestamp(&timestamp);
4923 }
4924 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004925 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004926 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004927 collectTimestamps_l();
4928 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4929 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004930 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004931 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4932 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4933 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4934 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4935 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004936 }
4937 return INVALID_OPERATION;
4938}
Eric Laurent1c333e22014-05-20 10:48:17 -07004939
Eric Laurenteab90452019-06-24 15:17:46 -07004940// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4941// still applied by the mixer.
4942// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4943// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4944// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004945status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004946{
4947 status_t result = NO_ERROR;
4948 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4949 if (*volume != mLeftVolFloat) {
4950 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004951 // HAL can return INVALID_OPERATION if operation is not supported.
4952 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004953 "Error when setting output stream volume: %d", result);
4954 if (result == NO_ERROR) {
4955 mLeftVolFloat = *volume;
4956 }
4957 }
4958 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4959 // remove stream volume contribution from software volume.
4960 if (mLeftVolFloat == *volume) {
4961 *volume = 1.0f;
4962 }
4963 }
4964 return result;
4965}
4966
Andy Hungee58e4a2023-07-07 13:47:37 -07004967status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004968 audio_patch_handle_t *handle)
4969{
Andy Hungf60abce2016-08-26 11:37:54 -07004970 status_t status;
4971 if (property_get_bool("af.patch_park", false /* default_value */)) {
4972 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4973 // or if HAL does not properly lock against access.
4974 AutoPark<FastMixer> park(mFastMixer);
4975 status = PlaybackThread::createAudioPatch_l(patch, handle);
4976 } else {
4977 status = PlaybackThread::createAudioPatch_l(patch, handle);
4978 }
Eric Laurentb0463942022-12-20 16:31:10 +01004979
4980 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004981 return status;
4982}
4983
Andy Hungee58e4a2023-07-07 13:47:37 -07004984status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004985 audio_patch_handle_t *handle)
4986{
4987 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004988
4989 // store new device and send to effects
4990 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004991 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004992 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004993 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4994 && !mOutput->audioHwDev->supportsAudioPatches(),
4995 "Enumerated device type(%#x) must not be used "
4996 "as it does not support audio patches",
4997 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004998 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004999 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
5000 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07005001 }
5002
François Gaffie0c280aa2018-07-25 10:02:15 +02005003 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07005004#ifdef ADD_BATTERY_DATA
5005 // when changing the audio output device, call addBatteryData to notify
5006 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07005007 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005008 uint32_t params = 0;
5009 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07005010 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005011 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07005012 }
5013
Eric Laurent054d9d32015-04-24 08:48:48 -07005014 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07005015 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005016 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5017 }
5018
5019 if (params != 0) {
5020 addBatteryData(params);
5021 }
5022 }
5023#endif
5024
5025 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08005026 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005027 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005028
jiabinc52b1ff2019-10-31 17:20:42 -07005029 // mPatch.num_sinks is not set when the thread is created so that
5030 // the first patch creation triggers an ioConfigChanged callback
5031 bool configChanged = (mPatch.num_sinks == 0) ||
5032 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005033 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005034 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005035 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005036
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005037 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005038 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5039 status = hwDevice->createAudioPatch(patch->num_sources,
5040 patch->sources,
5041 patch->num_sinks,
5042 patch->sinks,
5043 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005044 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005045 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005046 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005047 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005048 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005049
5050 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005051 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005052 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005053 // also dispatch to active AudioTracks for MediaMetrics
5054 for (const auto &track : mActiveTracks) {
5055 track->logEndInterval();
5056 track->logBeginInterval(patchSinksAsString);
5057 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005058
Eric Laurente8726fe2015-06-26 09:39:24 -07005059 if (configChanged) {
5060 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5061 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005062 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005063 mActiveTracks.setHasChanged();
5064
Eric Laurent1c333e22014-05-20 10:48:17 -07005065 return status;
5066}
5067
Andy Hungee58e4a2023-07-07 13:47:37 -07005068status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005069{
Andy Hungf60abce2016-08-26 11:37:54 -07005070 status_t status;
5071 if (property_get_bool("af.patch_park", false /* default_value */)) {
5072 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5073 // or if HAL does not properly lock against access.
5074 AutoPark<FastMixer> park(mFastMixer);
5075 status = PlaybackThread::releaseAudioPatch_l(handle);
5076 } else {
5077 status = PlaybackThread::releaseAudioPatch_l(handle);
5078 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005079 return status;
5080}
5081
Andy Hungee58e4a2023-07-07 13:47:37 -07005082status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005083{
5084 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005085
jiabinc52b1ff2019-10-31 17:20:42 -07005086 mPatch = audio_patch{};
5087 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005088
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005089 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005090 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5091 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005092 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005093 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005094 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005095 // Force meteadata update after a route change
5096 mActiveTracks.setHasChanged();
5097
Eric Laurent1c333e22014-05-20 10:48:17 -07005098 return status;
5099}
5100
Andy Hungee58e4a2023-07-07 13:47:37 -07005101void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005102{
Andy Hung972bec12023-08-31 16:13:39 -07005103 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005104 mTracks.add(track);
5105}
5106
Andy Hungee58e4a2023-07-07 13:47:37 -07005107void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005108{
Andy Hung972bec12023-08-31 16:13:39 -07005109 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005110 destroyTrack_l(track);
5111}
5112
Andy Hungee58e4a2023-07-07 13:47:37 -07005113void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005114{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005115 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005116 config->role = AUDIO_PORT_ROLE_SOURCE;
5117 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5118 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005119 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5120 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5121 config->flags.output = mOutput->flags;
5122 }
Eric Laurent83b88082014-06-20 18:31:16 -07005123}
5124
Atneya Nairaa3afcb2024-10-08 16:36:19 -07005125std::string PlaybackThread::getLocalLogHeader() const {
5126 using namespace std::literals;
5127 static constexpr auto indent = " "
5128 " "sv;
5129 return std::string{indent}.append(IAfTrack::getLogHeader());
5130}
Eric Laurent81784c32012-11-19 14:55:58 -08005131// ----------------------------------------------------------------------------
5132
Andy Hungee58e4a2023-07-07 13:47:37 -07005133/* static */
5134sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005135 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005136 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005137 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005138}
5139
Andy Hung583043b2023-07-17 17:05:00 -07005140MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005141 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005142 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005143 // mAudioMixer below
5144 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005145 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005146 mFastMixerFutex(0),
5147 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005148 // mOutputSink below
5149 // mPipeSink below
5150 // mNormalSink below
5151{
jiabinc52b1ff2019-10-31 17:20:42 -07005152 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005153 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005154 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005155 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5156 mNormalFrameCount);
5157 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5158
Andy Hungfbfc3952015-01-15 13:33:51 -08005159 if (type == DUPLICATING) {
5160 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5161 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5162 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005163 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5164 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005165 return;
5166 }
Eric Laurent81784c32012-11-19 14:55:58 -08005167 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005168 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005169 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005170 const NBAIO_Format offers[1] = {Format_from_SR_C(
5171 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005172#if !LOG_NDEBUG
5173 ssize_t index =
5174#else
5175 (void)
5176#endif
5177 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005178 ALOG_ASSERT(index == 0);
5179
5180 // initialize fast mixer depending on configuration
5181 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005182 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005183 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005184 } else {
5185 switch (kUseFastMixer) {
5186 case FastMixer_Never:
5187 initFastMixer = false;
5188 break;
5189 case FastMixer_Always:
5190 initFastMixer = true;
5191 break;
5192 case FastMixer_Static:
5193 case FastMixer_Dynamic:
5194 initFastMixer = mFrameCount < mNormalFrameCount;
5195 break;
5196 }
5197 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5198 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5199 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005200 }
5201 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005202 audio_format_t fastMixerFormat;
5203 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5204 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5205 } else {
5206 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5207 }
5208 if (mFormat != fastMixerFormat) {
5209 // change our Sink format to accept our intermediate precision
5210 mFormat = fastMixerFormat;
5211 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005212 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005213 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5214 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5215 }
Eric Laurent81784c32012-11-19 14:55:58 -08005216
5217 // create a MonoPipe to connect our submix to FastMixer
5218 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005219
Andy Hung1258c1a2014-05-23 21:22:17 -07005220 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005221 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005222 format.mFormat = fastMixerFormat;
5223 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5224
Eric Laurent81784c32012-11-19 14:55:58 -08005225 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5226 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5227 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5228 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005229 const NBAIO_Format offersFast[1] = {format};
5230 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005231#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005232 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005233#else
5234 (void)
5235#endif
Andy Hung920f6572022-10-06 12:09:49 -07005236 monoPipe->negotiate(offersFast, std::size(offersFast),
5237 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005238 ALOG_ASSERT(index == 0);
5239 monoPipe->setAvgFrames((mScreenState & 1) ?
5240 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5241 mPipeSink = monoPipe;
5242
Eric Laurent81784c32012-11-19 14:55:58 -08005243 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005244 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005245 FastMixerStateQueue *sq = mFastMixer->sq();
5246#ifdef STATE_QUEUE_DUMP
5247 sq->setObserverDump(&mStateQueueObserverDump);
5248 sq->setMutatorDump(&mStateQueueMutatorDump);
5249#endif
5250 FastMixerState *state = sq->begin();
5251 FastTrack *fastTrack = &state->mFastTracks[0];
5252 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5253 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5254 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005255 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5256 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5257 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005258 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005259 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005260 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005261 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005262 fastTrack->mGeneration++;
5263 state->mFastTracksGen++;
5264 state->mTrackMask = 1;
5265 // fast mixer will use the HAL output sink
5266 state->mOutputSink = mOutputSink.get();
5267 state->mOutputSinkGen++;
5268 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005269 // specify sink channel mask when haptic channel mask present as it can not
5270 // be calculated directly from channel count
5271 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005272 ? AUDIO_CHANNEL_NONE
5273 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005274 state->mCommand = FastMixerState::COLD_IDLE;
5275 // already done in constructor initialization list
5276 //mFastMixerFutex = 0;
5277 state->mColdFutexAddr = &mFastMixerFutex;
5278 state->mColdGen++;
5279 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005280 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005281 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005282 sq->end();
5283 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5284
Eric Tan0513b5d2018-09-17 10:32:48 -07005285 NBLog::thread_info_t info;
5286 info.id = mId;
5287 info.type = NBLog::FASTMIXER;
5288 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5289
Eric Laurent81784c32012-11-19 14:55:58 -08005290 // start the fast mixer
5291 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5292 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005293 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005294 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005295
5296#ifdef AUDIO_WATCHDOG
5297 // create and start the watchdog
5298 mAudioWatchdog = new AudioWatchdog();
5299 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5300 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5301 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005302 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005303#endif
Andy Hung8946a282018-04-19 20:04:56 -07005304 } else {
5305#ifdef TEE_SINK
5306 // Only use the MixerThread tee if there is no FastMixer.
5307 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5308 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5309#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005310 }
5311
5312 switch (kUseFastMixer) {
5313 case FastMixer_Never:
5314 case FastMixer_Dynamic:
5315 mNormalSink = mOutputSink;
5316 break;
5317 case FastMixer_Always:
5318 mNormalSink = mPipeSink;
5319 break;
5320 case FastMixer_Static:
5321 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5322 break;
5323 }
Andy Hung922617c2024-06-25 17:07:58 -07005324 // setMasterBalance needs to be called after the FastMixer
5325 // (if any) is set up, in order to deliver the balance settings to it.
5326 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005327}
5328
Andy Hungee58e4a2023-07-07 13:47:37 -07005329MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005330{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005331 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005332 FastMixerStateQueue *sq = mFastMixer->sq();
5333 FastMixerState *state = sq->begin();
5334 if (state->mCommand == FastMixerState::COLD_IDLE) {
5335 int32_t old = android_atomic_inc(&mFastMixerFutex);
5336 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005337 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005338 }
5339 }
5340 state->mCommand = FastMixerState::EXIT;
5341 sq->end();
5342 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5343 mFastMixer->join();
5344 // Though the fast mixer thread has exited, it's state queue is still valid.
5345 // We'll use that extract the final state which contains one remaining fast track
5346 // corresponding to our sub-mix.
5347 state = sq->begin();
5348 ALOG_ASSERT(state->mTrackMask == 1);
5349 FastTrack *fastTrack = &state->mFastTracks[0];
5350 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5351 delete fastTrack->mBufferProvider;
5352 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005353 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005354#ifdef AUDIO_WATCHDOG
5355 if (mAudioWatchdog != 0) {
5356 mAudioWatchdog->requestExit();
5357 mAudioWatchdog->requestExitAndWait();
5358 mAudioWatchdog.clear();
5359 }
5360#endif
5361 }
Andy Hung583043b2023-07-17 17:05:00 -07005362 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005363 delete mAudioMixer;
5364}
5365
Andy Hungee58e4a2023-07-07 13:47:37 -07005366void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005367 PlaybackThread::onFirstRef();
5368
Andy Hung972bec12023-08-31 16:13:39 -07005369 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005370 if (mOutput != nullptr && mOutput->stream != nullptr) {
5371 status_t status = mOutput->stream->setLatencyModeCallback(this);
5372 if (status != INVALID_OPERATION) {
5373 updateHalSupportedLatencyModes_l();
5374 }
5375 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5376 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5377 mBluetoothLatencyModesEnabled.store(
5378 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5379 }
5380}
Eric Laurent81784c32012-11-19 14:55:58 -08005381
Andy Hungee58e4a2023-07-07 13:47:37 -07005382uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005383{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005384 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005385 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5386 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5387 }
5388 return latency;
5389}
5390
Andy Hungee58e4a2023-07-07 13:47:37 -07005391ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005392{
5393 // FIXME we should only do one push per cycle; confirm this is true
5394 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005395 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005396 FastMixerStateQueue *sq = mFastMixer->sq();
5397 FastMixerState *state = sq->begin();
5398 if (state->mCommand != FastMixerState::MIX_WRITE &&
5399 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5400 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005401
5402 // FIXME workaround for first HAL write being CPU bound on some devices
5403 ATRACE_BEGIN("write");
5404 mOutput->write((char *)mSinkBuffer, 0);
5405 ATRACE_END();
5406
Eric Laurent81784c32012-11-19 14:55:58 -08005407 int32_t old = android_atomic_inc(&mFastMixerFutex);
5408 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005409 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005410 }
5411#ifdef AUDIO_WATCHDOG
5412 if (mAudioWatchdog != 0) {
5413 mAudioWatchdog->resume();
5414 }
5415#endif
5416 }
5417 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005418#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005419 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005420 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005421#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005422 sq->end();
5423 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5424 if (kUseFastMixer == FastMixer_Dynamic) {
5425 mNormalSink = mPipeSink;
5426 }
5427 } else {
5428 sq->end(false /*didModify*/);
5429 }
5430 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005431 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005432}
5433
Andy Hungee58e4a2023-07-07 13:47:37 -07005434void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005435{
5436 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005437 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005438 FastMixerStateQueue *sq = mFastMixer->sq();
5439 FastMixerState *state = sq->begin();
5440 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005441 // Report any frames trapped in the Monopipe
5442 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5443 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5444 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5445 "monoPipeWritten:%lld monoPipeLeft:%lld",
5446 (long long)mFramesWritten, (long long)mSuspendedFrames,
5447 (long long)mPipeSink->framesWritten(), pipeFrames);
5448 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5449
Eric Laurent81784c32012-11-19 14:55:58 -08005450 state->mCommand = FastMixerState::COLD_IDLE;
5451 state->mColdFutexAddr = &mFastMixerFutex;
5452 state->mColdGen++;
5453 mFastMixerFutex = 0;
5454 sq->end();
5455 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5456 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5457 if (kUseFastMixer == FastMixer_Dynamic) {
5458 mNormalSink = mOutputSink;
5459 }
5460#ifdef AUDIO_WATCHDOG
5461 if (mAudioWatchdog != 0) {
5462 mAudioWatchdog->pause();
5463 }
5464#endif
5465 } else {
5466 sq->end(false /*didModify*/);
5467 }
5468 }
5469 PlaybackThread::threadLoop_standby();
5470}
5471
Andy Hungee58e4a2023-07-07 13:47:37 -07005472bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005473{
5474 return false;
5475}
5476
Andy Hungee58e4a2023-07-07 13:47:37 -07005477bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005478{
5479 return !mStandby;
5480}
5481
Andy Hungee58e4a2023-07-07 13:47:37 -07005482bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005483{
Andy Hung972bec12023-08-31 16:13:39 -07005484 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005485 return waitingAsyncCallback_l();
5486}
5487
Eric Laurent81784c32012-11-19 14:55:58 -08005488// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005489void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005490{
Andy Hung8d672e02023-09-15 18:19:28 -07005491 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5492 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005493 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005494 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005495 // discard any pending drain or write ack by incrementing sequence
5496 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5497 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005498 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005499 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5500 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005501 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005502 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005503 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005504}
5505
Andy Hungee58e4a2023-07-07 13:47:37 -07005506void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005507{
5508 ALOGV("signal playback thread");
5509 broadcast_l();
5510}
5511
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005512void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005513{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005514 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005515 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5516 invalidateTracks((audio_stream_type_t)i);
5517 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005518 if (isHardError) {
5519 mAfThreadCallback->onHardError(allTrackPortIds);
5520 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005521}
5522
Andy Hungee58e4a2023-07-07 13:47:37 -07005523void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005524{
Eric Laurent81784c32012-11-19 14:55:58 -08005525 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005526 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005527 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005528 // increase sleep time progressively when application underrun condition clears.
5529 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5530 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5531 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005532 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005533 sleepTimeShift--;
5534 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005535 mSleepTimeUs = 0;
5536 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005537 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005538
Eric Laurent81784c32012-11-19 14:55:58 -08005539}
5540
Andy Hungee58e4a2023-07-07 13:47:37 -07005541void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005542{
5543 // If no tracks are ready, sleep once for the duration of an output
5544 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005545 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005546 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005547 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5548 // Using the Monopipe availableToWrite, we estimate the
5549 // sleep time to retry for more data (before we underrun).
5550 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5551 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5552 const size_t pipeFrames = monoPipe->maxFrames();
5553 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5554 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5555 const size_t framesDelay = std::min(
5556 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5557 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5558 pipeFrames, framesLeft, framesDelay);
5559 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5560 } else {
5561 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5562 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5563 mSleepTimeUs = kMinThreadSleepTimeUs;
5564 }
5565 // reduce sleep time in case of consecutive application underruns to avoid
5566 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5567 // duration we would end up writing less data than needed by the audio HAL if
5568 // the condition persists.
5569 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5570 sleepTimeShift++;
5571 }
Eric Laurent81784c32012-11-19 14:55:58 -08005572 }
5573 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005574 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005575 }
5576 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005577 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5578 // before effects processing or output.
5579 if (mMixerBufferValid) {
5580 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005581 if (mType == SPATIALIZER) {
5582 memset(mSinkBuffer, 0, mSinkBufferSize);
5583 }
Andy Hung98ef9782014-03-04 14:46:50 -08005584 } else {
5585 memset(mSinkBuffer, 0, mSinkBufferSize);
5586 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005587 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5589 "anticipated start");
5590 }
5591 // TODO add standby time extension fct of effect tail
5592}
5593
Andy Hungc5007f82023-08-29 14:26:09 -07005594// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005595PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005596 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005597{
Andy Hungc0691382018-09-12 18:01:57 -07005598 // clean up deleted track ids in AudioMixer before allocating new tracks
5599 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5600 // for each trackId, destroy it in the AudioMixer
5601 if (mAudioMixer->exists(trackId)) {
5602 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005603 }
5604 });
Andy Hungc0691382018-09-12 18:01:57 -07005605 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005606
5607 mixer_state mixerStatus = MIXER_IDLE;
5608 // find out which tracks need to be processed
5609 size_t count = mActiveTracks.size();
5610 size_t mixedTracks = 0;
5611 size_t tracksWithEffect = 0;
5612 // counts only _active_ fast tracks
5613 size_t fastTracks = 0;
5614 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5615
5616 float masterVolume = mMasterVolume;
5617 bool masterMute = mMasterMute;
5618
5619 if (masterMute) {
5620 masterVolume = 0;
5621 }
5622 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005623 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005624 if (chain != 0) {
5625 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005626 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005627 masterVolume = (float)((v + (1 << 23)) >> 24);
5628 chain.clear();
5629 }
5630
5631 // prepare a new state to push
5632 FastMixerStateQueue *sq = NULL;
5633 FastMixerState *state = NULL;
5634 bool didModify = false;
5635 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005636 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005637 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005638 sq = mFastMixer->sq();
5639 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005640 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005641 }
5642
Andy Hung69aed5f2014-02-25 17:24:40 -08005643 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005644 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005645
Andy Hungbd3b2b02018-05-21 10:53:11 -07005646 // DeferredOperations handles statistics after setting mixerStatus.
5647 class DeferredOperations {
5648 public:
Andy Hungea840382020-05-05 21:50:17 -07005649 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5650 : mMixerStatus(mixerStatus)
5651 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005652
5653 // when leaving scope, tally frames properly.
5654 ~DeferredOperations() {
5655 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5656 // because that is when the underrun occurs.
5657 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005658 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005659 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005660 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005661 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005662 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005663 }
5664 }
Andy Hungea840382020-05-05 21:50:17 -07005665 // send the max underrun frames for this mixer period
5666 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005667 }
5668
5669 // tallyUnderrunFrames() is called to update the track counters
5670 // with the number of underrun frames for a particular mixer period.
5671 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005672 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005673 mUnderrunFrames.emplace_back(track, underrunFrames);
5674 }
5675
5676 private:
5677 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005678 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005679 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005680 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005681 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005682
jiabin245cdd92018-12-07 17:55:15 -08005683 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005684 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005685 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005686
5687 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005688 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005689
5690 // process fast tracks
5691 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005692 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5693 "%s(%d): FastTrack(%d) present without FastMixer",
5694 __func__, id(), track->id());
5695
jiabin245cdd92018-12-07 17:55:15 -08005696 if (track->getHapticPlaybackEnabled()) {
5697 noFastHapticTrack = false;
5698 }
Eric Laurent81784c32012-11-19 14:55:58 -08005699
5700 // It's theoretically possible (though unlikely) for a fast track to be created
5701 // and then removed within the same normal mix cycle. This is not a problem, as
5702 // the track never becomes active so it's fast mixer slot is never touched.
5703 // The converse, of removing an (active) track and then creating a new track
5704 // at the identical fast mixer slot within the same normal mix cycle,
5705 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005706 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005707 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005708 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5709 FastTrack *fastTrack = &state->mFastTracks[j];
5710
5711 // Determine whether the track is currently in underrun condition,
5712 // and whether it had a recent underrun.
5713 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5714 FastTrackUnderruns underruns = ftDump->mUnderruns;
5715 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005716 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005717 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005718 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005719 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005720 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005721 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005722 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005723 // don't count underruns that occur while stopping or pausing
5724 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005725 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005726 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5727 recentUnderruns > 0) {
5728 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005729 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005730 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005731 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005732 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005733
5734 // This is similar to the state machine for normal tracks,
5735 // with a few modifications for fast tracks.
5736 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005737 switch (track->state()) {
5738 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005739 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005740 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005741 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005742 }
5743 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005744 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005745 // ramp down is not yet implemented
5746 track->setPaused();
5747 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005748 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005749 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005750 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005751 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005752 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005753 if (recentFull > 0 || recentPartial > 0) {
5754 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005755 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005756 }
5757 if (recentUnderruns == 0) {
5758 // no recent underruns: stay active
5759 break;
5760 }
5761 // there has recently been an underrun of some kind
5762 if (track->sharedBuffer() == 0) {
5763 // were any of the recent underruns "empty" (no frames available)?
5764 if (recentEmpty == 0) {
5765 // no, then ignore the partial underruns as they are allowed indefinitely
5766 break;
5767 }
5768 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005769 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005770 break;
5771 }
5772 // indicate to client process that the track was disabled because of underrun;
5773 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005774 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005775 // remove from active list, but state remains ACTIVE [confusing but true]
5776 isActive = false;
5777 break;
5778 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005779 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005780 case IAfTrackBase::STOPPING_2:
5781 case IAfTrackBase::PAUSED:
5782 case IAfTrackBase::STOPPED:
5783 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005784 // Check for presentation complete if track is inactive
5785 // We have consumed all the buffers of this track.
5786 // This would be incomplete if we auto-paused on underrun
5787 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005788 uint32_t latency = 0;
5789 status_t result = mOutput->stream->getLatency(&latency);
5790 ALOGE_IF(result != OK,
5791 "Error when retrieving output stream latency: %d", result);
5792 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005793 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005794 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5795 // track stays in active list until presentation is complete
5796 break;
5797 }
5798 }
5799 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005800 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005801 }
5802 if (track->isStopped()) {
5803 // Can't reset directly, as fast mixer is still polling this track
5804 // track->reset();
5805 // So instead mark this track as needing to be reset after push with ack
5806 resetMask |= 1 << i;
5807 }
5808 isActive = false;
5809 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005810 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005811 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005812 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005813 }
5814
5815 if (isActive) {
5816 // was it previously inactive?
5817 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005818 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5819 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005820 fastTrack->mBufferProvider = eabp;
5821 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005822 fastTrack->mChannelMask = track->channelMask();
5823 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005824 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005825 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005826 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005827 fastTrack->mGeneration++;
5828 state->mTrackMask |= 1 << j;
5829 didModify = true;
5830 // no acknowledgement required for newly active tracks
5831 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005832 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005833 float volume;
Andy Hung6b137d12024-08-27 22:35:17 +00005834 if (!audioserver_flags::portid_volume_management()) {
5835 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5836 volume = 0.f;
5837 } else {
5838 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5839 }
Eric Laurenteab90452019-06-24 15:17:46 -07005840 } else {
Andy Hung6b137d12024-08-27 22:35:17 +00005841 if (track->isPlaybackRestricted()) {
5842 volume = 0.f;
5843 } else {
5844 volume = masterVolume * track->getPortVolume();
5845 }
Eric Laurenteab90452019-06-24 15:17:46 -07005846 }
Eric Laurenteab90452019-06-24 15:17:46 -07005847 handleVoipVolume_l(&volume);
5848
Eric Laurent81784c32012-11-19 14:55:58 -08005849 // cache the combined master volume and stream type volume for fast mixer; this
5850 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005851 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005852 proxy->framesReleased()).first;
5853 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005854 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005855 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005856 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5857 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Andy Hung6b137d12024-08-27 22:35:17 +00005858 if (!audioserver_flags::portid_volume_management()) {
5859 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5860 /*muteState=*/{masterVolume == 0.f,
5861 mStreamTypes[track->streamType()].volume == 0.f,
5862 mStreamTypes[track->streamType()].mute,
5863 track->isPlaybackRestricted(),
5864 vlf == 0.f && vrf == 0.f,
5865 vh == 0.f});
5866 } else {
5867 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5868 /*muteState=*/{masterVolume == 0.f,
5869 track->getPortVolume() == 0.f,
5870 /* muteFromStreamMuted= */ false,
5871 track->isPlaybackRestricted(),
5872 vlf == 0.f && vrf == 0.f,
5873 vh == 0.f});
5874 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005875 vlf *= volume;
5876 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005877
jiabin220eea12024-05-17 17:55:20 +00005878 if (track->getInternalMute()) {
5879 vlf = 0.f;
5880 vrf = 0.f;
5881 }
5882
jiabin76d94692022-12-15 21:51:21 +00005883 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005884 ++fastTracks;
5885 } else {
5886 // was it previously active?
5887 if (state->mTrackMask & (1 << j)) {
5888 fastTrack->mBufferProvider = NULL;
5889 fastTrack->mGeneration++;
5890 state->mTrackMask &= ~(1 << j);
5891 didModify = true;
5892 // If any fast tracks were removed, we must wait for acknowledgement
5893 // because we're about to decrement the last sp<> on those tracks.
5894 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5895 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005896 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5897 // AudioTrack may start (which may not be with a start() but with a write()
5898 // after underrun) and immediately paused or released. In that case the
5899 // FastTrack state hasn't had time to update.
5900 // TODO Remove the ALOGW when this theory is confirmed.
5901 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005902 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005903 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005904 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005905 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005906 }
5907 tracksToRemove->add(track);
5908 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005909 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005910 }
jiabin245cdd92018-12-07 17:55:15 -08005911 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5912 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5913 didModify = true;
5914 }
Eric Laurent81784c32012-11-19 14:55:58 -08005915 continue;
5916 }
5917
5918 { // local variable scope to avoid goto warning
5919
5920 audio_track_cblk_t* cblk = track->cblk();
5921
5922 // The first time a track is added we wait
5923 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005924 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005925
5926 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005927 // use the trackId as the AudioMixer name.
5928 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005929 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005930 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005931 track->channelMask(),
5932 track->format(),
5933 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005934 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005935 ALOGW("%s(): AudioMixer cannot create track(%d)"
5936 " mask %#x, format %#x, sessionId %d",
5937 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005938 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005939 tracksToRemove->add(track);
5940 track->invalidate(); // consider it dead.
5941 continue;
5942 }
5943 }
5944
Eric Laurent81784c32012-11-19 14:55:58 -08005945 // make sure that we have enough frames to mix one full buffer.
5946 // enforce this condition only once to enable draining the buffer in case the client
5947 // app does not call stop() and relies on underrun to stop:
5948 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5949 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005950 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005951 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5952 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005953
5954 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005955 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005956 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5957 // add frames already consumed but not yet released by the resampler
5958 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005959 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005960
Eric Laurent81784c32012-11-19 14:55:58 -08005961 uint32_t minFrames = 1;
5962 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5963 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005964 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005965 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005966
5967 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005968 if (ATRACE_ENABLED()) {
5969 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005970 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005971 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005972 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005973 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005974 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005975 !track->isPaused() && !track->isTerminated())
5976 {
Andy Hungc0691382018-09-12 18:01:57 -07005977 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005978
5979 mixedTracks++;
5980
Shunkai Yaof4847652024-01-12 00:25:20 +00005981 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005982 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005983 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005984 if (track->mainBuffer() != mSinkBuffer &&
5985 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005986 if (mEffectBufferEnabled) {
5987 mEffectBufferValid = true; // Later can set directly.
5988 }
Eric Laurent81784c32012-11-19 14:55:58 -08005989 chain = getEffectChain_l(track->sessionId());
5990 // Delegate volume control to effect in track effect chain if needed
5991 if (chain != 0) {
5992 tracksWithEffect++;
5993 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005994 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005995 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005996 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005997 }
5998 }
5999
6000
6001 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07006002 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08006003 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07006004 track->fillingStatus() = IAfTrack::FS_ACTIVE;
6005 if (track->state() == IAfTrackBase::RESUMING) {
6006 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08006007 // If a new track is paused immediately after start, do not ramp on resume.
6008 if (cblk->mServer != 0) {
6009 param = AudioMixer::RAMP_VOLUME;
6010 }
Eric Laurent81784c32012-11-19 14:55:58 -08006011 }
Andy Hungc0691382018-09-12 18:01:57 -07006012 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07006013 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07006014 // FIXME should not make a decision based on mServer
6015 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006016 // If the track is stopped before the first frame was mixed,
6017 // do not apply ramp
6018 param = AudioMixer::RAMP_VOLUME;
6019 }
6020
6021 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07006022 uint32_t vl, vr; // in U8.24 integer format
6023 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07006024 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07006025 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07006026 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07006027 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07006028 track->audioTrackServerProxy()->framesReleased()).first;
Andy Hung6b137d12024-08-27 22:35:17 +00006029 float v;
6030 if (!audioserver_flags::portid_volume_management()) {
6031 v = masterVolume * mStreamTypes[track->streamType()].volume;
6032 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6033 v = 0;
6034 }
6035 } else {
6036 v = masterVolume * track->getPortVolume();
6037 if (track->isPlaybackRestricted()) {
6038 v = 0;
6039 }
Eric Laurenteab90452019-06-24 15:17:46 -07006040 }
Eric Laurenteab90452019-06-24 15:17:46 -07006041 handleVoipVolume_l(&v);
6042
6043 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006044 vl = vr = 0;
6045 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006046 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006047 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006048 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006049 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6050 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006051 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006052 if (vlf > GAIN_FLOAT_UNITY) {
6053 ALOGV("Track left volume out of range: %.3g", vlf);
6054 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006055 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006056 if (vrf > GAIN_FLOAT_UNITY) {
6057 ALOGV("Track right volume out of range: %.3g", vrf);
6058 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006059 }
Andy Hung6b137d12024-08-27 22:35:17 +00006060 if (!audioserver_flags::portid_volume_management()) {
6061 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6062 /*muteState=*/{masterVolume == 0.f,
6063 mStreamTypes[track->streamType()].volume == 0.f,
6064 mStreamTypes[track->streamType()].mute,
6065 track->isPlaybackRestricted(),
6066 vlf == 0.f && vrf == 0.f,
6067 vh == 0.f});
6068 } else {
6069 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6070 /*muteState=*/{masterVolume == 0.f,
6071 track->getPortVolume() == 0.f,
6072 /* muteFromStreamMuted= */ false,
6073 track->isPlaybackRestricted(),
6074 vlf == 0.f && vrf == 0.f,
6075 vh == 0.f});
6076 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006077 // now apply the master volume and stream type volume and shaper volume
6078 vlf *= v * vh;
6079 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006080 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006081 // then derive vl and vr as U8.24 versions for the effect chain
6082 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6083 vl = (uint32_t) (scaleto8_24 * vlf);
6084 vr = (uint32_t) (scaleto8_24 * vrf);
6085 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006086 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006087 // send level comes from shared memory and so may be corrupt
6088 if (sendLevel > MAX_GAIN_INT) {
6089 ALOGV("Track send level out of range: %04X", sendLevel);
6090 sendLevel = MAX_GAIN_INT;
6091 }
Andy Hung6be49402014-05-30 10:42:03 -07006092 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6093 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006094 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006095
jiabin220eea12024-05-17 17:55:20 +00006096 if (track->getInternalMute()) {
6097 vrf = 0.f;
6098 vlf = 0.f;
6099 }
6100
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006101 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006102
Eric Laurent81784c32012-11-19 14:55:58 -08006103 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006104 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006105 // Do not ramp volume if volume is controlled by effect
6106 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006107 // Update remaining floating point volume levels
6108 vlf = (float)vl / (1 << 24);
6109 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006110 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006111 } else {
6112 // force no volume ramp when volume controller was just disabled or removed
6113 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006114 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006115 param = AudioMixer::VOLUME;
6116 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006117 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006118 }
6119
Eric Laurent81784c32012-11-19 14:55:58 -08006120 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006121 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006122 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006123
Andy Hungc0691382018-09-12 18:01:57 -07006124 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6125 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6126 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006127 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006128 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006129 AudioMixer::TRACK,
6130 AudioMixer::FORMAT, (void *)track->format());
6131 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006132 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006133 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006134 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006135
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006136 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006137 mAudioMixer->setParameter(
6138 trackId,
6139 AudioMixer::TRACK,
6140 AudioMixer::MIXER_CHANNEL_MASK,
6141 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6142 } else {
6143 mAudioMixer->setParameter(
6144 trackId,
6145 AudioMixer::TRACK,
6146 AudioMixer::MIXER_CHANNEL_MASK,
6147 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6148 }
6149
Glenn Kastene3aa6592012-12-04 12:22:46 -08006150 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006151 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006152 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006153 if (reqSampleRate == 0) {
6154 reqSampleRate = mSampleRate;
6155 } else if (reqSampleRate > maxSampleRate) {
6156 reqSampleRate = maxSampleRate;
6157 }
Eric Laurent81784c32012-11-19 14:55:58 -08006158 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006159 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006160 AudioMixer::RESAMPLE,
6161 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006162 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006163
Andy Hung8edb8dc2015-03-26 19:13:55 -07006164 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006165 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006166 AudioMixer::TIMESTRETCH,
6167 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006168 // cast away constness for this generic API.
6169 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006170
Andy Hung69aed5f2014-02-25 17:24:40 -08006171 /*
6172 * Select the appropriate output buffer for the track.
6173 *
Andy Hung98ef9782014-03-04 14:46:50 -08006174 * Tracks with effects go into their own effects chain buffer
6175 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006176 *
6177 * Other tracks can use mMixerBuffer for higher precision
6178 * channel accumulation. If this buffer is enabled
6179 * (mMixerBufferEnabled true), then selected tracks will accumulate
6180 * into it.
6181 *
6182 */
6183 if (mMixerBufferEnabled
6184 && (track->mainBuffer() == mSinkBuffer
6185 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006186 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006187 mAudioMixer->setParameter(
6188 trackId,
6189 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006190 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006191 mAudioMixer->setParameter(
6192 trackId,
6193 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006194 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006195 } else {
6196 mAudioMixer->setParameter(
6197 trackId,
6198 AudioMixer::TRACK,
6199 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6200 mAudioMixer->setParameter(
6201 trackId,
6202 AudioMixer::TRACK,
6203 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6204 // TODO: override track->mainBuffer()?
6205 mMixerBufferValid = true;
6206 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006207 } else {
6208 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006209 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006210 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006211 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006212 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006213 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006214 AudioMixer::TRACK,
6215 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6216 }
Eric Laurent81784c32012-11-19 14:55:58 -08006217 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006218 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006219 AudioMixer::TRACK,
6220 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006221 mAudioMixer->setParameter(
6222 trackId,
6223 AudioMixer::TRACK,
6224 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006225 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006226 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006227 trackId,
6228 AudioMixer::TRACK,
6229 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006230 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006231 mAudioMixer->setParameter(
6232 trackId,
6233 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006234 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006235
6236 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006237 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006238
6239 // If one track is ready, set the mixer ready if:
6240 // - the mixer was not ready during previous round OR
6241 // - no other track is not ready
6242 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6243 mixerStatus != MIXER_TRACKS_ENABLED) {
6244 mixerStatus = MIXER_TRACKS_READY;
6245 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006246
6247 // Enable the next few lines to instrument a test for underrun log handling.
6248 // TODO: Remove when we have a better way of testing the underrun log.
6249#if 0
6250 static int i;
6251 if ((++i & 0xf) == 0) {
6252 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6253 }
6254#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006255 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006256 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006257 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006258 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6259 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006260 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006261 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006262 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006263
Eric Laurent81784c32012-11-19 14:55:58 -08006264 // clear effect chain input buffer if an active track underruns to avoid sending
6265 // previous audio buffer again to effects
6266 chain = getEffectChain_l(track->sessionId());
6267 if (chain != 0) {
6268 chain->clearInputBuffer();
6269 }
6270
Andy Hungc0691382018-09-12 18:01:57 -07006271 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006272 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6273 track->isStopped() || track->isPaused()) {
6274 // We have consumed all the buffers of this track.
6275 // Remove it from the list of active tracks.
6276 // TODO: use actual buffer filling status instead of latency when available from
6277 // audio HAL
6278 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006279 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006280 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6281 if (track->isStopped()) {
6282 track->reset();
6283 }
6284 tracksToRemove->add(track);
6285 }
6286 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006287 // No buffers for this track. Give it a few chances to
6288 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006289 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006290 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6291 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006292 tracksToRemove->add(track);
6293 // indicate to client process that the track was disabled because of underrun;
6294 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006295 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006296 // If one track is not ready, mark the mixer also not ready if:
6297 // - the mixer was ready during previous round OR
6298 // - no other track is ready
6299 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6300 mixerStatus != MIXER_TRACKS_READY) {
6301 mixerStatus = MIXER_TRACKS_ENABLED;
6302 }
6303 }
Andy Hungc0691382018-09-12 18:01:57 -07006304 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006305 }
6306
6307 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006308
6309 }
6310
jiabin245cdd92018-12-07 17:55:15 -08006311 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6312 // When there is no fast track playing haptic and FastMixer exists,
6313 // enabling the first FastTrack, which provides mixed data from normal
6314 // tracks, to play haptic data.
6315 FastTrack *fastTrack = &state->mFastTracks[0];
6316 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6317 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6318 didModify = true;
6319 }
6320 }
6321
Eric Laurent81784c32012-11-19 14:55:58 -08006322 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006323 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006324 if (didModify) {
6325 state->mFastTracksGen++;
6326 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6327 if (kUseFastMixer == FastMixer_Dynamic &&
6328 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6329 state->mCommand = FastMixerState::COLD_IDLE;
6330 state->mColdFutexAddr = &mFastMixerFutex;
6331 state->mColdGen++;
6332 mFastMixerFutex = 0;
6333 if (kUseFastMixer == FastMixer_Dynamic) {
6334 mNormalSink = mOutputSink;
6335 }
6336 // If we go into cold idle, need to wait for acknowledgement
6337 // so that fast mixer stops doing I/O.
6338 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6339 pauseAudioWatchdog = true;
6340 }
Eric Laurent81784c32012-11-19 14:55:58 -08006341 }
6342 if (sq != NULL) {
6343 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006344 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6345 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6346 // when bringing the output sink into standby.)
6347 //
6348 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6349 //
6350 // This occurs with BT suspend when we idle the FastMixer with
6351 // active tracks, which may be added or removed.
6352 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006353 }
6354#ifdef AUDIO_WATCHDOG
6355 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6356 mAudioWatchdog->pause();
6357 }
6358#endif
6359
6360 // Now perform the deferred reset on fast tracks that have stopped
6361 while (resetMask != 0) {
6362 size_t i = __builtin_ctz(resetMask);
6363 ALOG_ASSERT(i < count);
6364 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006365 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006366 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6367 track->reset();
6368 }
6369
Andy Hung80d03d22018-04-10 10:32:11 -07006370 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6371 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6372 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6373 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6374 // See also the implementation of destroyTrack_l().
6375 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006376 const int trackId = track->id();
6377 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6378 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006379 }
6380 }
6381
Eric Laurent81784c32012-11-19 14:55:58 -08006382 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006383 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006384
Eric Laurentb3f315a2021-07-13 15:09:05 +02006385 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6386 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006387 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006388 }
6389
6390 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006391 // as long as there are effects we should clear the effects buffer, to avoid
6392 // passing a non-clean buffer to the effect chain
6393 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006394 if (mType == SPATIALIZER) {
6395 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6396 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006397 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006398 // sink or mix buffer must be cleared if all tracks are connected to an
6399 // effect chain as in this case the mixer will not write to the sink or mix buffer
6400 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006401 // always clear sink buffer for spatializer output as the output of the spatializer
6402 // effect will be accumulated into it
6403 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6404 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006405 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006406 if (mMixerBufferValid) {
6407 memset(mMixerBuffer, 0, mMixerBufferSize);
6408 // TODO: In testing, mSinkBuffer below need not be cleared because
6409 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6410 // after mixing.
6411 //
6412 // To enforce this guarantee:
6413 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6414 // (mixedTracks == 0 && fastTracks > 0))
6415 // must imply MIXER_TRACKS_READY.
6416 // Later, we may clear buffers regardless, and skip much of this logic.
6417 }
Andy Hung98ef9782014-03-04 14:46:50 -08006418 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006419 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006420 }
6421
6422 // if any fast tracks, then status is ready
6423 mMixerStatusIgnoringFastTracks = mixerStatus;
6424 if (fastTracks > 0) {
6425 mixerStatus = MIXER_TRACKS_READY;
6426 }
6427 return mixerStatus;
6428}
6429
Andy Hungc5007f82023-08-29 14:26:09 -07006430// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006431uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006432{
6433 uint32_t trackCount = 0;
6434 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006435 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006436 trackCount++;
6437 }
6438 }
6439 return trackCount;
6440}
6441
Andy Hungee58e4a2023-07-07 13:47:37 -07006442bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006443{
Brian Lindahl65e90012022-07-27 18:01:07 +02006444 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6445 // could falsely detect that the frame position has stalled due to underrun because we haven't
6446 // given the Audio HAL enough time to update.
6447 const nsecs_t nowNs = systemTime();
6448 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6449 return mLatchedValue;
6450 }
6451 mPreviousNs = nowNs;
6452 mLatchedValue = false;
6453 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006454 uint64_t position = 0;
6455 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006456 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006457 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006458 if (position != mPreviousPosition) {
6459 mPreviousPosition = position;
6460 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006461 }
6462 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006463 return mLatchedValue;
6464}
6465
Andy Hungee58e4a2023-07-07 13:47:37 -07006466void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006467{
6468 mLatchedValue = true;
6469 mPreviousPosition = 0;
6470 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006471}
6472
Andy Hungc5007f82023-08-29 14:26:09 -07006473// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006474bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006475 audio_channel_mask_t channelMask, audio_format_t format,
6476 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006477{
Andy Hung1bc088a2018-02-09 15:57:31 -08006478 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6479 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006480 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006481 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006482 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006483 ALOGW("%s: invalid format: %#x", __func__, format);
6484 return false;
6485 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006486 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006487 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6488 return false;
6489 }
6490 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006491}
6492
Andy Hungc5007f82023-08-29 14:26:09 -07006493// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006494bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006495 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006496{
Eric Laurent81784c32012-11-19 14:55:58 -08006497 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006498 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006499
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006500 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006501
Eric Laurent10351942014-05-08 18:49:52 -07006502 AudioParameter param = AudioParameter(keyValuePair);
6503 int value;
6504 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6505 reconfig = true;
6506 }
6507 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006508 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006509 status = BAD_VALUE;
6510 } else {
6511 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006512 reconfig = true;
6513 }
Eric Laurent10351942014-05-08 18:49:52 -07006514 }
6515 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006516 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006517 status = BAD_VALUE;
6518 } else {
6519 // no need to save value, since it's constant
6520 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006521 }
Eric Laurent10351942014-05-08 18:49:52 -07006522 }
6523 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6524 // do not accept frame count changes if tracks are open as the track buffer
6525 // size depends on frame count and correct behavior would not be guaranteed
6526 // if frame count is changed after track creation
6527 if (!mTracks.isEmpty()) {
6528 status = INVALID_OPERATION;
6529 } else {
6530 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006531 }
Eric Laurent10351942014-05-08 18:49:52 -07006532 }
6533 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006534 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006535 }
Eric Laurent81784c32012-11-19 14:55:58 -08006536
Eric Laurent10351942014-05-08 18:49:52 -07006537 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006538 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006539 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006540 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6541 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006542 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006543 mThreadMetrics.logEndInterval();
6544 mThreadSnapshot.onEnd();
6545 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006546 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006547 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006548 }
Eric Laurent10351942014-05-08 18:49:52 -07006549 if (status == NO_ERROR && reconfig) {
6550 readOutputParameters_l();
6551 delete mAudioMixer;
6552 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006553 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006554 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006555 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006556 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006557 track->channelMask(),
6558 track->format(),
6559 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006560 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006561 "%s(): AudioMixer cannot create track(%d)"
6562 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006563 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006564 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006565 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006566 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006567 }
Eric Laurent81784c32012-11-19 14:55:58 -08006568 }
6569
Dean Wheatley68918102021-03-19 22:09:19 +11006570 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006571}
6572
6573
Andy Hungee58e4a2023-07-07 13:47:37 -07006574void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006575{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006576 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006577 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006578 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006579 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006580 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6581 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6582 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006583 if (hasFastMixer()) {
6584 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6585
6586 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6587 // while we are dumping it. It may be inconsistent, but it won't mutate!
6588 // This is a large object so we place it on the heap.
6589 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006590 const std::unique_ptr<FastMixerDumpState> copy =
6591 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006592 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006593
6594#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006595 // Similar for state queue
6596 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6597 observerCopy.dump(fd);
6598 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6599 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006600#endif
6601
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006602#ifdef AUDIO_WATCHDOG
6603 if (mAudioWatchdog != 0) {
6604 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6605 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6606 wdCopy.dump(fd);
6607 }
6608#endif
6609
6610 } else {
6611 dprintf(fd, " No FastMixer\n");
6612 }
Eric Laurent90cea102023-05-15 15:08:27 +02006613
6614 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6615 mBluetoothLatencyModesEnabled ? "" : "not ");
6616 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6617 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6618 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006619}
6620
Andy Hungee58e4a2023-07-07 13:47:37 -07006621uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006622{
6623 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6624}
6625
Andy Hungee58e4a2023-07-07 13:47:37 -07006626uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006627{
6628 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6629}
6630
Andy Hungee58e4a2023-07-07 13:47:37 -07006631void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006632{
6633 PlaybackThread::cacheParameters_l();
6634
6635 // FIXME: Relaxed timing because of a certain device that can't meet latency
6636 // Should be reduced to 2x after the vendor fixes the driver issue
6637 // increase threshold again due to low power audio mode. The way this warning
6638 // threshold is calculated and its usefulness should be reconsidered anyway.
6639 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6640}
6641
Andy Hungee58e4a2023-07-07 13:47:37 -07006642void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006643 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006644}
6645
Andy Hungee58e4a2023-07-07 13:47:37 -07006646void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006647 // Only handle latency mode if:
6648 // - mBluetoothLatencyModesEnabled is true
6649 // - the HAL supports latency modes
6650 // - the selected device is Bluetooth LE or A2DP
6651 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6652 return;
6653 }
6654 if (mOutDeviceTypeAddrs.size() != 1
6655 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6656 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6657 return;
6658 }
6659
6660 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6661 if (mSupportedLatencyModes.size() == 1) {
6662 // If the HAL only support one latency mode currently, confirm the choice
6663 latencyMode = mSupportedLatencyModes[0];
6664 } else if (mSupportedLatencyModes.size() > 1) {
6665 // Request low latency if:
6666 // - At least one active track is either:
6667 // - a fast track with gaming usage or
6668 // - a track with acessibility usage
6669 for (const auto& track : mActiveTracks) {
6670 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6671 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6672 latencyMode = AUDIO_LATENCY_MODE_LOW;
6673 break;
6674 }
6675 }
6676 }
6677
6678 if (latencyMode != mSetLatencyMode) {
6679 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6680 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6681 __func__, mId, toString(latencyMode).c_str(), status);
6682 if (status == NO_ERROR) {
6683 mSetLatencyMode = latencyMode;
6684 }
6685 }
6686}
6687
Andy Hungee58e4a2023-07-07 13:47:37 -07006688void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006689
6690 if (mOutput == nullptr || mOutput->stream == nullptr) {
6691 return;
6692 }
6693 std::vector<audio_latency_mode_t> latencyModes;
6694 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6695 if (status != NO_ERROR) {
6696 latencyModes.clear();
6697 }
6698 if (latencyModes != mSupportedLatencyModes) {
6699 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6700 __func__, mId, status, toString(latencyModes).c_str());
6701 mSupportedLatencyModes.swap(latencyModes);
6702 sendHalLatencyModesChangedEvent_l();
6703 }
6704}
6705
Andy Hungee58e4a2023-07-07 13:47:37 -07006706status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006707 std::vector<audio_latency_mode_t>* modes) {
6708 if (modes == nullptr) {
6709 return BAD_VALUE;
6710 }
Andy Hung972bec12023-08-31 16:13:39 -07006711 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006712 *modes = mSupportedLatencyModes;
6713 return NO_ERROR;
6714}
6715
Andy Hungee58e4a2023-07-07 13:47:37 -07006716void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006717 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006718 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006719 if (modes != mSupportedLatencyModes) {
6720 ALOGD("%s: thread(%d) supported latency modes: %s",
6721 __func__, mId, toString(modes).c_str());
6722 mSupportedLatencyModes.swap(modes);
6723 sendHalLatencyModesChangedEvent_l();
6724 }
6725}
6726
Andy Hungee58e4a2023-07-07 13:47:37 -07006727status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006728 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6729 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6730 return INVALID_OPERATION;
6731 }
6732 mBluetoothLatencyModesEnabled.store(enabled);
6733 return NO_ERROR;
6734}
6735
Eric Laurent81784c32012-11-19 14:55:58 -08006736// ----------------------------------------------------------------------------
6737
Andy Hungee58e4a2023-07-07 13:47:37 -07006738/* static */
6739sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006740 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006741 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6742 const audio_offload_info_t& offloadInfo) {
6743 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006744 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006745}
6746
Andy Hung583043b2023-07-17 17:05:00 -07006747DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006748 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6749 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006750 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006751 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006752{
Andy Hung583043b2023-07-17 17:05:00 -07006753 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006754}
6755
Andy Hungee58e4a2023-07-07 13:47:37 -07006756DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006757{
6758}
6759
Andy Hungee58e4a2023-07-07 13:47:37 -07006760void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006761{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006762 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006763 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6764 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6765}
6766
Andy Hungee58e4a2023-07-07 13:47:37 -07006767void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006768{
Andy Hung972bec12023-08-31 16:13:39 -07006769 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006770 if (mMasterBalance != balance) {
6771 mMasterBalance.store(balance);
6772 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6773 broadcast_l();
6774 }
6775}
6776
Andy Hungee58e4a2023-07-07 13:47:37 -07006777void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006778{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006779 float left, right;
6780
Andy Hung333ab962019-05-28 20:23:35 -07006781 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006782 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006783
Andy Hung398ffa22022-12-13 19:19:53 -08006784 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6785 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6786
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006787 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6788 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006789
6790 const int64_t volumeShaperFrames =
6791 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6792 const auto [shaperVolume, shaperActive] =
6793 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006794 mVolumeShaperActive = shaperActive;
6795
Vlad Popae2f5aef2022-07-25 16:00:20 +02006796 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6797 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6798 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6799
6800 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6801
Andy Hung6b137d12024-08-27 22:35:17 +00006802 if (!audioserver_flags::portid_volume_management()) {
6803 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6804 track->isPlaybackRestricted()) {
6805 left = right = 0;
6806 } else {
6807 float typeVolume = mStreamTypes[track->streamType()].volume;
6808 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurent277a37e2024-07-29 18:37:52 +00006809
Andy Hung6b137d12024-08-27 22:35:17 +00006810 if (left > GAIN_FLOAT_UNITY) {
6811 left = GAIN_FLOAT_UNITY;
6812 }
6813 if (right > GAIN_FLOAT_UNITY) {
6814 right = GAIN_FLOAT_UNITY;
6815 }
6816 left *= v;
6817 right *= v;
6818 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006819 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Andy Hung6b137d12024-08-27 22:35:17 +00006820 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6821 right *= mMasterBalanceRight;
6822 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006823 }
Andy Hung6b137d12024-08-27 22:35:17 +00006824 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6825 /*muteState=*/{mMasterMute,
6826 mStreamTypes[track->streamType()].volume == 0.f,
6827 mStreamTypes[track->streamType()].mute,
6828 track->isPlaybackRestricted(),
6829 clientVolumeMute,
6830 shaperVolume == 0.f});
6831 } else {
6832 if (mMasterMute || track->isPlaybackRestricted()) {
6833 left = right = 0;
6834 } else {
6835 float typeVolume = track->getPortVolume();
6836 const float v = mMasterVolume * typeVolume * shaperVolume;
Liana Kazanova (xWF)d3e99d22024-08-23 22:15:51 +00006837
Andy Hung6b137d12024-08-27 22:35:17 +00006838 if (left > GAIN_FLOAT_UNITY) {
6839 left = GAIN_FLOAT_UNITY;
6840 }
6841 if (right > GAIN_FLOAT_UNITY) {
6842 right = GAIN_FLOAT_UNITY;
6843 }
6844 left *= v;
6845 right *= v;
6846 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6847 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6848 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6849 right *= mMasterBalanceRight;
6850 }
6851 }
6852 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6853 /*muteState=*/{mMasterMute,
6854 track->getPortVolume() == 0.f,
6855 /* muteFromStreamMuted= */ false,
6856 track->isPlaybackRestricted(),
6857 clientVolumeMute,
6858 shaperVolume == 0.f});
6859 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006860
Eric Laurentbfb1b832013-01-07 09:53:42 -08006861 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006862 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006863 if (left != mLeftVolFloat || right != mRightVolFloat) {
6864 mLeftVolFloat = left;
6865 mRightVolFloat = right;
6866
Eric Laurentbfb1b832013-01-07 09:53:42 -08006867 // Delegate volume control to effect in track effect chain if needed
6868 // only one effect chain can be present on DirectOutputThread, so if
6869 // there is one, the track is connected to it
6870 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006871 // if effect chain exists, volume is handled by it.
6872 // Convert volumes from float to 8.24
6873 uint32_t vl = (uint32_t)(left * (1 << 24));
6874 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006875 // Direct/Offload effect chains set output volume in setVolume().
6876 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006877 } else {
6878 // otherwise we directly set the volume.
6879 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006880 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006881 }
6882 }
6883}
6884
Andy Hungee58e4a2023-07-07 13:47:37 -07006885void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006886{
Andy Hung8d31fd22023-06-26 19:20:57 -07006887 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6888 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006889
Eric Laurent0f0631e2015-07-06 18:01:25 -07006890 if (previousTrack != 0 && latestTrack != 0) {
6891 if (mType == DIRECT) {
6892 if (previousTrack.get() != latestTrack.get()) {
6893 mFlushPending = true;
6894 }
6895 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006896 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6897 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006898 mFlushPending = true;
6899 }
6900 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006901 } else if (previousTrack == 0) {
6902 // there could be an old track added back during track transition for direct
6903 // output, so always issues flush to flush data of the previous track if it
6904 // was already destroyed with HAL paused, then flush can resume the playback
6905 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006906 }
6907 PlaybackThread::onAddNewTrack_l();
6908}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006909
Andy Hungee58e4a2023-07-07 13:47:37 -07006910PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006911 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006912)
6913{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006914 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006915 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006916 bool doHwPause = false;
6917 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006918
6919 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006920 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006921 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006922 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006923 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006924 continue;
6925 }
6926
Andy Hung8d31fd22023-06-26 19:20:57 -07006927 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006928#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006929 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006930#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006931 // Only consider last track started for volume and mixer state control.
6932 // In theory an older track could underrun and restart after the new one starts
6933 // but as we only care about the transition phase between two tracks on a
6934 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006935 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006936 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006937
Kuowei Li23666472021-01-20 10:23:25 +08006938 if (track->isPausePending()) {
6939 track->pauseAck();
6940 // It is possible a track might have been flushed or stopped.
6941 // Other operations such as flush pending might occur on the next prepare.
6942 if (track->isPausing()) {
6943 track->setPaused();
6944 }
6945 // Always perform pause, as an immediate flush will change
6946 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006947 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006948 doHwPause = true;
6949 mHwPaused = true;
6950 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006951 } else if (track->isFlushPending()) {
6952 track->flushAck();
6953 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006954 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006955 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006956 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006957 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006958 if (last) {
6959 mLeftVolFloat = mRightVolFloat = -1.0;
6960 if (mHwPaused) {
6961 doHwResume = true;
6962 mHwPaused = false;
6963 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006964 }
6965 }
6966
Eric Laurent81784c32012-11-19 14:55:58 -08006967 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006968 // for all its buffers to be filled before processing it.
6969 // Allow draining the buffer in case the client
6970 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006971 // hence the test on (track->retryCount() > 1).
6972 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006973 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6974 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006975 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006976
6977 // target retry count that we will use is based on the time we wait for retries.
6978 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6979 // the retry threshold is when we accept any size for PCM data. This is slightly
6980 // smaller than the retry count so we can push small bits of data without a glitch.
6981 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006982 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006983 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006984 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006985 minFrames = mNormalFrameCount;
6986 } else {
6987 minFrames = 1;
6988 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006989
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006990 const size_t framesReady = track->framesReady();
6991 const int trackId = track->id();
6992 if (ATRACE_ENABLED()) {
6993 std::string traceName("nRdy");
6994 traceName += std::to_string(trackId);
6995 ATRACE_INT(traceName.c_str(), framesReady);
6996 }
6997 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006998 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006999 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07007000 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08007001
Andy Hung8d31fd22023-06-26 19:20:57 -07007002 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7003 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007004 if (last) {
7005 // make sure processVolume_l() will apply new volume even if 0
7006 mLeftVolFloat = mRightVolFloat = -1.0;
7007 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08007008 if (!mHwSupportsPause) {
7009 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08007010 }
7011 }
7012
7013 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08007014 processVolume_l(track, last);
7015 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007016 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007017 if (previousTrack != 0) {
7018 if (track != previousTrack.get()) {
7019 // Flush any data still being written from last track
7020 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07007021 // Invalidate previous track to force a seek when resuming.
7022 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007023 }
7024 }
7025 mPreviousTrack = track;
7026
Eric Laurentd595b7c2013-04-03 17:27:56 -07007027 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07007028 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08007029 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07007030 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07007031 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007032 doHwResume = true;
7033 mHwPaused = false;
7034 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007035 }
Eric Laurent81784c32012-11-19 14:55:58 -08007036 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007037 // clear effect chain input buffer if the last active track started underruns
7038 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007039 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007040 mEffectChains[0]->clearInputBuffer();
7041 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007042 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007043 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007044 if (last && mHwPaused) {
7045 doHwResume = true;
7046 mHwPaused = false;
7047 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007048 }
7049 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7050 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007051 // We have consumed all the buffers of this track.
7052 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007053 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007054 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007055 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007056 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007057 if (presComplete) {
7058 mOutput->presentationComplete();
7059 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007060 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007061 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007062 }
Eric Laurent81784c32012-11-19 14:55:58 -08007063 if (track->isStopped()) {
7064 track->reset();
7065 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007066 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007067 }
7068 } else {
7069 // No buffers for this track. Give it a few chances to
7070 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007071 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007072 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007073 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007074 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007075 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007076 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007077 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007078 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7079 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007080 tracksToRemove->add(track);
7081 // indicate to client process that the track was disabled because of
7082 // underrun; it will then automatically call start() when data is available
7083 track->disable();
7084 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7085 // unlike mixerthread, HAL can be paused for direct output
7086 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7087 "minFrames = %u, mFormat = %#x",
7088 framesReady, minFrames, mFormat);
7089 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7090 doHwPause = true;
7091 mHwPaused = true;
7092 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007093 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007094 } else if (last) {
7095 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007096 }
7097 }
7098 }
7099 }
7100
Eric Laurentd1f69b02014-12-15 14:33:13 -08007101 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007102 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007103 for (size_t i = 0; i < mTracks.size(); i++) {
7104 if (mTracks[i]->isFlushPending()) {
7105 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007106 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007107 }
7108 }
7109 }
7110
7111 // make sure the pause/flush/resume sequence is executed in the right order.
7112 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7113 // before flush and then resume HW. This can happen in case of pause/flush/resume
7114 // if resume is received before pause is executed.
7115 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007116 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007117 status_t result = mOutput->stream->pause();
7118 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007119 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007120 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007121 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007122 flushHw_l();
7123 }
7124 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007125 status_t result = mOutput->stream->resume();
7126 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007127 }
Eric Laurent81784c32012-11-19 14:55:58 -08007128 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007129 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007130
7131 return mixerStatus;
7132}
7133
Andy Hungee58e4a2023-07-07 13:47:37 -07007134void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007135{
Eric Laurent81784c32012-11-19 14:55:58 -08007136 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007137 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007138 // output audio to hardware
7139 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007140 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007141 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007142 status_t status = mActiveTrack->getNextBuffer(&buffer);
7143 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007144 // no need to pad with 0 for compressed audio
7145 if (audio_has_proportional_frames(mFormat)) {
7146 memset(curBuf, 0, frameCount * mFrameSize);
7147 }
Eric Laurent81784c32012-11-19 14:55:58 -08007148 break;
7149 }
7150 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7151 frameCount -= buffer.frameCount;
7152 curBuf += buffer.frameCount * mFrameSize;
7153 mActiveTrack->releaseBuffer(&buffer);
7154 }
Andy Hung2098f272014-02-27 14:00:06 -08007155 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007156 mSleepTimeUs = 0;
7157 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007158 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007159}
7160
Andy Hungee58e4a2023-07-07 13:47:37 -07007161void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007162{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007163 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007164 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007165 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007166 return;
7167 }
Andy Hung85ba3332021-04-27 17:40:26 -07007168 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7169 mSleepTimeUs = mActiveSleepTimeUs;
7170 } else {
7171 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007172 }
Andy Hung85ba3332021-04-27 17:40:26 -07007173 // Note: In S or later, we do not write zeroes for
7174 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007175}
7176
Andy Hungee58e4a2023-07-07 13:47:37 -07007177void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007178{
7179 {
Andy Hung972bec12023-08-31 16:13:39 -07007180 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007181 for (size_t i = 0; i < mTracks.size(); i++) {
7182 if (mTracks[i]->isFlushPending()) {
7183 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007184 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007185 }
7186 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007187 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007188 flushHw_l();
7189 }
7190 }
7191 PlaybackThread::threadLoop_exit();
7192}
7193
7194// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007195bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007196{
7197 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007198 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007199 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007200
Eric Laurent022a5132024-04-12 17:02:51 +00007201 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007202 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007203 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007204 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007205 const auto& mainTrack = mTracks[mTracks.size() - 1];
7206
7207 trackPaused = mainTrack->isPaused();
7208 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7209 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007210 }
7211
Eric Laurent022a5132024-04-12 17:02:51 +00007212 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007213}
7214
Andy Hungc5007f82023-08-29 14:26:09 -07007215// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007216bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007217 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007218{
7219 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007220 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007221
Eric Laurent10351942014-05-08 18:49:52 -07007222 AudioParameter param = AudioParameter(keyValuePair);
7223 int value;
7224 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007225 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007226 }
Eric Laurent10351942014-05-08 18:49:52 -07007227 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7228 // do not accept frame count changes if tracks are open as the track buffer
7229 // size depends on frame count and correct behavior would not be garantied
7230 // if frame count is changed after track creation
7231 if (!mTracks.isEmpty()) {
7232 status = INVALID_OPERATION;
7233 } else {
7234 reconfig = true;
7235 }
7236 }
7237 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007238 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007239 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007240 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007241 if (!mStandby) {
7242 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007243 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007244 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007245 }
Eric Laurent10351942014-05-08 18:49:52 -07007246 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007247 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007248 }
7249 if (status == NO_ERROR && reconfig) {
7250 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007251 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007252 }
7253 }
7254
Dean Wheatley68918102021-03-19 22:09:19 +11007255 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007256}
7257
Andy Hungee58e4a2023-07-07 13:47:37 -07007258uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007259{
7260 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007261 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007262 time = PlaybackThread::activeSleepTimeUs();
7263 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007264 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007265 }
7266 return time;
7267}
7268
Andy Hungee58e4a2023-07-07 13:47:37 -07007269uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007270{
7271 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007272 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007273 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7274 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007275 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007276 }
7277 return time;
7278}
7279
Andy Hungee58e4a2023-07-07 13:47:37 -07007280uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007281{
7282 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007283 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007284 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7285 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007286 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007287 }
7288 return time;
7289}
7290
Andy Hungee58e4a2023-07-07 13:47:37 -07007291void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007292{
7293 PlaybackThread::cacheParameters_l();
7294
7295 // use shorter standby delay as on normal output to release
7296 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007297 // no delay on outputs with HW A/V sync
7298 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007299 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007300 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007301 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007302 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007303 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007304 }
Eric Laurent81784c32012-11-19 14:55:58 -08007305}
7306
Andy Hungee58e4a2023-07-07 13:47:37 -07007307void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007308{
ziyangch8f194f12021-12-01 13:48:04 -08007309 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007310 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007311 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007312 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007313 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007314 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007315 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007316}
7317
Andy Hungee58e4a2023-07-07 13:47:37 -07007318int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007319 // If a VolumeShaper is active, we must wake up periodically to update volume.
7320 const int64_t NS_PER_MS = 1000000;
7321 return mVolumeShaperActive ?
7322 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7323}
7324
Eric Laurent81784c32012-11-19 14:55:58 -08007325// ----------------------------------------------------------------------------
7326
Andy Hungee58e4a2023-07-07 13:47:37 -07007327AsyncCallbackThread::AsyncCallbackThread(
7328 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007329 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007330 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007331 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007332 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007333 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007334{
7335}
7336
Andy Hungee58e4a2023-07-07 13:47:37 -07007337void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007338{
7339 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7340}
7341
Andy Hungee58e4a2023-07-07 13:47:37 -07007342bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007343{
7344 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007345 uint32_t writeAckSequence;
7346 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007347 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348
7349 {
Andy Hungc5007f82023-08-29 14:26:09 -07007350 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007351 while (!((mWriteAckSequence & 1) ||
7352 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007353 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007354 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007355 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007356 }
7357
Eric Laurentbfb1b832013-01-07 09:53:42 -08007358 if (exitPending()) {
7359 break;
7360 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007361 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7362 mWriteAckSequence, mDrainSequence);
7363 writeAckSequence = mWriteAckSequence;
7364 mWriteAckSequence &= ~1;
7365 drainSequence = mDrainSequence;
7366 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007367 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007368 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007369 }
7370 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007371 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007372 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007373 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007374 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007375 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007376 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007377 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007378 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007379 if (asyncError != ASYNC_ERROR_NONE) {
7380 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007381 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007382 }
7383 }
7384 }
7385 return false;
7386}
7387
Andy Hungee58e4a2023-07-07 13:47:37 -07007388void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007389{
7390 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007391 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007392 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007393 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007394}
7395
Andy Hungee58e4a2023-07-07 13:47:37 -07007396void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007397{
Andy Hung972bec12023-08-31 16:13:39 -07007398 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007399 // bit 0 is cleared
7400 mWriteAckSequence = sequence << 1;
7401}
7402
Andy Hungee58e4a2023-07-07 13:47:37 -07007403void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007404{
Andy Hung972bec12023-08-31 16:13:39 -07007405 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007406 // ignore unexpected callbacks
7407 if (mWriteAckSequence & 2) {
7408 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007409 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007410 }
7411}
7412
Andy Hungee58e4a2023-07-07 13:47:37 -07007413void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007414{
Andy Hung972bec12023-08-31 16:13:39 -07007415 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007416 // bit 0 is cleared
7417 mDrainSequence = sequence << 1;
7418}
7419
Andy Hungee58e4a2023-07-07 13:47:37 -07007420void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007421{
Andy Hung972bec12023-08-31 16:13:39 -07007422 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007423 // ignore unexpected callbacks
7424 if (mDrainSequence & 2) {
7425 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007426 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007427 }
7428}
7429
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007430void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007431{
Andy Hung972bec12023-08-31 16:13:39 -07007432 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007433 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007434 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007435}
7436
Eric Laurentbfb1b832013-01-07 09:53:42 -08007437
7438// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007439
7440/* static */
7441sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007442 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007443 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7444 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007445 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007446}
7447
Andy Hung583043b2023-07-17 17:05:00 -07007448OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007449 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7450 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007451 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007452 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007453{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007454 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007455 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007456 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007457}
7458
Andy Hungee58e4a2023-07-07 13:47:37 -07007459void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007460{
7461 if (mFlushPending || mHwPaused) {
7462 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007463 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007464 flushHw_l();
7465 } else {
7466 mMixerStatus = MIXER_DRAIN_ALL;
7467 threadLoop_drain();
7468 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007469 if (mUseAsyncWrite) {
7470 ALOG_ASSERT(mCallbackThread != 0);
7471 mCallbackThread->exit();
7472 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007473 PlaybackThread::threadLoop_exit();
7474}
7475
Andy Hungee58e4a2023-07-07 13:47:37 -07007476PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007477 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007478)
7479{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007480 size_t count = mActiveTracks.size();
7481
7482 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007483 bool doHwPause = false;
7484 bool doHwResume = false;
7485
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007486 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007487
Eric Laurentbfb1b832013-01-07 09:53:42 -08007488 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007489 for (const sp<IAfTrack>& t : mActiveTracks) {
7490 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007491#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007492 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007493#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007494 // Only consider last track started for volume and mixer state control.
7495 // In theory an older track could underrun and restart after the new one starts
7496 // but as we only care about the transition phase between two tracks on a
7497 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007498 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007499 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007500
Haynes Mathew George7844f672014-01-15 12:32:55 -08007501 if (track->isInvalid()) {
7502 ALOGW("An invalidated track shouldn't be in active list");
7503 tracksToRemove->add(track);
7504 continue;
7505 }
7506
Andy Hung8d31fd22023-06-26 19:20:57 -07007507 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007508 ALOGW("An idle track shouldn't be in active list");
7509 continue;
7510 }
7511
Kuowei Li23666472021-01-20 10:23:25 +08007512 if (track->isPausePending()) {
7513 track->pauseAck();
7514 // It is possible a track might have been flushed or stopped.
7515 // Other operations such as flush pending might occur on the next prepare.
7516 if (track->isPausing()) {
7517 track->setPaused();
7518 }
7519 // Always perform pause if last, as an immediate flush will change
7520 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007521 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007522 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007523 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007524 mHwPaused = true;
7525 }
7526 // If we were part way through writing the mixbuffer to
7527 // the HAL we must save this until we resume
7528 // BUG - this will be wrong if a different track is made active,
7529 // in that case we want to discard the pending data in the
7530 // mixbuffer and tell the client to present it again when the
7531 // track is resumed
7532 mPausedWriteLength = mCurrentWriteLength;
7533 mPausedBytesRemaining = mBytesRemaining;
7534 mBytesRemaining = 0; // stop writing
7535 }
7536 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007537 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007538 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007539 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007540 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007541 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007542 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007543 track->flushAck();
7544 if (last) {
7545 mFlushPending = true;
7546 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007547 } else if (track->isResumePending()){
7548 track->resumeAck();
7549 if (last) {
7550 if (mPausedBytesRemaining) {
7551 // Need to continue write that was interrupted
7552 mCurrentWriteLength = mPausedWriteLength;
7553 mBytesRemaining = mPausedBytesRemaining;
7554 mPausedBytesRemaining = 0;
7555 }
7556 if (mHwPaused) {
7557 doHwResume = true;
7558 mHwPaused = false;
7559 // threadLoop_mix() will handle the case that we need to
7560 // resume an interrupted write
7561 }
7562 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007563 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007564
Eric Laurent3df841a2016-07-15 15:15:40 -07007565 mLeftVolFloat = mRightVolFloat = -1.0;
7566
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007567 // Do not handle new data in this iteration even if track->framesReady()
7568 mixerStatus = MIXER_TRACKS_ENABLED;
7569 }
7570 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007571 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007572 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007573 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7574 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007575 if (last) {
7576 // make sure processVolume_l() will apply new volume even if 0
7577 mLeftVolFloat = mRightVolFloat = -1.0;
7578 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007579 }
7580
7581 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007582 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007583 if (previousTrack != 0) {
7584 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007585 // Flush any data still being written from last track
7586 mBytesRemaining = 0;
7587 if (mPausedBytesRemaining) {
7588 // Last track was paused so we also need to flush saved
7589 // mixbuffer state and invalidate track so that it will
7590 // re-submit that unwritten data when it is next resumed
7591 mPausedBytesRemaining = 0;
7592 // Invalidate is a bit drastic - would be more efficient
7593 // to have a flag to tell client that some of the
7594 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007595 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007596 }
7597 // flush data already sent to the DSP if changing audio session as audio
7598 // comes from a different source. Also invalidate previous track to force a
7599 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007600 if (previousTrack->sessionId() != track->sessionId()) {
7601 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007602 }
7603 }
7604 }
7605 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007606 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007607 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007608 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007609 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007610 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007611 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007612 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007613 mixerStatus = MIXER_TRACKS_READY;
7614 }
7615 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007616 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007617 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007618 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007619 // Hardware buffer can hold a large amount of audio so we must
7620 // wait for all current track's data to drain before we say
7621 // that the track is stopped.
7622 if (mBytesRemaining == 0) {
7623 // Only start draining when all data in mixbuffer
7624 // has been written
7625 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007626 track->setState(IAfTrackBase::STOPPING_2);
7627 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007628 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7629 if (last && !mStandby) {
7630 // do not modify drain sequence if we are already draining. This happens
7631 // when resuming from pause after drain.
7632 if ((mDrainSequence & 1) == 0) {
7633 mSleepTimeUs = 0;
7634 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7635 mixerStatus = MIXER_DRAIN_TRACK;
7636 mDrainSequence += 2;
7637 }
7638 if (mHwPaused) {
7639 // It is possible to move from PAUSED to STOPPING_1 without
7640 // a resume so we must ensure hardware is running
7641 doHwResume = true;
7642 mHwPaused = false;
7643 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007644 }
7645 }
Eric Laurente93cc032016-05-05 10:15:10 -07007646 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007647 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007648 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007649 }
7650 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007651 // Drain has completed or we are in standby, signal presentation complete
7652 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007653 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007654 mOutput->presentationComplete();
7655 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007656 track->reset();
7657 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007658 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007659 if (!mUseAsyncWrite) {
7660 // If we don't get explicit drain notification we must
7661 // register discontinuity regardless of whether this is
7662 // the previous (!last) or the upcoming (last) track
7663 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007664 mTimestampVerifier.discontinuity(
7665 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007666 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007667 }
7668 } else {
7669 // No buffers for this track. Give it a few chances to
7670 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007671 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007672 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007673 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007674 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007675 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007676 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007677 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7678 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007679 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007680 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007681 // it will then automatically call start() when data is available
7682 track->disable();
7683 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007684 } else if (last){
7685 mixerStatus = MIXER_TRACKS_ENABLED;
7686 }
7687 }
7688 }
7689 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007690 if (track->isReady()) { // check ready to prevent premature start.
7691 processVolume_l(track, last);
7692 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007693 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007694
Eric Laurentea0fade2013-10-04 16:23:48 -07007695 // make sure the pause/flush/resume sequence is executed in the right order.
7696 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7697 // before flush and then resume HW. This can happen in case of pause/flush/resume
7698 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007699 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007700 status_t result = mOutput->stream->pause();
7701 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007702 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007703 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007704 if (mFlushPending) {
7705 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007706 }
Eric Laurentfd477972013-10-25 18:10:40 -07007707 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007708 status_t result = mOutput->stream->resume();
7709 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007710 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007711
Eric Laurentbfb1b832013-01-07 09:53:42 -08007712 // remove all the tracks that need to be...
7713 removeTracks_l(*tracksToRemove);
7714
7715 return mixerStatus;
7716}
7717
Eric Laurentbfb1b832013-01-07 09:53:42 -08007718// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007719bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007720{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007721 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7722 mWriteAckSequence, mDrainSequence);
7723 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007724 return true;
7725 }
7726 return false;
7727}
7728
Andy Hungee58e4a2023-07-07 13:47:37 -07007729bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007730{
Andy Hung972bec12023-08-31 16:13:39 -07007731 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007732 return waitingAsyncCallback_l();
7733}
7734
Andy Hungee58e4a2023-07-07 13:47:37 -07007735void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007736{
Eric Laurente659ef42014-09-29 13:06:46 -07007737 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007738 // Flush anything still waiting in the mixbuffer
7739 mCurrentWriteLength = 0;
7740 mBytesRemaining = 0;
7741 mPausedWriteLength = 0;
7742 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007743 // reset bytes written count to reflect that DSP buffers are empty after flush.
7744 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007745
Eric Laurentbfb1b832013-01-07 09:53:42 -08007746 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007747 // discard any pending drain or write ack by incrementing sequence
7748 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7749 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007750 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007751 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7752 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007753 }
7754}
7755
Andy Hungee58e4a2023-07-07 13:47:37 -07007756void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007757{
Andy Hung972bec12023-08-31 16:13:39 -07007758 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007759 if (PlaybackThread::invalidateTracks_l(streamType)) {
7760 mFlushPending = true;
7761 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007762}
7763
Andy Hungee58e4a2023-07-07 13:47:37 -07007764void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007765 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007766 if (PlaybackThread::invalidateTracks_l(portIds)) {
7767 mFlushPending = true;
7768 }
7769}
7770
Eric Laurentbfb1b832013-01-07 09:53:42 -08007771// ----------------------------------------------------------------------------
7772
Andy Hungee58e4a2023-07-07 13:47:37 -07007773/* static */
7774sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007775 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007776 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007777 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007778}
7779
Andy Hung583043b2023-07-17 17:05:00 -07007780DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007781 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007782 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007783 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007784 mWaitTimeMs(UINT_MAX)
7785{
7786 addOutputTrack(mainThread);
7787}
7788
Andy Hungee58e4a2023-07-07 13:47:37 -07007789DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007790{
7791 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7792 mOutputTracks[i]->destroy();
7793 }
7794}
7795
Andy Hungee58e4a2023-07-07 13:47:37 -07007796void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007797{
7798 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007799 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007800 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007801 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007802 if (mMixerBufferValid) {
7803 memset(mMixerBuffer, 0, mMixerBufferSize);
7804 } else {
7805 memset(mSinkBuffer, 0, mSinkBufferSize);
7806 }
Eric Laurent81784c32012-11-19 14:55:58 -08007807 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007808 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007809 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007810 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007811 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007812}
7813
Andy Hungee58e4a2023-07-07 13:47:37 -07007814void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007815{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007816 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007817 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007818 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007819 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007820 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007821 }
7822 } else if (mBytesWritten != 0) {
7823 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7824 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007825 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007826 } else {
7827 // flush remaining overflow buffers in output tracks
7828 writeFrames = 0;
7829 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007830 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007831 }
7832}
7833
Andy Hungee58e4a2023-07-07 13:47:37 -07007834ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007835{
7836 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007837 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7838
7839 // Consider the first OutputTrack for timestamp and frame counting.
7840
7841 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7842 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7843 // we always claim success.
7844 if (i == 0) {
7845 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7846 ALOGD_IF(correction != 0 && writeFrames != 0,
7847 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7848 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7849 mFramesWritten -= correction;
7850 }
7851
7852 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007853 }
Andy Hungcf10d742020-04-28 15:38:24 -07007854 if (mStandby) {
7855 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007856 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007857 mStandby = false;
7858 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007859 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007860}
7861
Andy Hungee58e4a2023-07-07 13:47:37 -07007862void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007863{
7864 // DuplicatingThread implements standby by stopping all tracks
7865 for (size_t i = 0; i < outputTracks.size(); i++) {
7866 outputTracks[i]->stop();
7867 }
7868}
7869
Andy Hung8a5abfd2023-12-07 19:35:12 -08007870void DuplicatingThread::threadLoop_exit()
7871{
7872 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7873 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7874 // Do so here in the threadLoop_exit().
7875
7876 SortedVector <sp<IAfOutputTrack>> localTracks;
7877 {
7878 audio_utils::lock_guard l(mutex());
7879 localTracks = std::move(mOutputTracks);
7880 mOutputTracks.clear();
jiabinc62d6032024-09-03 23:39:57 +00007881 for (size_t i = 0; i < localTracks.size(); ++i) {
7882 localTracks[i]->destroy();
7883 }
Andy Hung8a5abfd2023-12-07 19:35:12 -08007884 }
7885 localTracks.clear();
7886 outputTracks.clear();
7887 PlaybackThread::threadLoop_exit();
7888}
7889
Andy Hungee58e4a2023-07-07 13:47:37 -07007890void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007891{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007892 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007893
7894 std::stringstream ss;
7895 const size_t numTracks = mOutputTracks.size();
7896 ss << " " << numTracks << " OutputTracks";
7897 if (numTracks > 0) {
7898 ss << ":";
7899 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007900 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007901 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007902 if (thread.get() != nullptr) {
7903 ss << thread.get() << ", " << thread->id();
7904 } else {
7905 ss << "null";
7906 }
7907 ss << ")";
7908 }
7909 }
7910 ss << "\n";
7911 std::string result = ss.str();
7912 write(fd, result.c_str(), result.size());
7913}
7914
Andy Hungee58e4a2023-07-07 13:47:37 -07007915void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007916{
7917 outputTracks = mOutputTracks;
7918}
7919
Andy Hungee58e4a2023-07-07 13:47:37 -07007920void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007921{
7922 outputTracks.clear();
7923}
7924
Andy Hungee58e4a2023-07-07 13:47:37 -07007925void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007926{
Andy Hung972bec12023-08-31 16:13:39 -07007927 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007928 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7929 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7930 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7931 const size_t frameCount =
7932 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7933 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7934 // from different OutputTracks and their associated MixerThreads (e.g. one may
7935 // nearly empty and the other may be dropping data).
7936
Svet Ganov33761132021-05-13 22:51:08 +00007937 // TODO b/182392769: use attribution source util, move to server edge
7938 AttributionSourceState attributionSource = AttributionSourceState();
7939 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007940 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007941 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007942 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007943 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007944 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007945 this,
7946 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007947 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007948 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007949 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007950 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007951 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7952 if (status != NO_ERROR) {
7953 ALOGE("addOutputTrack() initCheck failed %d", status);
7954 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007955 }
Andy Hung6b137d12024-08-27 22:35:17 +00007956 if (!audioserver_flags::portid_volume_management()) {
7957 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7958 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007959 mOutputTracks.add(outputTrack);
7960 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7961 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007962}
7963
Andy Hungee58e4a2023-07-07 13:47:37 -07007964void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007965{
Andy Hung972bec12023-08-31 16:13:39 -07007966 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007967 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7968 if (mOutputTracks[i]->thread() == thread) {
7969 mOutputTracks[i]->destroy();
7970 mOutputTracks.removeAt(i);
7971 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007972 // NO_THREAD_SAFETY_ANALYSIS
7973 // Lambda workaround: as thread != this
7974 // we can safely call the remote thread getOutput.
7975 const bool equalOutput =
7976 [&](){ return thread->getOutput() == mOutput; }();
7977 if (equalOutput) {
7978 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007979 }
Eric Laurent81784c32012-11-19 14:55:58 -08007980 return;
7981 }
7982 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007983 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007984}
7985
Andy Hungc5007f82023-08-29 14:26:09 -07007986// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007987void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007988{
7989 mWaitTimeMs = UINT_MAX;
7990 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007991 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007992 if (strong != 0) {
7993 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7994 if (waitTimeMs < mWaitTimeMs) {
7995 mWaitTimeMs = waitTimeMs;
7996 }
7997 }
7998 }
7999}
8000
Andy Hungee58e4a2023-07-07 13:47:37 -07008001bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08008002{
8003 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07008004 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008005 if (thread == 0) {
8006 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
8007 outputTracks[i].get());
8008 return false;
8009 }
Andy Hung87c693c2023-07-06 20:56:16 -07008010 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08008011 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07008012 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08008013 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
8014 thread.get());
8015 return false;
8016 }
8017 }
8018 return true;
8019}
8020
Andy Hungee58e4a2023-07-07 13:47:37 -07008021void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07008022 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07008023{
Kevin Rocard12381092018-04-11 09:19:59 -07008024 for (auto& outputTrack : outputTracks) { // not mOutputTracks
8025 outputTrack->setMetadatas(metadata.tracks);
8026 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008027}
8028
Andy Hungee58e4a2023-07-07 13:47:37 -07008029uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08008030{
Andy Hung7a6a0f02023-11-29 13:42:08 -08008031 // return half the wait time in microseconds.
8032 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08008033}
8034
Andy Hungee58e4a2023-07-07 13:47:37 -07008035void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008036{
8037 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8038 updateWaitTime_l();
8039
8040 MixerThread::cacheParameters_l();
8041}
8042
Eric Laurentb3f315a2021-07-13 15:09:05 +02008043// ----------------------------------------------------------------------------
8044
Andy Hungee58e4a2023-07-07 13:47:37 -07008045/* static */
8046sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008047 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008048 AudioStreamOut* output,
8049 audio_io_handle_t id,
8050 bool systemReady,
8051 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008052 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008053}
8054
Andy Hung583043b2023-07-17 17:05:00 -07008055SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008056 AudioStreamOut* output,
8057 audio_io_handle_t id,
8058 bool systemReady,
8059 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008060 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008061{
8062}
8063
Andy Hungee58e4a2023-07-07 13:47:37 -07008064void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008065 // if mSupportedLatencyModes is empty, the HAL stream does not support
8066 // latency mode control and we can exit.
8067 if (mSupportedLatencyModes.empty()) {
8068 return;
8069 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008070 // Do not update the HAL latency mode if no track is active
8071 if (mActiveTracks.isEmpty()) {
8072 return;
8073 }
8074
Eric Laurent68a40a82022-05-03 18:15:04 +02008075 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8076 if (mSupportedLatencyModes.size() == 1) {
8077 // If the HAL only support one latency mode currently, confirm the choice
8078 latencyMode = mSupportedLatencyModes[0];
8079 } else if (mSupportedLatencyModes.size() > 1) {
8080 // Request low latency if:
8081 // - The low latency mode is requested by the spatializer controller
8082 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8083 // AND
8084 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008085 for (const auto& track : mActiveTracks) {
8086 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008087 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008088 break;
8089 }
8090 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008091 }
8092
8093 if (latencyMode != mSetLatencyMode) {
8094 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008095 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8096 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008097 if (status == NO_ERROR) {
8098 mSetLatencyMode = latencyMode;
8099 }
8100 }
8101}
8102
Andy Hungee58e4a2023-07-07 13:47:37 -07008103status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008104 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008105 return BAD_VALUE;
8106 }
Andy Hung972bec12023-08-31 16:13:39 -07008107 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008108 mRequestedLatencyMode = mode;
8109 return NO_ERROR;
8110}
8111
Andy Hungee58e4a2023-07-07 13:47:37 -07008112void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008113NO_THREAD_SAFETY_ANALYSIS
8114// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008115{
8116 bool hasVirtualizer = false;
8117 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008118 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008119 {
Andy Hung972bec12023-08-31 16:13:39 -07008120 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008121 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008122 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008123 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008124 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8125 }
8126
8127 finalDownMixer = mFinalDownMixer;
8128 mFinalDownMixer.clear();
8129 }
8130
8131 if (hasVirtualizer) {
8132 if (finalDownMixer != nullptr) {
8133 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008134 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008135 }
8136 finalDownMixer.clear();
8137 } else if (!hasDownMixer) {
8138 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008139 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008140 EFFECT_UIID_DOWNMIX, &descriptors);
8141 if (status != NO_ERROR) {
8142 return;
8143 }
8144 ALOG_ASSERT(!descriptors.empty(),
8145 "%s getDescriptors() returned no error but empty list", __func__);
8146
8147 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8148 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008149 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008150
8151 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8152 ALOGW("%s error creating downmixer %d", __func__, status);
8153 finalDownMixer.clear();
8154 } else {
8155 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008156 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008157 }
8158 }
8159
8160 {
Andy Hung972bec12023-08-31 16:13:39 -07008161 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008162 mFinalDownMixer = finalDownMixer;
8163 }
8164}
8165
Andy Hunge2514462023-12-06 14:59:24 -08008166void SpatializerThread::threadLoop_exit()
8167{
8168 // The Spatializer EffectHandle must be released on the PlaybackThread
8169 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8170 mFinalDownMixer.clear();
8171
8172 PlaybackThread::threadLoop_exit();
8173}
8174
Eric Laurent81784c32012-11-19 14:55:58 -08008175// ----------------------------------------------------------------------------
8176// Record
8177// ----------------------------------------------------------------------------
8178
Andy Hung583043b2023-07-17 17:05:00 -07008179sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008180 AudioStreamIn* input,
8181 audio_io_handle_t id,
8182 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008183 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008184}
8185
Andy Hung583043b2023-07-17 17:05:00 -07008186RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008187 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008188 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008189 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008190 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008191 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008192 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008193 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008194 mActiveTracks(&this->mLocalLog),
8195 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008196 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008197 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008198 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8199 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008200 // mFastCapture below
8201 , mFastCaptureFutex(0)
8202 // mInputSource
8203 // mPipeSink
8204 // mPipeSource
8205 , mPipeFramesP2(0)
8206 // mPipeMemory
8207 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008208 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008209 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008210{
Glenn Kastend7dca052015-03-05 16:05:54 -08008211 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008212 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008213
George Burgess IVa8f90c12020-05-14 11:27:19 -07008214 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008215 mIsMsdDevice = strcmp(
8216 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8217 }
8218
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008219 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008220
Andy Hungc8fddf32018-08-08 18:32:37 -07008221 // TODO: We may also match on address as well as device type for
8222 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008223 // TODO: This property should be ensure that only contains one single device type.
8224 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8225 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008226 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8227 : AUDIO_DEVICE_NONE));
8228
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008229 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008230 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008231 size_t numCounterOffers = 0;
8232 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008233#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008234 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008235#else
8236 (void)
8237#endif
8238 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008239 ALOG_ASSERT(index == 0);
8240
8241 // initialize fast capture depending on configuration
8242 bool initFastCapture;
8243 switch (kUseFastCapture) {
8244 case FastCapture_Never:
8245 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008246 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008247 break;
8248 case FastCapture_Always:
8249 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008250 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008251 break;
8252 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008253 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008254 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008255 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008256 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8257 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8258 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008259 break;
8260 // case FastCapture_Dynamic:
8261 }
8262
8263 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008264 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008265 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008266 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8267 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008268 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008269 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008270 const sp<MemoryDealer> roHeap(readOnlyHeap());
8271 sp<IMemory> pipeMemory;
8272 if ((roHeap == 0) ||
8273 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008274 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008275 ALOGE("not enough memory for pipe buffer size=%zu; "
8276 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8277 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8278 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279 goto failed;
8280 }
8281 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8282 memset(pipeBuffer, 0, pipeSize);
8283 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008284 const NBAIO_Format offersFast[1] = {format};
8285 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008286 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008287 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008288 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008289 mPipeSink = pipe;
8290 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008291 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008292 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008293 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008294 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008295 mPipeSource = pipeReader;
8296 mPipeFramesP2 = pipeFramesP2;
8297 mPipeMemory = pipeMemory;
8298
8299 // create fast capture
8300 mFastCapture = new FastCapture();
8301 FastCaptureStateQueue *sq = mFastCapture->sq();
8302#ifdef STATE_QUEUE_DUMP
8303 // FIXME
8304#endif
8305 FastCaptureState *state = sq->begin();
8306 state->mCblk = NULL;
8307 state->mInputSource = mInputSource.get();
8308 state->mInputSourceGen++;
8309 state->mPipeSink = pipe;
8310 state->mPipeSinkGen++;
8311 state->mFrameCount = mFrameCount;
8312 state->mCommand = FastCaptureState::COLD_IDLE;
8313 // already done in constructor initialization list
8314 //mFastCaptureFutex = 0;
8315 state->mColdFutexAddr = &mFastCaptureFutex;
8316 state->mColdGen++;
8317 state->mDumpState = &mFastCaptureDumpState;
8318#ifdef TEE_SINK
8319 // FIXME
8320#endif
Andy Hung583043b2023-07-17 17:05:00 -07008321 mFastCaptureNBLogWriter =
8322 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008323 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8324 sq->end();
8325 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8326
8327 // start the fast capture
8328 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8329 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008330 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008331 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008332#ifdef AUDIO_WATCHDOG
8333 // FIXME
8334#endif
8335
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008336 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008337 }
Andy Hung8946a282018-04-19 20:04:56 -07008338#ifdef TEE_SINK
8339 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8340 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8341#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008342failed: ;
8343
8344 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008345}
8346
Andy Hungee58e4a2023-07-07 13:47:37 -07008347RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008348{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008349 if (mFastCapture != 0) {
8350 FastCaptureStateQueue *sq = mFastCapture->sq();
8351 FastCaptureState *state = sq->begin();
8352 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8353 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8354 if (old == -1) {
8355 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8356 }
8357 }
8358 state->mCommand = FastCaptureState::EXIT;
8359 sq->end();
8360 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8361 mFastCapture->join();
8362 mFastCapture.clear();
8363 }
Andy Hung583043b2023-07-17 17:05:00 -07008364 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8365 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008366 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008367}
8368
Andy Hungee58e4a2023-07-07 13:47:37 -07008369void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008370{
Glenn Kastend7dca052015-03-05 16:05:54 -08008371 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008372}
8373
Andy Hungee58e4a2023-07-07 13:47:37 -07008374void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008375{
8376 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008377 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008378 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008379 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008380 track->invalidate();
8381 }
8382 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008383 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008384}
8385
Andy Hungee58e4a2023-07-07 13:47:37 -07008386bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008387{
Eric Laurent81784c32012-11-19 14:55:58 -08008388 nsecs_t lastWarning = 0;
8389
8390 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008391
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008392reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008393 {
Andy Hung972bec12023-08-31 16:13:39 -07008394 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008395 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008396 }
8397
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008398 // used to request a deferred sleep, to be executed later while mutex is unlocked
8399 uint32_t sleepUs = 0;
8400
Andy Hung95c94a22023-10-20 16:41:18 -07008401 // timestamp correction enable is determined under lock, used in processing step.
8402 bool timestampCorrectionEnabled = false;
8403
Andy Hung446f4df2019-02-21 12:26:41 -08008404 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8405
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008406 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008407 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008408 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8409 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008410 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008411 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008412
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008413 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008414 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008415
Glenn Kasten735f45f2014-08-18 15:51:59 -07008416 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008417 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008418
Glenn Kasten735f45f2014-08-18 15:51:59 -07008419 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008420 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008421
Eric Laurent33403f02020-05-29 18:35:06 -07008422 bool silenceFastCapture = false;
8423
Andy Hungc5007f82023-08-29 14:26:09 -07008424 { // scope for mutex()
8425 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008426
Eric Laurent021cf962014-05-13 10:18:14 -07008427 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008428
Eric Laurent000a4192014-01-29 15:17:32 -08008429 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008430 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008431 if (exitPending()) {
8432 break;
8433 }
8434
Eric Laurent5c25d562016-07-13 17:17:45 -07008435 // sleep with mutex unlocked
8436 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008437 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008438 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008439 ATRACE_END();
8440 sleepUs = 0;
8441 continue;
8442 }
8443
Glenn Kasten2b806402013-11-20 16:37:38 -08008444 // if no active track(s), then standby and release wakelock
8445 size_t size = mActiveTracks.size();
8446 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008447 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008448 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008449 releaseWakeLock_l();
8450 ALOGV("RecordThread: loop stopping");
8451 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008452 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008453 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008454 goto reacquire_wakelock;
8455 }
8456
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008457 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008458 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008459 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008460 if (activeTrack) { // ensure track release is outside lock.
8461 oldActiveTracks.emplace_back(std::move(activeTrack));
8462 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008463 activeTrack = mActiveTracks[i];
8464 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008465 if (activeTrack->isFastTrack()) {
8466 ALOG_ASSERT(fastTrackToRemove == 0);
8467 fastTrackToRemove = activeTrack;
8468 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008469 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008470 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008472 continue;
8473 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008474
Andy Hung8d31fd22023-06-26 19:20:57 -07008475 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008476 switch (activeTrackState) {
8477
Andy Hung8d31fd22023-06-26 19:20:57 -07008478 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008479 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008480 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008481 if (activeTrack->isFastTrack()) {
8482 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8483 // Keep a ref on fast track to wait for FastCapture thread to get updated
8484 // state before potential track removal
8485 fastTrackToRemove = activeTrack;
8486 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008487 doBroadcast = true;
8488 size--;
8489 continue;
8490
Andy Hung8d31fd22023-06-26 19:20:57 -07008491 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008492 sleepUs = 10000;
8493 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008494 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008495 continue;
8496
Andy Hung8d31fd22023-06-26 19:20:57 -07008497 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008498 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008499 if (mStandby) {
8500 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008501 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008502 mStandby = false;
8503 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008504 activeTrack->setState(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::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008509 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008510 break;
8511
Andy Hung8d31fd22023-06-26 19:20:57 -07008512 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8513 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8514 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008515 default:
Andy Hungce685402018-10-05 17:23:27 -07008516 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8517 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008518 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008519
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008520 if (activeTrack->isFastTrack()) {
8521 ALOG_ASSERT(!mFastTrackAvail);
8522 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008523 // if the active fast track is silenced either:
8524 // 1) silence the whole capture from fast capture buffer if this is
8525 // the only active track
8526 // 2) invalidate this track: this will cause the client to reconnect and possibly
8527 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008528 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008529 if (activeTrack->isSilenced()) {
8530 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008531 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008532 } else {
8533 silenceFastCapture = true;
8534 }
8535 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008536 // Invalidate fast tracks if access to audio history is required as this is not
8537 // possible with fast tracks. Once the fast track has been invalidated, no new
8538 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8539 if (mMaxSharedAudioHistoryMs != 0) {
8540 invalidate = true;
8541 }
8542 if (invalidate) {
8543 activeTrack->invalidate();
8544 ALOG_ASSERT(fastTrackToRemove == 0);
8545 fastTrackToRemove = activeTrack;
8546 removeTrack_l(activeTrack);
8547 mActiveTracks.remove(activeTrack);
8548 size--;
8549 continue;
8550 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008551 fastTrack = activeTrack;
8552 }
Eric Laurent33403f02020-05-29 18:35:06 -07008553
8554 activeTracks.add(activeTrack);
8555 i++;
8556
Glenn Kasten9e982352013-08-14 14:39:50 -07008557 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008558
Andy Hungab65b182023-09-06 19:41:47 -07008559 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008560
Kevin Rocard069c2712018-03-29 19:09:14 -07008561 updateMetadata_l();
8562
Eric Laurent5c25d562016-07-13 17:17:45 -07008563 if (allStopped) {
8564 standbyIfNotAlreadyInStandby();
8565 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008566 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008567 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008568 }
8569
8570 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008571 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008572 if (sleepUs == 0) {
8573 sleepUs = kRecordThreadSleepUs;
8574 }
8575 continue;
8576 }
8577 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008578
Andy Hung95c94a22023-10-20 16:41:18 -07008579 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008580 lockEffectChains_l(effectChains);
8581 }
8582
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008583 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008584
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008585 size_t size = effectChains.size();
8586 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008587 // thread mutex is not locked, but effect chain is locked
8588 effectChains[i]->process_l();
8589 }
8590
Glenn Kasten735f45f2014-08-18 15:51:59 -07008591 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008592 if (mFastCapture != 0) {
8593 FastCaptureStateQueue *sq = mFastCapture->sq();
8594 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008595 bool didModify = false;
8596 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008597 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8598 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8599 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8600 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8601 if (old == -1) {
8602 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8603 }
8604 }
8605 state->mCommand = FastCaptureState::READ_WRITE;
8606#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008607 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008608 FastThreadDumpState::kSamplingNforLowRamDevice :
8609 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008610#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008611 didModify = true;
8612 }
8613 audio_track_cblk_t *cblkOld = state->mCblk;
8614 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8615 if (cblkNew != cblkOld) {
8616 state->mCblk = cblkNew;
8617 // block until acked if removing a fast track
8618 if (cblkOld != NULL) {
8619 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8620 }
8621 didModify = true;
8622 }
jiabin01c8f562018-07-19 17:47:28 -07008623 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8624 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8625 if (state->mFastPatchRecordBufferProvider != abp) {
8626 state->mFastPatchRecordBufferProvider = abp;
8627 state->mFastPatchRecordFormat = fastTrack == 0 ?
8628 AUDIO_FORMAT_INVALID : fastTrack->format();
8629 didModify = true;
8630 }
Eric Laurent33403f02020-05-29 18:35:06 -07008631 if (state->mSilenceCapture != silenceFastCapture) {
8632 state->mSilenceCapture = silenceFastCapture;
8633 didModify = true;
8634 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008635 sq->end(didModify);
8636 if (didModify) {
8637 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008638#if 0
8639 if (kUseFastCapture == FastCapture_Dynamic) {
8640 mNormalSource = mPipeSource;
8641 }
8642#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008643 }
8644 }
8645
Glenn Kasten735f45f2014-08-18 15:51:59 -07008646 // now run the fast track destructor with thread mutex unlocked
8647 fastTrackToRemove.clear();
8648
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008649 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8650 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8651 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8652 // If destination is non-contiguous, first read past the nominal end of buffer, then
8653 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008654
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008655 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008656 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008657 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008658
8659 // If an NBAIO source is present, use it to read the normal capture's data
8660 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008661 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008662
8663 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8664 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8665 // we immediately retry the read() to get data and prevent another overflow.
8666 for (int retries = 0; retries <= 2; ++retries) {
8667 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8668 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8669 framesToRead);
8670 if (framesRead != OVERRUN) break;
8671 }
8672
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008673 const ssize_t availableToRead = mPipeSource->availableToRead();
8674 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008675 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008676 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008677 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8678 "more frames to read than fifo size, %zd > %zu",
8679 availableToRead, mPipeFramesP2);
8680 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8681 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8682 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8683 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008684 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8685 }
8686 if (framesRead < 0) {
8687 status_t status = (status_t) framesRead;
8688 switch (status) {
8689 case OVERRUN:
8690 ALOGW("overrun on read from pipe");
8691 framesRead = 0;
8692 break;
8693 case NEGOTIATE:
8694 ALOGE("re-negotiation is needed");
8695 framesRead = -1; // Will cause an attempt to recover.
8696 break;
8697 default:
8698 ALOGE("unknown error %d on read from pipe", status);
8699 break;
8700 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008701 }
8702 // otherwise use the HAL / AudioStreamIn directly
8703 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008704 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008705 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008706 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008707 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008708 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008709 if (result < 0) {
8710 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008711 } else {
8712 framesRead = bytesRead / mFrameSize;
8713 }
8714 }
8715
Andy Hung446f4df2019-02-21 12:26:41 -08008716 const int64_t lastIoEndNs = systemTime(); // end IO timing
8717
Andy Hung3f0c9022016-01-15 17:49:46 -08008718 // Update server timestamp with server stats
8719 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008720 if (framesRead >= 0) {
8721 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8722 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8723 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008724
8725 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008726 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008727 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008728 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008729 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8730 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8731 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008732 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008733 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8734
8735 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008736 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008737 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008738 id(), (long long)time, (long long)position);
8739 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8740 position = correctedTimestamp.mFrames;
8741 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008742 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008743 id(), (long long)time, (long long)position);
8744 }
8745
Andy Hung3f0c9022016-01-15 17:49:46 -08008746 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8747 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8748 // Note: In general record buffers should tend to be empty in
8749 // a properly running pipeline.
8750 //
8751 // Also, it is not advantageous to call get_presentation_position during the read
8752 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008753 } else {
8754 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008755 }
8756 }
Andy Hunge6c37112019-02-26 17:38:10 -08008757
8758 // From the timestamp, input read latency is negative output write latency.
8759 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008760 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008761 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8762 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8763 mLatencyMs.add(latencyMs);
8764 }
8765
Andy Hung3f0c9022016-01-15 17:49:46 -08008766 // Use this to track timestamp information
8767 // ALOGD("%s", mTimestamp.toString().c_str());
8768
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008769 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008770 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008771 // Force input into standby so that it tries to recover at next read attempt
8772 inputStandBy();
8773 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008774 }
8775 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008776 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008777 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008778 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008779 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008780
Andy Hung8946a282018-04-19 20:04:56 -07008781#ifdef TEE_SINK
8782 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8783#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008784 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008785 {
8786 size_t part1 = mRsmpInFramesP2 - rear;
8787 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008788 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008789 (framesRead - part1) * mFrameSize);
8790 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008791 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008792 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008793
8794 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008795
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008796 // loop over each active track
8797 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008798 if (activeTrack) { // ensure track release is outside lock.
8799 oldActiveTracks.emplace_back(std::move(activeTrack));
8800 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008801 activeTrack = activeTracks[i];
8802
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008803 // skip fast tracks, as those are handled directly by FastCapture
8804 if (activeTrack->isFastTrack()) {
8805 continue;
8806 }
8807
Andy Hung73c02e42015-03-29 01:13:58 -07008808 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008809 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8810
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008811 enum {
8812 OVERRUN_UNKNOWN,
8813 OVERRUN_TRUE,
8814 OVERRUN_FALSE
8815 } overrun = OVERRUN_UNKNOWN;
8816
8817 // loop over getNextBuffer to handle circular sink
8818 for (;;) {
8819
Andy Hung8d31fd22023-06-26 19:20:57 -07008820 activeTrack->sinkBuffer().frameCount = ~0;
8821 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8822 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008823 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8824
Andy Hung73c02e42015-03-29 01:13:58 -07008825 // check available frames and handle overrun conditions
8826 // if the record track isn't draining fast enough.
8827 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008828 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008829 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008830 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008831 overrun = OVERRUN_TRUE;
8832 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008833 if (framesOut == 0 || framesIn == 0) {
8834 break;
8835 }
8836
Andy Hung6770c6f2015-04-07 13:43:36 -07008837 // Don't allow framesOut to be larger than what is possible with resampling
8838 // from framesIn.
8839 // This isn't strictly necessary but helps limit buffer resizing in
8840 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008841 if (audio_is_linear_pcm(activeTrack->format())) {
8842 framesOut = min(framesOut,
8843 destinationFramesPossible(
8844 framesIn, mSampleRate, activeTrack->sampleRate()));
8845 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008846
8847 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008848 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008849 // straight from RecordThread buffer to RecordTrack buffer.
8850 AudioBufferProvider::Buffer buffer;
8851 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008852 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008853 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008854 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008855 ALOGV_IF(buffer.frameCount != framesOut,
8856 "%s() read less than expected (%zu vs %zu)",
8857 __func__, buffer.frameCount, framesOut);
8858 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008859 memcpy(activeTrack->sinkBuffer().raw,
8860 buffer.raw, buffer.frameCount * mFrameSize);
8861 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008862 } else {
8863 framesOut = 0;
8864 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008865 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008866 }
8867 } else {
8868 // process frames from the RecordThread buffer provider to the RecordTrack
8869 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008870 framesOut = activeTrack->recordBufferConverter()->convert(
8871 activeTrack->sinkBuffer().raw,
8872 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008873 framesOut);
8874 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008875
8876 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8877 overrun = OVERRUN_FALSE;
8878 }
8879
Andy Hung93bb5732023-05-04 21:16:34 -07008880 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8881 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008882 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008883 if (framesToDrop == 0) {
8884 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008885 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008886 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008887 // Sanitize before releasing if the track has no access to the source data
8888 // An idle UID receives silence from non virtual devices until active
8889 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008890 memset(activeTrack->sinkBuffer().raw,
8891 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008892 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008893 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008894 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008895 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008896 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008897 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008898 }
8899 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008900
8901 switch (overrun) {
8902 case OVERRUN_TRUE:
8903 // client isn't retrieving buffers fast enough
8904 if (!activeTrack->setOverflow()) {
8905 nsecs_t now = systemTime();
8906 // FIXME should lastWarning per track?
8907 if ((now - lastWarning) > kWarningThrottleNs) {
8908 ALOGW("RecordThread: buffer overflow");
8909 lastWarning = now;
8910 }
8911 }
8912 break;
8913 case OVERRUN_FALSE:
8914 activeTrack->clearOverflow();
8915 break;
8916 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008917 break;
8918 }
8919
Andy Hung3f0c9022016-01-15 17:49:46 -08008920 // update frame information and push timestamp out
8921 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008922 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008923 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8924 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008925 }
8926
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008927unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008928 // enable changes in effect chain
8929 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008930 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008931 if (audio_has_proportional_frames(mFormat)
8932 && loopCount == lastLoopCountRead + 1) {
8933 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8934 const double jitterMs =
8935 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8936 {framesRead, readPeriodNs},
8937 {0, 0} /* lastTimestamp */, mSampleRate);
8938 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8939
Andy Hung972bec12023-08-31 16:13:39 -07008940 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008941 mIoJitterMs.add(jitterMs);
8942 mProcessTimeMs.add(processMs);
8943 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008944 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008945 // update timing info.
8946 mLastIoBeginNs = lastIoBeginNs;
8947 mLastIoEndNs = lastIoEndNs;
8948 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008949 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008950 mThreadloopExecutor.process(); // process any remaining deferred actions.
8951 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008952
Glenn Kasten93e471f2013-08-19 08:40:07 -07008953 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008954
8955 {
Andy Hung972bec12023-08-31 16:13:39 -07008956 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008957 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008958 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008959 track->invalidate();
8960 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008961 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008962 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008963 }
8964
8965 releaseWakeLock();
8966
8967 ALOGV("RecordThread %p exiting", this);
8968 return false;
8969}
8970
Andy Hungee58e4a2023-07-07 13:47:37 -07008971void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008972{
8973 if (!mStandby) {
8974 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008975 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008976 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008977 mStandby = true;
8978 }
8979}
8980
Andy Hungee58e4a2023-07-07 13:47:37 -07008981void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008982{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008983 // Idle the fast capture if it's currently running
8984 if (mFastCapture != 0) {
8985 FastCaptureStateQueue *sq = mFastCapture->sq();
8986 FastCaptureState *state = sq->begin();
8987 if (!(state->mCommand & FastCaptureState::IDLE)) {
8988 state->mCommand = FastCaptureState::COLD_IDLE;
8989 state->mColdFutexAddr = &mFastCaptureFutex;
8990 state->mColdGen++;
8991 mFastCaptureFutex = 0;
8992 sq->end();
8993 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8994 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8995#if 0
8996 if (kUseFastCapture == FastCapture_Dynamic) {
8997 // FIXME
8998 }
8999#endif
9000#ifdef AUDIO_WATCHDOG
9001 // FIXME
9002#endif
9003 } else {
9004 sq->end(false /*didModify*/);
9005 }
9006 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07009007 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009008 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07009009
9010 // If going into standby, flush the pipe source.
9011 if (mPipeSource.get() != nullptr) {
9012 const ssize_t flushed = mPipeSource->flush();
9013 if (flushed > 0) {
9014 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
9015 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
9016 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
9017 }
9018 }
Eric Laurent81784c32012-11-19 14:55:58 -08009019}
9020
Andy Hungc5007f82023-08-29 14:26:09 -07009021// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009022sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07009023 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009024 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009025 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08009026 audio_format_t format,
9027 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08009028 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08009029 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009030 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009031 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00009032 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07009033 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08009034 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08009035 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009036 audio_port_handle_t portId,
9037 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009038{
Glenn Kasten74935e42013-12-19 08:56:45 -08009039 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009040 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009041 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009042 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009043 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009044 audio_input_flags_t requestedFlags = *flags;
9045 uint32_t sampleRate;
9046
9047 lStatus = initCheck();
9048 if (lStatus != NO_ERROR) {
9049 ALOGE("createRecordTrack_l() audio driver not initialized");
9050 goto Exit;
9051 }
9052
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009053 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9054 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9055 lStatus = BAD_VALUE;
9056 goto Exit;
9057 }
9058
Eric Laurentec376dc2021-04-08 20:41:22 +02009059 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009060 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009061 lStatus = PERMISSION_DENIED;
9062 goto Exit;
9063 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009064 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009065 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009066 lStatus = BAD_VALUE;
9067 goto Exit;
9068 }
9069 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009070 if (*pSampleRate == 0) {
9071 *pSampleRate = mSampleRate;
9072 }
9073 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009074
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009075 // special case for FAST flag considered OK if fast capture is present and access to
9076 // audio history is not required
9077 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009078 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9079 }
9080
Eric Laurentf14db3c2017-12-08 14:20:36 -08009081 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009082 if ((*flags & inputFlags) != *flags) {
9083 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9084 " input flags (%08x)",
9085 *flags, inputFlags);
9086 *flags = (audio_input_flags_t)(*flags & inputFlags);
9087 }
Eric Laurent81784c32012-11-19 14:55:58 -08009088
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009089 // client expresses a preference for FAST and no access to audio history,
9090 // but we get the final say
9091 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009092 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009093 // we formerly checked for a callback handler (non-0 tid),
9094 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009095 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009096 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009097 // Frame count is not specified (0), or is less than or equal the pipe depth.
9098 // It is OK to provide a higher capacity than requested.
9099 // We will force it to mPipeFramesP2 below.
9100 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009101 // PCM data
9102 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009103 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009104 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009105 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009106 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009107 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009108 hasFastCapture() &&
9109 // there are sufficient fast track slots available
9110 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009111 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009112 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009113 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009114 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009115 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009116 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009117 audio_input_flags_t old = *flags;
9118 chain->checkInputFlagCompatibility(flags);
9119 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009120 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9121 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009122 }
9123 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009124 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009125 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9126 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009127 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009128 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9129 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009130 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009131 this, frameCount, mFrameCount, mPipeFramesP2,
9132 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009133 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009134 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009135 }
9136 }
9137
Eric Laurentf14db3c2017-12-08 14:20:36 -08009138 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9139 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9140 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9141 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9142 lStatus = BAD_TYPE;
9143 goto Exit;
9144 }
9145
Glenn Kasten74105912014-07-03 12:28:53 -07009146 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009147 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009148 // fast track: frame count is exactly the pipe depth
9149 frameCount = mPipeFramesP2;
9150 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009151 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009152 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009153 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9154 // or 20 ms if there is a fast capture
9155 // TODO This could be a roundupRatio inline, and const
9156 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9157 * sampleRate + mSampleRate - 1) / mSampleRate;
9158 // minimum number of notification periods is at least kMinNotifications,
9159 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9160 static const size_t kMinNotifications = 3;
9161 static const uint32_t kMinMs = 30;
9162 // TODO This could be a roundupRatio inline
9163 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9164 // TODO This could be a roundupRatio inline
9165 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9166 maxNotificationFrames;
9167 const size_t minFrameCount = maxNotificationFrames *
9168 max(kMinNotifications, minNotificationsByMs);
9169 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009170 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9171 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009172 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009173 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009174 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009175 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009176
Andy Hungc5007f82023-08-29 14:26:09 -07009177 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009178 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009179 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009180 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009181 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009182 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009183 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009184 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009185 }
Eric Laurent81784c32012-11-19 14:55:58 -08009186
Andy Hung8d31fd22023-06-26 19:20:57 -07009187 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009188 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009189 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009190 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009191 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009192
Glenn Kasten03003332013-08-06 15:40:54 -07009193 lStatus = track->initCheck();
9194 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009195 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009196 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009197 goto Exit;
9198 }
9199 mTracks.add(track);
9200
Eric Laurent05067782016-06-01 18:27:28 -07009201 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009202 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9203 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9204 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009205 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009206 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009207
9208 if (maxSharedAudioHistoryMs != 0) {
9209 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9210 }
Eric Laurent81784c32012-11-19 14:55:58 -08009211 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009212
Eric Laurent81784c32012-11-19 14:55:58 -08009213 lStatus = NO_ERROR;
9214
9215Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009216 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009217 return track;
9218}
9219
Andy Hungee58e4a2023-07-07 13:47:37 -07009220status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009221 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009222 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009223{
9224 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9225 sp<ThreadBase> strongMe = this;
9226 status_t status = NO_ERROR;
9227
9228 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009229 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009230 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009231 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009232 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009233 event, triggerSession,
9234 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009235 }
9236
9237 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009238 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009239 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009240 if (recordTrack->isInvalid()) {
9241 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009242 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9243 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009244 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009245 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009246 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009247 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9248 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009249 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009250 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009251 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009252 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009253 }
9254 return status;
9255 }
9256
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009257 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9258 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9259 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009260 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009261 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009262 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009263 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009264 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009265 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009266 if (recordTrack->isInvalid()) {
9267 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009268 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9269 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009270 // STARTING_2 forces destroy to call stopInput.
9271 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009272 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9273 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009274 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009275 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009276 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009277 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009278 // Someone else has changed state, let them take over,
9279 // leave mState in the new state.
9280 recordTrack->clearSyncStartEvent();
9281 return INVALID_OPERATION;
9282 }
9283 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009284 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009285 ALOGW("%s(%d): startInput failed, status %d",
9286 __func__, recordTrack->id(), status);
9287 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9288 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009289 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009290 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009291 return status;
9292 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009293 sendIoConfigEvent_l(
9294 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009295 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009296
9297 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9298
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009299 // Catch up with current buffer indices if thread is already running.
9300 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9301 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9302 // see previously buffered data before it called start(), but with greater risk of overrun.
9303
Andy Hung8d31fd22023-06-26 19:20:57 -07009304 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009305 if (!recordTrack->isDirect()) {
9306 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009307 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009308 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009309 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009310 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009311 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009312 return status;
9313 }
Eric Laurent81784c32012-11-19 14:55:58 -08009314}
9315
Andy Hungee58e4a2023-07-07 13:47:37 -07009316void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009317{
Andy Hungee58e4a2023-07-07 13:47:37 -07009318 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009319
9320 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009321 sp<IAfTrackBase> ptr =
9322 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9323 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009324 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009325 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009326 }
Eric Laurent81784c32012-11-19 14:55:58 -08009327 }
9328}
9329
Andy Hungee58e4a2023-07-07 13:47:37 -07009330bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009331 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009332 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009333 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009334 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009335 return false;
9336 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009337 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009338 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009339
Andy Hungabfab202019-03-07 19:45:54 -08009340 // NOTE: Waiting here is important to keep stop synchronous.
9341 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009342 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009343 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009344 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009345 }
Andy Hungce685402018-10-05 17:23:27 -07009346
Andy Hung8d31fd22023-06-26 19:20:57 -07009347 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009348 ALOGV("Record stopped OK");
9349 return true;
9350 }
Andy Hungce685402018-10-05 17:23:27 -07009351
9352 // don't handle anything - we've been invalidated or restarted and in a different state
9353 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009354 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009355 return false;
9356}
9357
Andy Hungee58e4a2023-07-07 13:47:37 -07009358bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009359{
9360 return false;
9361}
9362
Andy Hungee58e4a2023-07-07 13:47:37 -07009363status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009364{
9365#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9366 if (!isValidSyncEvent(event)) {
9367 return BAD_VALUE;
9368 }
9369
Glenn Kastend848eb42016-03-08 13:42:11 -08009370 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009371 status_t ret = NAME_NOT_FOUND;
9372
Andy Hung972bec12023-08-31 16:13:39 -07009373 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009374
9375 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009376 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009377 if (eventSession == track->sessionId()) {
9378 (void) track->setSyncEvent(event);
9379 ret = NO_ERROR;
9380 }
9381 }
9382 return ret;
9383#else
9384 return BAD_VALUE;
9385#endif
9386}
9387
Andy Hungee58e4a2023-07-07 13:47:37 -07009388status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009389 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009390{
9391 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009392 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009393 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009394 return NO_INIT;
9395 }
jiabin9ff780e2018-03-19 18:19:52 -07009396 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9397 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009398}
9399
Andy Hungee58e4a2023-07-07 13:47:37 -07009400status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009401 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009402{
Paul McLean12340082019-03-19 09:35:05 -06009403 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009404 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009405 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009406 return NO_INIT;
9407 }
Paul McLean12340082019-03-19 09:35:05 -06009408 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009409}
9410
Andy Hungee58e4a2023-07-07 13:47:37 -07009411status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009412{
Paul McLean12340082019-03-19 09:35:05 -06009413 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009414 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009415 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009416 return NO_INIT;
9417 }
Paul McLean12340082019-03-19 09:35:05 -06009418 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009419}
9420
Andy Hungee58e4a2023-07-07 13:47:37 -07009421status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009422 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9423 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009424 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009425 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9426}
9427
Andy Hungee58e4a2023-07-07 13:47:37 -07009428status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009429 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9430 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009431
Eric Laurentec376dc2021-04-08 20:41:22 +02009432 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9433 return BAD_VALUE;
9434 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009435
9436 if (sharedAudioStartMs < 0
9437 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009438 return BAD_VALUE;
9439 }
9440
Eric Laurent2407ce32021-04-26 14:56:03 +02009441 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9442 // As we cannot detect more than one wraparound, only accept values up current write position
9443 // after one wraparound
9444 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9445 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009446 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009447 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9448 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009449 // Bring the start frame position within the input buffer to match the documented
9450 // "best effort" behavior of the API.
9451 if (sharedOffset < 0) {
9452 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009453 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009454 sharedAudioStartFrames =
9455 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009456 }
9457
Eric Laurentec376dc2021-04-08 20:41:22 +02009458 mSharedAudioPackageName = sharedAudioPackageName;
9459 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009460 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009461 } else {
9462 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009463 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009464 }
9465 return NO_ERROR;
9466}
9467
Andy Hungee58e4a2023-07-07 13:47:37 -07009468void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009469 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9470 mSharedAudioStartFrames = -1;
9471 mSharedAudioPackageName = "";
9472}
9473
Andy Hungee58e4a2023-07-07 13:47:37 -07009474ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009475{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009476 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009477 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009478 }
9479 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009480 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009481 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009482 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009483 }
9484 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009485 MetadataUpdate change;
9486 change.recordMetadataUpdate = metadata.tracks;
9487 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009488}
9489
Andy Hungc5007f82023-08-29 14:26:09 -07009490// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009491void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009492{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009493 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009494 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009495
Eric Laurent81784c32012-11-19 14:55:58 -08009496 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009497 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009498 removeTrack_l(track);
9499 }
9500}
9501
Andy Hungee58e4a2023-07-07 13:47:37 -07009502void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009503{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009504 String8 result;
9505 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009506 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009507
Eric Laurent81784c32012-11-19 14:55:58 -08009508 mTracks.remove(track);
9509 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009510 if (track->isFastTrack()) {
9511 ALOG_ASSERT(!mFastTrackAvail);
9512 mFastTrackAvail = true;
9513 }
Eric Laurent81784c32012-11-19 14:55:58 -08009514}
9515
Andy Hungee58e4a2023-07-07 13:47:37 -07009516void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009517{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009518 AudioStreamIn *input = mInput;
9519 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9520 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009521 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009522 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009523 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009524 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009525 }
Andy Hungbfa64962017-06-12 14:43:19 -07009526
9527 if (input != nullptr) {
9528 dprintf(fd, " Hal stream dump:\n");
9529 (void)input->stream->dump(fd);
9530 }
9531
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009532 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009533 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009534
Glenn Kasten2f90c512015-12-02 11:40:09 -08009535 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9536 // while we are dumping it. It may be inconsistent, but it won't mutate!
9537 // This is a large object so we place it on the heap.
9538 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009539 const std::unique_ptr<FastCaptureDumpState> copy =
9540 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009541 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009542}
9543
Andy Hungee58e4a2023-07-07 13:47:37 -07009544void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009545{
Eric Laurent81784c32012-11-19 14:55:58 -08009546 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009547 size_t numtracks = mTracks.size();
9548 size_t numactive = mActiveTracks.size();
9549 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009550 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009551 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009552 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009553 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009554 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009555 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009556 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009557 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009558 if (track != 0) {
9559 bool active = mActiveTracks.indexOf(track) >= 0;
9560 if (active) {
9561 numactiveseen++;
9562 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009563 result.append(prefix);
9564 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009565 }
Eric Laurent81784c32012-11-19 14:55:58 -08009566 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009567 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009568 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009569 }
9570
Marco Nelissenb2208842014-02-07 14:00:50 -08009571 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009572 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009573 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009574 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009575 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009576 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009577 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009578 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009579 result.append(prefix);
9580 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009581 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009582 }
Eric Laurent81784c32012-11-19 14:55:58 -08009583
9584 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009585 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009586}
9587
Andy Hungee58e4a2023-07-07 13:47:37 -07009588void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009589{
Andy Hung972bec12023-08-31 16:13:39 -07009590 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009591 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009592 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009593 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009594 track->setSilenced(silenced);
9595 }
9596 }
9597}
Andy Hung73c02e42015-03-29 01:13:58 -07009598
Andy Hung8d31fd22023-06-26 19:20:57 -07009599void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009600{
Andy Hung87c693c2023-07-06 20:56:16 -07009601 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009602 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009603 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009604 const int32_t rear = recordThread->mRsmpInRear;
9605 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009606 if (mRecordTrack->startFrames() >= 0) {
9607 int32_t startFrames = mRecordTrack->startFrames();
9608 // Accept a recent wraparound of mRsmpInRear
9609 if (startFrames <= rear) {
9610 deltaFrames = rear - startFrames;
9611 } else {
9612 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009613 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009614 // start frame cannot be further in the past than start of resampling buffer
9615 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9616 deltaFrames = recordThread->mRsmpInFrames;
9617 }
9618 }
9619 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009620}
9621
Andy Hung8d31fd22023-06-26 19:20:57 -07009622void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009623 size_t *framesAvailable, bool *hasOverrun)
9624{
Andy Hung87c693c2023-07-06 20:56:16 -07009625 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009626 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009627 const int32_t rear = recordThread->mRsmpInRear;
9628 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009629 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009630
9631 size_t framesIn;
9632 bool overrun = false;
9633 if (filled < 0) {
9634 // should not happen, but treat like a massive overrun and re-sync
9635 framesIn = 0;
9636 mRsmpInFront = rear;
9637 overrun = true;
9638 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9639 framesIn = (size_t) filled;
9640 } else {
9641 // client is not keeping up with server, but give it latest data
9642 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009643 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9644 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009645 overrun = true;
9646 }
9647 if (framesAvailable != NULL) {
9648 *framesAvailable = framesIn;
9649 }
9650 if (hasOverrun != NULL) {
9651 *hasOverrun = overrun;
9652 }
9653}
9654
Eric Laurent81784c32012-11-19 14:55:58 -08009655// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009656status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009657 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009658{
Andy Hung87c693c2023-07-06 20:56:16 -07009659 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009660 if (threadBase == 0) {
9661 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009662 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009663 return NOT_ENOUGH_DATA;
9664 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009665 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009666 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009667 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009668 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009669 // FIXME should not be P2 (don't want to increase latency)
9670 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009671 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009672 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009673
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009674 front &= recordThread->mRsmpInFramesP2 - 1;
9675 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009676 if (part1 > (size_t) filled) {
9677 part1 = filled;
9678 }
9679 size_t ask = buffer->frameCount;
9680 ALOG_ASSERT(ask > 0);
9681 if (part1 > ask) {
9682 part1 = ask;
9683 }
9684 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009685 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009686 buffer->raw = NULL;
9687 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009688 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009689 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009690 }
9691
Andy Hung57446612015-04-19 23:56:46 -07009692 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009693 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009694 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009695 return NO_ERROR;
9696}
9697
9698// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009699void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009700 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009701{
Hongwei Wang95e37682019-04-12 11:13:36 -07009702 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009703 if (stepCount == 0) {
9704 return;
9705 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009706 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009707 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009708 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009709 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009710 buffer->frameCount = 0;
9711}
9712
Andy Hungee58e4a2023-07-07 13:47:37 -07009713void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009714{
Andy Hung972bec12023-08-31 16:13:39 -07009715 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009716 checkBtNrec_l();
9717}
9718
Andy Hungee58e4a2023-07-07 13:47:37 -07009719void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009720{
9721 // disable AEC and NS if the device is a BT SCO headset supporting those
9722 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009723 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009724 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009725 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9726 for (size_t i = 0; i < mEffectChains.size(); i++) {
9727 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9728 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9729 }
9730 }
9731}
9732
Andy Hung97a893e2015-03-29 01:03:07 -07009733
Andy Hungee58e4a2023-07-07 13:47:37 -07009734bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009735 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009736{
9737 bool reconfig = false;
9738
Eric Laurent10351942014-05-08 18:49:52 -07009739 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009740
Eric Laurent10351942014-05-08 18:49:52 -07009741 audio_format_t reqFormat = mFormat;
9742 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009743 // 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 +08009744 [[maybe_unused]] audio_channel_mask_t channelMask =
9745 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009746
9747 AudioParameter param = AudioParameter(keyValuePair);
9748 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009749
9750 // scope for AutoPark extends to end of method
9751 AutoPark<FastCapture> park(mFastCapture);
9752
Eric Laurent10351942014-05-08 18:49:52 -07009753 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9754 // channel count change can be requested. Do we mandate the first client defines the
9755 // HAL sampling rate and channel count or do we allow changes on the fly?
9756 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9757 samplingRate = value;
9758 reconfig = true;
9759 }
9760 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009761 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009762 status = BAD_VALUE;
9763 } else {
9764 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009765 reconfig = true;
9766 }
Eric Laurent10351942014-05-08 18:49:52 -07009767 }
9768 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9769 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009770 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009771 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009772 status = BAD_VALUE;
9773 } else {
9774 channelMask = mask;
9775 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009776 }
Eric Laurent10351942014-05-08 18:49:52 -07009777 }
9778 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9779 // do not accept frame count changes if tracks are open as the track buffer
9780 // size depends on frame count and correct behavior would not be guaranteed
9781 // if frame count is changed after track creation
9782 if (mActiveTracks.size() > 0) {
9783 status = INVALID_OPERATION;
9784 } else {
9785 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009786 }
Eric Laurent10351942014-05-08 18:49:52 -07009787 }
9788 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009789 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009790 }
9791 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9792 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009793 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009794 }
Glenn Kastene198c362013-08-13 09:13:36 -07009795
Eric Laurent10351942014-05-08 18:49:52 -07009796 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009797 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009798 if (status == INVALID_OPERATION) {
9799 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009800 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009801 }
9802 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009803 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009804 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9805 if (mInput->stream->getAudioProperties(&config) == OK &&
9806 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9807 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009808 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009809 status = NO_ERROR;
9810 }
Eric Laurent81784c32012-11-19 14:55:58 -08009811 }
Eric Laurent10351942014-05-08 18:49:52 -07009812 if (status == NO_ERROR) {
9813 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009814 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009815 }
9816 }
Eric Laurent81784c32012-11-19 14:55:58 -08009817 }
Eric Laurent10351942014-05-08 18:49:52 -07009818
Eric Laurent81784c32012-11-19 14:55:58 -08009819 return reconfig;
9820}
9821
Andy Hungee58e4a2023-07-07 13:47:37 -07009822String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009823{
Andy Hung972bec12023-08-31 16:13:39 -07009824 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009825 if (initCheck() == NO_ERROR) {
9826 String8 out_s8;
9827 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9828 return out_s8;
9829 }
Eric Laurent81784c32012-11-19 14:55:58 -08009830 }
Andy Hung920f6572022-10-06 12:09:49 -07009831 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009832}
9833
Andy Hungab65b182023-09-06 19:41:47 -07009834void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009835 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009836 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009837 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009838 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009839 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009840 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009841 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9842 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009843 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009844 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009845 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009846 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009847 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009848 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009849 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009850 break;
9851 }
Andy Hungab65b182023-09-06 19:41:47 -07009852 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009853}
9854
Andy Hungee58e4a2023-07-07 13:47:37 -07009855void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009856{
Dean Wheatley6c009512023-10-23 09:34:14 +11009857 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9858 mSampleRate = audioConfig.sample_rate;
9859 mChannelMask = audioConfig.channel_mask;
9860 if (!audio_is_input_channel(mChannelMask)) {
9861 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9862 }
9863
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009864 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009865
9866 // Get actual HAL format.
9867 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9868 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9869 // Get format from the shim, which will be different than the HAL format
9870 // if recording compressed audio from IEC61937 wrapped sources.
9871 mFormat = audioConfig.format;
9872 if (!audio_is_valid_format(mFormat)) {
9873 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9874 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009875 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009876 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9877 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009878 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009879 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009880 ALOGI("HAL format %#x is not linear pcm", mFormat);
9881 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009882 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009883 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9884 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009885 result = mInput->stream->getBufferSize(&mBufferSize);
9886 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009887 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009888 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9889 "mBufferSize=%zu, mFrameCount=%zu",
9890 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009891
Eric Laurentec376dc2021-04-08 20:41:22 +02009892 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9893 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009894 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009895
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009896 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9897 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009898
9899 audio_input_flags_t flags = mInput->flags;
9900 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9901 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009902 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009903 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9904 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9905 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9906 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9907 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9908 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009909}
9910
Andy Hungee58e4a2023-07-07 13:47:37 -07009911uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009912{
Andy Hung972bec12023-08-31 16:13:39 -07009913 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009914 uint32_t result;
9915 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9916 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009917 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009918 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009919}
9920
Andy Hungee58e4a2023-07-07 13:47:37 -07009921KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009922{
Glenn Kastend848eb42016-03-08 13:42:11 -08009923 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009924 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009925 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009926 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009927 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009928 if (ids.indexOfKey(sessionId) < 0) {
9929 ids.add(sessionId, true);
9930 }
9931 }
9932 return ids;
9933}
9934
Andy Hungee58e4a2023-07-07 13:47:37 -07009935AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009936{
Andy Hung972bec12023-08-31 16:13:39 -07009937 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009938 AudioStreamIn *input = mInput;
9939 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009940 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009941 return input;
9942}
9943
Andy Hungc5007f82023-08-29 14:26:09 -07009944// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009945sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009946{
9947 if (mInput == NULL) {
9948 return NULL;
9949 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009950 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009951}
9952
Andy Hungee58e4a2023-07-07 13:47:37 -07009953status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009954{
Eric Laurent81784c32012-11-19 14:55:58 -08009955 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009956 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009957 chain->setInBuffer(NULL);
9958 chain->setOutBuffer(NULL);
9959
9960 checkSuspendOnAddEffectChain_l(chain);
9961
Eric Laurent1b928682014-10-02 19:41:47 -07009962 // make sure enabled pre processing effects state is communicated to the HAL as we
9963 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009964 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009965
Eric Laurent81784c32012-11-19 14:55:58 -08009966 mEffectChains.add(chain);
9967
9968 return NO_ERROR;
9969}
9970
Andy Hungee58e4a2023-07-07 13:47:37 -07009971size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009972{
9973 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009974
9975 for (size_t i = 0; i < mEffectChains.size(); i++) {
9976 if (chain == mEffectChains[i]) {
9977 mEffectChains.removeAt(i);
9978 break;
9979 }
Eric Laurent81784c32012-11-19 14:55:58 -08009980 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009981 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009982}
9983
Andy Hungee58e4a2023-07-07 13:47:37 -07009984status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009985 audio_patch_handle_t *handle)
9986{
9987 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009988
9989 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009990 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009991 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009992 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009993 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009994 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009995 }
9996
Eric Laurentd8365c52017-07-16 15:27:05 -07009997 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009998
9999 // store new source and send to effects
10000 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10001 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -070010002 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -070010003 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -070010004 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010005 }
Eric Laurent1c333e22014-05-20 10:48:17 -070010006
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010007 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010008 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10009 status = hwDevice->createAudioPatch(patch->num_sources,
10010 patch->sources,
10011 patch->num_sinks,
10012 patch->sinks,
10013 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010014 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010015 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
10016 patch->sinks[0].ext.mix.usecase.source,
10017 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -070010018 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -070010019 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010020
jiabinc52b1ff2019-10-31 17:20:42 -070010021 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -070010022 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -070010023 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -070010024 }
Eric Laurent296fb132015-05-01 11:38:42 -070010025
Andy Hungc2b11cb2020-04-22 09:04:01 -070010026 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -070010027 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -070010028 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -070010029 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -070010030 // also dispatch to active AudioRecords
10031 for (const auto &track : mActiveTracks) {
10032 track->logEndInterval();
10033 track->logBeginInterval(pathSourcesAsString);
10034 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010035 // Force meteadata update after a route change
10036 mActiveTracks.setHasChanged();
10037
Eric Laurent1c333e22014-05-20 10:48:17 -070010038 return status;
10039}
10040
Andy Hungee58e4a2023-07-07 13:47:37 -070010041status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010042{
10043 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010044
jiabinc52b1ff2019-10-31 17:20:42 -070010045 mPatch = audio_patch{};
10046 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010047
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010048 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010049 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10050 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010051 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010052 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010053 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010054 // Force meteadata update after a route change
10055 mActiveTracks.setHasChanged();
10056
Eric Laurent1c333e22014-05-20 10:48:17 -070010057 return status;
10058}
10059
Andy Hungee58e4a2023-07-07 13:47:37 -070010060void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010061{
Andy Hung972bec12023-08-31 16:13:39 -070010062 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010063 mOutDevices = outDevices;
10064 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10065 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010066 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010067 }
10068}
10069
Andy Hungee58e4a2023-07-07 13:47:37 -070010070int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010071{
10072 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010073 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010074 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010075 int32_t oldestFront = mRsmpInRear;
10076 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010077 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010078 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010079 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010080 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010081 if (filled > maxFilled) {
10082 oldestFront = front;
10083 maxFilled = filled;
10084 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010085 }
Andy Hung920f6572022-10-06 12:09:49 -070010086 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010087 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10088 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010089 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010090}
10091
Andy Hungee58e4a2023-07-07 13:47:37 -070010092void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010093{
10094 if (offset == 0) {
10095 return;
10096 }
10097 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010098 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010099 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010100 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010101 }
10102}
10103
Andy Hungee58e4a2023-07-07 13:47:37 -070010104void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010105{
10106 // This is the formula for calculating the temporary buffer size.
10107 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10108 // 1 full output buffer, regardless of the alignment of the available input.
10109 // The value is somewhat arbitrary, and could probably be even larger.
10110 // A larger value should allow more old data to be read after a track calls start(),
10111 // without increasing latency.
10112 //
10113 // Note this is independent of the maximum downsampling ratio permitted for capture.
10114 size_t minRsmpInFrames = mFrameCount * 7;
10115
10116 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10117 // capture history available to another client using the same session ID:
10118 // dimension the resampler input buffer accordingly.
10119
10120 // Get oldest client read position: getOldestFront_l() must be called before altering
10121 // mRsmpInRear, or mRsmpInFrames
10122 int32_t previousFront = getOldestFront_l();
10123 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10124 int32_t previousRear = mRsmpInRear;
10125 mRsmpInRear = 0;
10126
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010127 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010128 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010129 "resizeInputBuffer_l() called with invalid max shared history %d",
10130 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010131 if (maxSharedAudioHistoryMs != 0) {
10132 // resizeInputBuffer_l should never be called with a non zero shared history if the
10133 // buffer was not already allocated
10134 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10135 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10136 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10137 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010138 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010139 return;
10140 }
10141 mRsmpInFrames = rsmpInFrames;
10142 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010143 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010144 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10145 // initialized
10146 if (mRsmpInFrames < minRsmpInFrames) {
10147 mRsmpInFrames = minRsmpInFrames;
10148 }
10149 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10150
10151 // TODO optimize audio capture buffer sizes ...
10152 // Here we calculate the size of the sliding buffer used as a source
10153 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10154 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10155 // be better to have it derived from the pipe depth in the long term.
10156 // The current value is higher than necessary. However it should not add to latency.
10157
10158 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10159 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10160
10161 void *rsmpInBuffer;
10162 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10163 // if posix_memalign fails, will segv here.
10164 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10165
10166 // Copy audio history if any from old buffer before freeing it
10167 if (previousRear != 0) {
10168 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10169 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10170
10171 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10172 previousFront &= previousRsmpInFramesP2 - 1;
10173 size_t part1 = previousRsmpInFramesP2 - previousFront;
10174 if (part1 > (size_t) unread) {
10175 part1 = unread;
10176 }
10177 if (part1 != 0) {
10178 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10179 part1 * mFrameSize);
10180 mRsmpInRear = part1;
10181 part1 = unread - part1;
10182 if (part1 != 0) {
10183 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10184 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10185 mRsmpInRear += part1;
10186 }
10187 }
10188 // Update front for all clients according to new rear
10189 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10190 } else {
10191 mRsmpInRear = 0;
10192 }
10193 free(mRsmpInBuffer);
10194 mRsmpInBuffer = rsmpInBuffer;
10195}
10196
Andy Hungee58e4a2023-07-07 13:47:37 -070010197void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010198{
Andy Hung972bec12023-08-31 16:13:39 -070010199 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010200 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010201 if (record->getSource()) {
10202 mSource = record->getSource();
10203 }
Eric Laurent83b88082014-06-20 18:31:16 -070010204}
10205
Andy Hungee58e4a2023-07-07 13:47:37 -070010206void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010207{
Andy Hung972bec12023-08-31 16:13:39 -070010208 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010209 if (mSource == record->getSource()) {
10210 mSource = mInput;
10211 }
Eric Laurent83b88082014-06-20 18:31:16 -070010212 destroyTrack_l(record);
10213}
10214
Andy Hungee58e4a2023-07-07 13:47:37 -070010215void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010216{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010217 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010218 config->role = AUDIO_PORT_ROLE_SINK;
10219 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10220 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010221 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10222 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10223 config->flags.input = mInput->flags;
10224 }
Eric Laurent83b88082014-06-20 18:31:16 -070010225}
Eric Laurent1c333e22014-05-20 10:48:17 -070010226
Atneya Nairaa3afcb2024-10-08 16:36:19 -070010227std::string RecordThread::getLocalLogHeader() const {
10228 using namespace std::literals;
10229 static constexpr auto indent = " "
10230 " "sv;
10231 return std::string{indent}.append(IAfRecordTrack::getLogHeader());
10232}
10233
Eric Laurent6acd1d42017-01-04 14:23:29 -080010234// ----------------------------------------------------------------------------
10235// Mmap
10236// ----------------------------------------------------------------------------
10237
Andy Hung7aa7d102023-07-07 15:58:48 -070010238// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10239// MmapPlaybackThread or MmapCaptureThread instance.
10240class MmapThreadHandle : public MmapStreamInterface {
10241public:
10242 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10243 ~MmapThreadHandle() override;
10244
10245 // MmapStreamInterface virtuals
10246 status_t createMmapBuffer(int32_t minSizeFrames,
10247 struct audio_mmap_buffer_info* info) final;
10248 status_t getMmapPosition(struct audio_mmap_position* position) final;
10249 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10250 status_t start(const AudioClient& client,
10251 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10252 status_t stop(audio_port_handle_t handle) final;
10253 status_t standby() final;
10254 status_t reportData(const void* buffer, size_t frameCount) final;
10255private:
10256 const sp<IAfMmapThread> mThread;
10257};
10258
10259/* static */
10260sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10261 const sp<IAfMmapThread>& mmapThread) {
10262 return sp<MmapThreadHandle>::make(mmapThread);
10263}
10264
10265MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266 : mThread(thread)
10267{
Phil Burk9fabbf82017-08-03 12:02:00 -070010268 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269}
10270
Andy Hung7aa7d102023-07-07 15:58:48 -070010271// MmapStreamInterface could be directly implemented by MmapThread excepting this
10272// special handling on adapter dtor.
10273MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010274{
Phil Burk9fabbf82017-08-03 12:02:00 -070010275 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276}
10277
Andy Hung7aa7d102023-07-07 15:58:48 -070010278status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279 struct audio_mmap_buffer_info *info)
10280{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010281 return mThread->createMmapBuffer(minSizeFrames, info);
10282}
10283
Andy Hung7aa7d102023-07-07 15:58:48 -070010284status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010285{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010286 return mThread->getMmapPosition(position);
10287}
10288
Andy Hung7aa7d102023-07-07 15:58:48 -070010289status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010290 int64_t *timeNanos) {
10291 return mThread->getExternalPosition(position, timeNanos);
10292}
10293
Andy Hung7aa7d102023-07-07 15:58:48 -070010294status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010295 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010296{
jiabind1f1cb62020-03-24 11:57:57 -070010297 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298}
10299
Andy Hung7aa7d102023-07-07 15:58:48 -070010300status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010301{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010302 return mThread->stop(handle);
10303}
10304
Andy Hung7aa7d102023-07-07 15:58:48 -070010305status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010306{
Eric Laurent18b57012017-02-13 16:23:52 -080010307 return mThread->standby();
10308}
10309
Andy Hung7aa7d102023-07-07 15:58:48 -070010310status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10311{
jiabinfc791ee2023-02-15 19:43:40 +000010312 return mThread->reportData(buffer, frameCount);
10313}
10314
Eric Laurent6acd1d42017-01-04 14:23:29 -080010315
Andy Hungee58e4a2023-07-07 13:47:37 -070010316MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010317 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010318 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010319 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010320 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010321 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010322 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010323 mActiveTracks(&this->mLocalLog),
10324 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10325 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010326{
Eric Laurent18b57012017-02-13 16:23:52 -080010327 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010328 readHalParameters_l();
10329}
10330
Andy Hungee58e4a2023-07-07 13:47:37 -070010331void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332{
10333 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10334}
10335
Andy Hungee58e4a2023-07-07 13:47:37 -070010336void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337{
Andy Hung8d31fd22023-06-26 19:20:57 -070010338 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010339 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010340 {
Andy Hung972bec12023-08-31 16:13:39 -070010341 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010342 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010343 activeTracks.add(t);
10344 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010345 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010346 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010347 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348 stop(t->portId());
10349 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010350 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010351 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010352 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010354 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010355 }
10356}
10357
10358
Andy Hung8d672e02023-09-15 18:19:28 -070010359void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360 audio_stream_type_t streamType __unused,
10361 audio_session_t sessionId,
10362 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010363 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010364 audio_port_handle_t portId)
10365{
10366 mAttr = *attr;
10367 mSessionId = sessionId;
10368 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010369 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010370 mPortId = portId;
10371}
10372
Andy Hungee58e4a2023-07-07 13:47:37 -070010373status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374 struct audio_mmap_buffer_info *info)
10375{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010376 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377 if (mHalStream == 0) {
10378 return NO_INIT;
10379 }
Eric Laurent18b57012017-02-13 16:23:52 -080010380 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010381 return mHalStream->createMmapBuffer(minSizeFrames, info);
10382}
10383
Andy Hungee58e4a2023-07-07 13:47:37 -070010384status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010386 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387 if (mHalStream == 0) {
10388 return NO_INIT;
10389 }
10390 return mHalStream->getMmapPosition(position);
10391}
10392
Andy Hungee58e4a2023-07-07 13:47:37 -070010393status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010394{
Eric Laurentdda206a2022-07-08 17:28:35 +020010395 // The HAL must receive track metadata before starting the stream
10396 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010397 status_t ret = mHalStream->start();
10398 if (ret != NO_ERROR) {
10399 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10400 return ret;
10401 }
Andy Hungcf10d742020-04-28 15:38:24 -070010402 if (mStandby) {
10403 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010404 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010405 mStandby = false;
10406 }
Eric Laurent331679c2018-04-16 17:03:16 -070010407 return NO_ERROR;
10408}
10409
Andy Hungee58e4a2023-07-07 13:47:37 -070010410status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010411 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010412 audio_port_handle_t *handle)
10413{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010414 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010415 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010416 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010417 if (mHalStream == 0) {
10418 return NO_INIT;
10419 }
10420
10421 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422
Eric Laurentdda206a2022-07-08 17:28:35 +020010423 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010424 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010425 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010426 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010427 }
10428
10429 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10430
10431 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010432 AttributionSourceState adjAttributionSource;
10433 if (!com::android::media::audio::audioserver_permissions()) {
10434 adjAttributionSource = afutils::checkAttributionSourcePackage(
10435 client.attributionSource);
10436 } else {
10437 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10438 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10439 client.attributionSource,
10440 mAfThreadCallback->getPermissionProvider()
10441 );
10442 if (!validatedRes.has_value()) {
10443 ALOGE("MMAP client package validation fail: %s",
10444 validatedRes.error().toString8().c_str());
10445 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10446 }
10447 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10448 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010449
Andy Hung3f49ebb2023-09-19 14:48:41 -070010450 const auto localSessionId = mSessionId;
10451 auto localAttr = mAttr;
Andy Hung6b137d12024-08-27 22:35:17 +000010452 float volume = 0.0f;
Eric Laurenta54f1282017-07-01 19:39:32 -070010453 if (isOutput()) {
10454 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10455 config.sample_rate = mSampleRate;
10456 config.channel_mask = mChannelMask;
10457 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010458 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010459 audio_output_flags_t flags =
10460 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010461 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010462 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010463 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010464 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010465 mutex().unlock();
10466 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10467 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010468 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010469 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010470 &config,
10471 flags,
10472 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010473 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010474 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010475 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +000010476 &isBitPerfect,
10477 &volume);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010478 mutex().lock();
10479 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010480 ALOGD_IF(!secondaryOutputs.empty(),
10481 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010483 audio_config_base_t config;
10484 config.sample_rate = mSampleRate;
10485 config.channel_mask = mChannelMask;
10486 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010487 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010488 mutex().unlock();
10489 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010490 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010491 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010492 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010493 &config,
10494 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10495 &deviceId,
10496 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010497 mutex().lock();
10498 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010499 }
10500 // APM should not chose a different input or output stream for the same set of attributes
10501 // and audo configuration
10502 if (ret != NO_ERROR || io != mId) {
10503 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10504 __FUNCTION__, ret, io, mId);
10505 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010506 }
10507
10508 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010509 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010510 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010511 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 } else {
jiabin09609032022-06-15 19:26:01 +000010513 {
10514 // Add the track record before starting input so that the silent status for the
10515 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010516 setClientSilencedState_l(portId, false /*silenced*/);
10517 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010518 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010519 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010520 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521 }
10522
10523 // abort if start is rejected by audio policy manager
10524 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010525 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010526 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010527 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010528 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010529 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010530 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010531 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010532 }
Andy Hungc5007f82023-08-29 14:26:09 -070010533 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010534 } else {
10535 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536 }
jiabin09609032022-06-15 19:26:01 +000010537 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010538 return PERMISSION_DENIED;
10539 }
10540
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010541 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010542 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10543 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010544 mChannelMask, mSessionId, isOutput(),
10545 client.attributionSource,
Andy Hung6b137d12024-08-27 22:35:17 +000010546 IPCThreadState::self()->getCallingPid(), portId,
10547 volume);
jiabin09609032022-06-15 19:26:01 +000010548 if (!isOutput()) {
10549 track->setSilenced_l(isClientSilenced_l(portId));
10550 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551
Eric Laurent4eb58f12018-12-07 16:41:02 -080010552 if (isOutput()) {
10553 // force volume update when a new track is added
10554 mHalVolFloat = -1.0f;
10555 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010556 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010557 if (t->isSilenced_l()
10558 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010559 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010560 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010561 }
10562 }
10563
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010565 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010566 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010567 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010568 chain->incTrackCnt();
10569 chain->incActiveTrackCnt();
10570 }
10571
Andy Hungc2b11cb2020-04-22 09:04:01 -070010572 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010573 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010574
10575 if (mActiveTracks.size() == 1) {
10576 ret = exitStandby_l();
10577 }
10578
Eric Laurent6acd1d42017-01-04 14:23:29 -080010579 broadcast_l();
10580
Eric Laurentdda206a2022-07-08 17:28:35 +020010581 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582
Eric Laurentdda206a2022-07-08 17:28:35 +020010583 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010584}
10585
Andy Hungee58e4a2023-07-07 13:47:37 -070010586status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010587{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010589 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010590
10591 if (mHalStream == 0) {
10592 return NO_INIT;
10593 }
10594
Eric Laurenta54f1282017-07-01 19:39:32 -070010595 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010596 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010597 return NO_ERROR;
10598 }
10599
Andy Hung8d31fd22023-06-26 19:20:57 -070010600 sp<IAfMmapTrack> track;
10601 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602 if (handle == t->portId()) {
10603 track = t;
10604 break;
10605 }
10606 }
10607 if (track == 0) {
10608 return BAD_VALUE;
10609 }
10610
10611 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010612 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010613
Andy Hungc5007f82023-08-29 14:26:09 -070010614 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010616 AudioSystem::stopOutput(track->portId());
10617 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010619 AudioSystem::stopInput(track->portId());
10620 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621 }
Andy Hungc5007f82023-08-29 14:26:09 -070010622 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623
Andy Hung116bc262023-06-20 18:56:17 -070010624 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010625 if (chain != 0) {
10626 chain->decActiveTrackCnt();
10627 chain->decTrackCnt();
10628 }
10629
Eric Laurentdda206a2022-07-08 17:28:35 +020010630 if (mActiveTracks.isEmpty()) {
10631 mHalStream->stop();
10632 }
10633
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634 broadcast_l();
10635
Eric Laurent6acd1d42017-01-04 14:23:29 -080010636 return NO_ERROR;
10637}
10638
Andy Hungee58e4a2023-07-07 13:47:37 -070010639status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010640NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010641{
10642 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010643 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010644
10645 if (mHalStream == 0) {
10646 return NO_INIT;
10647 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010648 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010649 return INVALID_OPERATION;
10650 }
10651 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010652 if (!mStandby) {
10653 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010654 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010655 mStandby = true;
10656 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010657 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010658 return NO_ERROR;
10659}
10660
Andy Hungee58e4a2023-07-07 13:47:37 -070010661status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010662 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10663 return INVALID_OPERATION;
10664}
10665
Andy Hungee58e4a2023-07-07 13:47:37 -070010666void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010667{
10668 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10669 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10670 mFormat = mHALFormat;
10671 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10672 result = mHalStream->getFrameSize(&mFrameSize);
10673 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010674 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10675 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676 result = mHalStream->getBufferSize(&mBufferSize);
10677 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10678 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010679
Andy Hungcf10d742020-04-28 15:38:24 -070010680 // TODO: make a readHalParameters call?
10681 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010682 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010683 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010684 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10685 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10686 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10687 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10688 /*
10689 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10690 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10691 (int32_t)mHapticChannelMask)
10692 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10693 (int32_t)mHapticChannelCount)
10694 */
10695 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010696 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010697 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10698 (int32_t)mFrameCount) // sic - added HAL
10699 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700}
10701
Andy Hungee58e4a2023-07-07 13:47:37 -070010702bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010703{
Andy Hungab65b182023-09-06 19:41:47 -070010704 {
10705 audio_utils::unique_lock _l(mutex());
10706 checkSilentMode_l();
10707 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708
10709 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10710
10711 while (!exitPending())
10712 {
Andy Hung116bc262023-06-20 18:56:17 -070010713 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714
Andy Hung13850be2019-03-14 11:33:09 -070010715 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010716 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010717
Eric Laurent6acd1d42017-01-04 14:23:29 -080010718 if (mSignalPending) {
10719 // A signal was raised while we were unlocked
10720 mSignalPending = false;
10721 } else {
10722 if (mConfigEvents.isEmpty()) {
10723 // we're about to wait, flush the binder command buffer
10724 IPCThreadState::self()->flushCommands();
10725
10726 if (exitPending()) {
10727 break;
10728 }
10729
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010731 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010732 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010733 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010734
10735 checkSilentMode_l();
10736
10737 continue;
10738 }
10739 }
10740
10741 processConfigEvents_l();
10742
10743 processVolume_l();
10744
10745 checkInvalidTracks_l();
10746
Andy Hungab65b182023-09-06 19:41:47 -070010747 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010748
Kevin Rocard069c2712018-03-29 19:09:14 -070010749 updateMetadata_l();
10750
Eric Laurent6acd1d42017-01-04 14:23:29 -080010751 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010752 } // release Thread lock
10753
Eric Laurent6acd1d42017-01-04 14:23:29 -080010754 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010755 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010756 }
Andy Hung13850be2019-03-14 11:33:09 -070010757
10758 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010759 unlockEffectChains(effectChains);
10760 // Effect chains will be actually deleted here if they were removed from
10761 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010762 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010764 mThreadloopExecutor.process(); // process any remaining deferred actions.
10765 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010766
10767 threadLoop_exit();
10768
10769 if (!mStandby) {
10770 threadLoop_standby();
10771 mStandby = true;
10772 }
10773
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 ALOGV("Thread %p type %d exiting", this, mType);
10775 return false;
10776}
10777
Andy Hungc5007f82023-08-29 14:26:09 -070010778// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010779bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780 status_t& status)
10781{
10782 AudioParameter param = AudioParameter(keyValuePair);
10783 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010784 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010785 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010786 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010788 if (sendToHal) {
10789 status = mHalStream->setParameters(keyValuePair);
10790 } else {
10791 status = NO_ERROR;
10792 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793
10794 return false;
10795}
10796
Andy Hungee58e4a2023-07-07 13:47:37 -070010797String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798{
Andy Hung972bec12023-08-31 16:13:39 -070010799 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010800 String8 out_s8;
10801 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10802 return out_s8;
10803 }
Andy Hung920f6572022-10-06 12:09:49 -070010804 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010805}
10806
Andy Hungab65b182023-09-06 19:41:47 -070010807void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010808 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010809 sp<AudioIoDescriptor> desc;
10810 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010811 switch (event) {
10812 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010813 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010815 isInput = true;
10816 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010817 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010818 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010820 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10821 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010822 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823 case AUDIO_INPUT_CLOSED:
10824 case AUDIO_OUTPUT_CLOSED:
10825 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010826 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827 break;
10828 }
Andy Hungab65b182023-09-06 19:41:47 -070010829 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830}
10831
Andy Hungee58e4a2023-07-07 13:47:37 -070010832status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010834NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010835{
10836 status_t status = NO_ERROR;
10837
10838 // store new device and send to effects
10839 audio_devices_t type = AUDIO_DEVICE_NONE;
10840 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010841 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10842 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10843 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844 if (isOutput()) {
10845 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010846 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10847 && !mAudioHwDev->supportsAudioPatches(),
10848 "Enumerated device type(%#x) must not be used "
10849 "as it does not support audio patches",
10850 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010851 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010852 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10853 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854 }
10855 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010856 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010857 } else {
10858 type = patch->sources[0].ext.device.type;
10859 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010860 numDevices = mPatch.num_sources;
10861 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010862 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010863 }
10864
10865 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010866 if (isOutput()) {
10867 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10868 } else {
10869 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10870 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010871 }
10872
jiabinc52b1ff2019-10-31 17:20:42 -070010873 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010874 // store new source and send to effects
10875 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10876 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10877 for (size_t i = 0; i < mEffectChains.size(); i++) {
10878 mEffectChains[i]->setAudioSource_l(mAudioSource);
10879 }
10880 }
10881 }
10882
jiabin78b86f22024-02-22 00:39:29 +000010883 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10884 // okay to notify the client earlier before the new patch creation.
10885 if (mDeviceId != deviceId) {
10886 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10887 // The aaudioservice handle the routing changed event asynchronously. In that case,
10888 // it is safe to hold the lock here.
10889 callback->onRoutingChanged(deviceId);
10890 }
10891 }
10892
Eric Laurent6acd1d42017-01-04 14:23:29 -080010893 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010894 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10895 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010897 audio_port_config port;
10898 std::optional<audio_source_t> source;
10899 if (isOutput()) {
10900 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010901 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010902 port = patch->sources[0];
10903 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010904 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010905 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010906 *handle = AUDIO_PATCH_HANDLE_NONE;
10907 }
10908
jiabinc52b1ff2019-10-31 17:20:42 -070010909 if (numDevices == 0 || mDeviceId != deviceId) {
10910 if (isOutput()) {
10911 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10912 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010913 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010914 } else {
10915 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10916 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10917 }
jiabinc52b1ff2019-10-31 17:20:42 -070010918 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010919 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010920 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010921 // Force meteadata update after a route change
10922 mActiveTracks.setHasChanged();
10923
Eric Laurent6acd1d42017-01-04 14:23:29 -080010924 return status;
10925}
10926
Andy Hungee58e4a2023-07-07 13:47:37 -070010927status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928{
10929 status_t status = NO_ERROR;
10930
jiabinc52b1ff2019-10-31 17:20:42 -070010931 mPatch = audio_patch{};
10932 mOutDeviceTypeAddrs.clear();
10933 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010934
10935 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10936 supportsAudioPatches : false;
10937
10938 if (supportsAudioPatches) {
10939 status = mHalDevice->releaseAudioPatch(handle);
10940 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010941 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010943 // Force meteadata update after a route change
10944 mActiveTracks.setHasChanged();
10945
Eric Laurent6acd1d42017-01-04 14:23:29 -080010946 return status;
10947}
10948
Andy Hungee58e4a2023-07-07 13:47:37 -070010949void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010950NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010951{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010952 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010953 if (isOutput()) {
10954 config->role = AUDIO_PORT_ROLE_SOURCE;
10955 config->ext.mix.hw_module = mAudioHwDev->handle();
10956 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10957 } else {
10958 config->role = AUDIO_PORT_ROLE_SINK;
10959 config->ext.mix.hw_module = mAudioHwDev->handle();
10960 config->ext.mix.usecase.source = mAudioSource;
10961 }
10962}
10963
Andy Hungee58e4a2023-07-07 13:47:37 -070010964status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010965{
10966 audio_session_t session = chain->sessionId();
10967
10968 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10969 // Attach all tracks with same session ID to this chain.
10970 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010971 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972 if (session == track->sessionId()) {
10973 chain->incTrackCnt();
10974 chain->incActiveTrackCnt();
10975 }
10976 }
10977
10978 chain->setThread(this);
10979 chain->setInBuffer(nullptr);
10980 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010981 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010982
10983 mEffectChains.add(chain);
10984 checkSuspendOnAddEffectChain_l(chain);
10985 return NO_ERROR;
10986}
10987
Andy Hungee58e4a2023-07-07 13:47:37 -070010988size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010989{
10990 audio_session_t session = chain->sessionId();
10991
10992 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10993
10994 for (size_t i = 0; i < mEffectChains.size(); i++) {
10995 if (chain == mEffectChains[i]) {
10996 mEffectChains.removeAt(i);
10997 // detach all active tracks from the chain
10998 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010999 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011000 if (session == track->sessionId()) {
11001 chain->decActiveTrackCnt();
11002 chain->decTrackCnt();
11003 }
11004 }
11005 break;
11006 }
11007 }
11008 return mEffectChains.size();
11009}
11010
Andy Hungee58e4a2023-07-07 13:47:37 -070011011void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011012{
11013 mHalStream->standby();
11014}
11015
Andy Hungee58e4a2023-07-07 13:47:37 -070011016void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011017{
Phil Burk7dce7282017-09-27 13:51:41 -070011018 // Do not call callback->onTearDown() because it is redundant for thread exit
11019 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080011020}
11021
Andy Hungee58e4a2023-07-07 13:47:37 -070011022status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011023{
11024 return BAD_VALUE;
11025}
11026
Andy Hungee58e4a2023-07-07 13:47:37 -070011027bool MmapThread::isValidSyncEvent(
11028 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011029{
11030 return false;
11031}
11032
Andy Hungee58e4a2023-07-07 13:47:37 -070011033status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080011034 const effect_descriptor_t *desc, audio_session_t sessionId)
11035{
11036 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080011037 if (audio_is_global_session(sessionId)) {
11038 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080011039 desc->name, mThreadName);
11040 return BAD_VALUE;
11041 }
11042
11043 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11044 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11045 desc->name);
11046 return BAD_VALUE;
11047 }
11048 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011049 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11050 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051 return BAD_VALUE;
11052 }
11053
11054 // Only allow effects without processing load or latency
11055 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11056 return BAD_VALUE;
11057 }
11058
Andy Hung116bc262023-06-20 18:56:17 -070011059 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011060 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11061 return BAD_VALUE;
11062 }
11063
Eric Laurent6acd1d42017-01-04 14:23:29 -080011064 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011065}
11066
Andy Hungee58e4a2023-07-07 13:47:37 -070011067void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011068{
Andy Hung8d31fd22023-06-26 19:20:57 -070011069 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011070 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011071 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11072 // The aaudioservice handle the routing changed event asynchronously. In that case,
11073 // it is safe to hold the lock here.
11074 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
11075 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011076 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11077 mNoCallbackWarningCount++;
11078 }
11079 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011080 }
11081 }
11082}
11083
Andy Hungee58e4a2023-07-07 13:47:37 -070011084void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011085{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011086 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11087 mAttr.content_type, mAttr.usage, mAttr.source);
11088 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011089 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011090 dprintf(fd, " No active clients\n");
11091 }
11092}
11093
Andy Hungee58e4a2023-07-07 13:47:37 -070011094void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011095{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011096 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011097 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011098 dprintf(fd, " %zu Tracks\n", numtracks);
11099 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011100 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011101 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011102 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011103 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011104 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011105 result.append(prefix);
11106 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011107 }
11108 } else {
11109 dprintf(fd, "\n");
11110 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011111 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011112}
11113
Atneya Nairaa3afcb2024-10-08 16:36:19 -070011114std::string MmapThread::getLocalLogHeader() const {
11115 using namespace std::literals;
11116 static constexpr auto indent = " "
11117 " "sv;
11118 return std::string{indent}.append(IAfMmapTrack::getLogHeader());
11119}
11120
Andy Hungee58e4a2023-07-07 13:47:37 -070011121/* static */
11122sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011123 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011124 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011125 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011126}
11127
11128MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011129 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011130 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011131 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011132 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011133 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011134{
11135 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11136 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011137 mMasterVolume = afThreadCallback->masterVolume_l();
11138 mMasterMute = afThreadCallback->masterMute_l();
Andy Hung6b137d12024-08-27 22:35:17 +000011139 if (!audioserver_flags::portid_volume_management()) {
11140 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11141 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11142 mStreamTypes[stream].volume = 0.0f;
11143 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11144 }
11145 // Audio patch and call assistant volume are always max
11146 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11147 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11148 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11149 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011150 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011151 if (mAudioHwDev) {
11152 if (mAudioHwDev->canSetMasterVolume()) {
11153 mMasterVolume = 1.0;
11154 }
11155
11156 if (mAudioHwDev->canSetMasterMute()) {
11157 mMasterMute = false;
11158 }
11159 }
11160}
11161
Andy Hungee58e4a2023-07-07 13:47:37 -070011162void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011163 audio_stream_type_t streamType,
11164 audio_session_t sessionId,
11165 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011166 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011167 audio_port_handle_t portId)
11168{
Andy Hung8d672e02023-09-15 18:19:28 -070011169 audio_utils::lock_guard l(mutex());
11170 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011171 mStreamType = streamType;
11172}
11173
Andy Hungee58e4a2023-07-07 13:47:37 -070011174AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011175{
Andy Hung972bec12023-08-31 16:13:39 -070011176 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011177 AudioStreamOut *output = mOutput;
11178 mOutput = NULL;
11179 return output;
11180}
11181
Andy Hungee58e4a2023-07-07 13:47:37 -070011182void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011183{
Andy Hung972bec12023-08-31 16:13:39 -070011184 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011185 // Don't apply master volume in SW if our HAL can do it for us.
11186 if (mAudioHwDev &&
11187 mAudioHwDev->canSetMasterVolume()) {
11188 mMasterVolume = 1.0;
11189 } else {
11190 mMasterVolume = value;
11191 }
11192}
11193
Andy Hungee58e4a2023-07-07 13:47:37 -070011194void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011195{
Andy Hung972bec12023-08-31 16:13:39 -070011196 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011197 // Don't apply master mute in SW if our HAL can do it for us.
11198 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11199 mMasterMute = false;
11200 } else {
11201 mMasterMute = muted;
11202 }
11203}
11204
Andy Hungee58e4a2023-07-07 13:47:37 -070011205void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011206{
Andy Hung972bec12023-08-31 16:13:39 -070011207 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011208 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011209 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011210 broadcast_l();
11211 }
11212}
11213
Andy Hungee58e4a2023-07-07 13:47:37 -070011214float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011215{
Andy Hung972bec12023-08-31 16:13:39 -070011216 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011217 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011218}
11219
Andy Hungee58e4a2023-07-07 13:47:37 -070011220void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011221{
Andy Hung972bec12023-08-31 16:13:39 -070011222 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011223 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011224 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011225 broadcast_l();
11226 }
11227}
11228
Andy Hung6b137d12024-08-27 22:35:17 +000011229status_t MmapPlaybackThread::setPortsVolume(
11230 const std::vector<audio_port_handle_t>& portIds, float volume) {
11231 audio_utils::lock_guard _l(mutex());
11232 for (const auto& portId : portIds) {
11233 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11234 if (portId == track->portId()) {
11235 track->setPortVolume(volume);
11236 break;
11237 }
11238 }
11239 }
11240 broadcast_l();
11241 return NO_ERROR;
11242}
11243
Andy Hungee58e4a2023-07-07 13:47:37 -070011244void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011245{
Andy Hung972bec12023-08-31 16:13:39 -070011246 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011247 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011248 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011249 track->invalidate();
11250 }
11251 broadcast_l();
11252 }
11253}
11254
Andy Hungee58e4a2023-07-07 13:47:37 -070011255void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011256{
Andy Hung972bec12023-08-31 16:13:39 -070011257 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011258 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011259 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011260 if (portIds.find(track->portId()) != portIds.end()) {
11261 track->invalidate();
11262 trackMatch = true;
11263 portIds.erase(track->portId());
11264 }
11265 if (portIds.empty()) {
11266 break;
11267 }
11268 }
11269 if (trackMatch) {
11270 broadcast_l();
11271 }
11272}
11273
Andy Hungee58e4a2023-07-07 13:47:37 -070011274void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011275NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011276{
Andy Hung6b137d12024-08-27 22:35:17 +000011277 float volume = 0;
11278 if (!audioserver_flags::portid_volume_management()) {
11279 if (mMasterMute || streamMuted_l()) {
11280 volume = 0;
11281 } else {
11282 volume = mMasterVolume * streamVolume_l();
11283 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011284 } else {
Andy Hung6b137d12024-08-27 22:35:17 +000011285 if (mMasterMute) {
11286 volume = 0;
11287 } else {
11288 // All mmap tracks are declared with the same audio attributes to the audio policy
11289 // manager. Hence, they follow the same routing / volume group. Any change of volume
11290 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11291 size_t numtracks = mActiveTracks.size();
11292 if (numtracks) {
11293 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11294 }
11295 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011296 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011297 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011298 // Convert volumes from float to 8.24
11299 uint32_t vol = (uint32_t)(volume * (1 << 24));
11300
11301 // Delegate volume control to effect in track effect chain if needed
11302 // only one effect chain can be present on DirectOutputThread, so if
11303 // there is one, the track is connected to it
11304 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011305 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011306 volume = (float)vol / (1 << 24);
11307 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011308 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011309 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11310 mHalVolFloat = volume; // HW volume control worked, so update value.
11311 mNoCallbackWarningCount = 0;
11312 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011313 sp<MmapStreamCallback> callback = mCallback.promote();
11314 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011315 mHalVolFloat = volume; // SW volume control worked, so update value.
11316 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011317 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011318 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011319 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011320 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011321 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11322 ALOGW("Could not set MMAP stream volume: no volume callback!");
11323 mNoCallbackWarningCount++;
11324 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011325 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011326 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011327 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011328 track->setMetadataHasChanged();
Andy Hung6b137d12024-08-27 22:35:17 +000011329 if (!audioserver_flags::portid_volume_management()) {
11330 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11331 /*muteState=*/{mMasterMute,
11332 streamVolume_l() == 0.f,
11333 streamMuted_l(),
11334 // TODO(b/241533526): adjust logic to include mute from AppOps
11335 false /*muteFromPlaybackRestricted*/,
11336 false /*muteFromClientVolume*/,
11337 false /*muteFromVolumeShaper*/});
11338 } else {
11339 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11340 /*muteState=*/{mMasterMute,
11341 track->getPortVolume() == 0.f,
11342 /* muteFromStreamMuted= */ false,
11343 // TODO(b/241533526): adjust logic to include mute from AppOps
11344 false /*muteFromPlaybackRestricted*/,
11345 false /*muteFromClientVolume*/,
11346 false /*muteFromVolumeShaper*/});
11347 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011348 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011349 }
11350}
11351
Andy Hungee58e4a2023-07-07 13:47:37 -070011352ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011353{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011354 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011355 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011356 }
11357 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011358 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011359 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011360 playback_track_metadata_v7_t trackMetadata;
11361 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011362 .usage = track->attributes().usage,
11363 .content_type = track->attributes().content_type,
11364 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011365 };
11366 trackMetadata.channel_mask = track->channelMask(),
11367 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11368 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011369 }
11370 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011371
11372 MetadataUpdate change;
11373 change.playbackMetadataUpdate = metadata.tracks;
11374 return change;
11375};
Kevin Rocard069c2712018-03-29 19:09:14 -070011376
Andy Hungee58e4a2023-07-07 13:47:37 -070011377void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011378{
11379 if (!mMasterMute) {
11380 char value[PROPERTY_VALUE_MAX];
11381 if (property_get("ro.audio.silent", value, "0") > 0) {
11382 char *endptr;
11383 unsigned long ul = strtoul(value, &endptr, 0);
11384 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011385 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011386 // The setprop command will not allow a property to be changed after
11387 // the first time it is set, so we don't have to worry about un-muting.
11388 setMasterMute_l(true);
11389 }
11390 }
11391 }
11392}
11393
Andy Hungee58e4a2023-07-07 13:47:37 -070011394void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011395{
11396 MmapThread::toAudioPortConfig(config);
11397 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11398 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11399 config->flags.output = mOutput->flags;
11400 }
11401}
11402
Andy Hungee58e4a2023-07-07 13:47:37 -070011403status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011404 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011405{
11406 if (mOutput == nullptr) {
11407 return NO_INIT;
11408 }
11409 struct timespec timestamp;
11410 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11411 if (status == NO_ERROR) {
11412 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11413 }
11414 return status;
11415}
11416
Andy Hungee58e4a2023-07-07 13:47:37 -070011417status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011418 // Send to MelProcessor for sound dose measurement.
11419 auto processor = mMelProcessor.load();
11420 if (processor) {
11421 processor->process(buffer, frameCount * mFrameSize);
11422 }
11423
jiabinfc791ee2023-02-15 19:43:40 +000011424 return NO_ERROR;
11425}
11426
Andy Hungc5007f82023-08-29 14:26:09 -070011427// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011428void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011429 const sp<audio_utils::MelProcessor>& processor)
11430{
11431 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011432 mMelProcessor.store(processor);
11433 if (processor) {
11434 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011435 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011436
11437 // no need to update output format for MMapPlaybackThread since it is
11438 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011439}
11440
Andy Hungc5007f82023-08-29 14:26:09 -070011441// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011442void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011443{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011444 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11445 auto melProcessor = mMelProcessor.load();
11446 if (melProcessor != nullptr) {
11447 melProcessor->pause();
11448 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011449}
11450
Andy Hungee58e4a2023-07-07 13:47:37 -070011451void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011452{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011453 MmapThread::dumpInternals_l(fd, args);
Andy Hung6b137d12024-08-27 22:35:17 +000011454 if (!audioserver_flags::portid_volume_management()) {
11455 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11456 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11457 } else {
11458 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11459 }
11460 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011461 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11462}
11463
Andy Hungee58e4a2023-07-07 13:47:37 -070011464/* static */
11465sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011466 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011467 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011468 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011469}
11470
11471MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011472 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011473 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011474 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011475 mInput(input)
11476{
11477 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11478 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11479}
11480
Andy Hungee58e4a2023-07-07 13:47:37 -070011481status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011482{
Phil Burkf054fc32018-12-06 09:45:59 -080011483 {
11484 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011485 if (mInput != nullptr && mInput->stream != nullptr) {
11486 mInput->stream->setGain(1.0f);
11487 }
11488 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011489 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011490}
11491
Andy Hungee58e4a2023-07-07 13:47:37 -070011492AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011493{
Andy Hung972bec12023-08-31 16:13:39 -070011494 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011495 AudioStreamIn *input = mInput;
11496 mInput = NULL;
11497 return input;
11498}
Kevin Rocard069c2712018-03-29 19:09:14 -070011499
Andy Hungee58e4a2023-07-07 13:47:37 -070011500void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011501{
11502 bool changed = false;
11503 bool silenced = false;
11504
11505 sp<MmapStreamCallback> callback = mCallback.promote();
11506 if (callback == 0) {
11507 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11508 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11509 mNoCallbackWarningCount++;
11510 }
11511 }
11512
11513 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11514 // track is silenced and unmute otherwise
11515 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11516 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11517 changed = true;
11518 silenced = mActiveTracks[i]->isSilenced_l();
11519 }
11520 }
11521
11522 if (changed) {
11523 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11524 }
11525}
11526
Andy Hungee58e4a2023-07-07 13:47:37 -070011527ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011528{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011529 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011530 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011531 }
11532 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011533 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011534 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011535 record_track_metadata_v7_t trackMetadata;
11536 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011537 .source = track->attributes().source,
11538 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011539 };
11540 trackMetadata.channel_mask = track->channelMask(),
11541 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11542 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011543 }
11544 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011545 MetadataUpdate change;
11546 change.recordMetadataUpdate = metadata.tracks;
11547 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011548}
11549
Andy Hungee58e4a2023-07-07 13:47:37 -070011550void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011551{
Andy Hung972bec12023-08-31 16:13:39 -070011552 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011553 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011554 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011555 mActiveTracks[i]->setSilenced_l(silenced);
11556 broadcast_l();
11557 }
11558 }
jiabin09609032022-06-15 19:26:01 +000011559 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011560}
11561
Andy Hungee58e4a2023-07-07 13:47:37 -070011562void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011563{
11564 MmapThread::toAudioPortConfig(config);
11565 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11566 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11567 config->flags.input = mInput->flags;
11568 }
11569}
11570
Andy Hungee58e4a2023-07-07 13:47:37 -070011571status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011572 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011573{
11574 if (mInput == nullptr) {
11575 return NO_INIT;
11576 }
11577 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11578}
11579
jiabinc658e452022-10-21 20:52:21 +000011580// ----------------------------------------------------------------------------
11581
Andy Hungee58e4a2023-07-07 13:47:37 -070011582/* static */
11583sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011584 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011585 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011586 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011587}
11588
Andy Hung583043b2023-07-17 17:05:00 -070011589BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011590 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011591 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011592
Andy Hungee58e4a2023-07-07 13:47:37 -070011593PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011594 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011595 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11596 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011597 float volumeLeft = 1.0f;
11598 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011599 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11600 bitPerfectTrack != nullptr) {
11601 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011602 mAudioMixer->setParameter(
11603 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11604 mAudioMixer->setParameter(
11605 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11606 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011607 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011608 mIsBitPerfect = true;
11609 } else {
11610 mIsBitPerfect = false;
11611 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11612 // active.
11613 for (const auto& track : mActiveTracks) {
11614 const int trackId = track->id();
11615 mAudioMixer->setParameter(
11616 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11617 }
11618 }
jiabin76d94692022-12-15 21:51:21 +000011619 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11620 mVolumeLeft = volumeLeft;
11621 mVolumeRight = volumeRight;
11622 setVolumeForOutput_l(volumeLeft, volumeRight);
11623 }
jiabinc658e452022-10-21 20:52:21 +000011624 return result;
11625}
11626
Andy Hungee58e4a2023-07-07 13:47:37 -070011627void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011628 MixerThread::threadLoop_mix();
11629 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11630}
11631
jiabin220eea12024-05-17 17:55:20 +000011632void BitPerfectThread::setTracksInternalMute(
11633 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
jiabin783a1eb2024-09-18 22:36:19 +000011634 audio_utils::lock_guard _l(mutex());
jiabin220eea12024-05-17 17:55:20 +000011635 for (auto& track : mTracks) {
11636 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11637 track->setInternalMute(it->second);
11638 tracksInternalMute->erase(it);
11639 }
11640 }
11641}
11642
11643sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11644 if (com::android::media::audioserver::
11645 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11646 sp<IAfTrack> bitPerfectTrack = nullptr;
11647 bool allOtherTracksMuted = true;
11648 // Return the bit perfect track if all other tracks are muted
11649 for (const auto& track : mActiveTracks) {
11650 if (track->isBitPerfect()) {
jiabin783a1eb2024-09-18 22:36:19 +000011651 if (track->getInternalMute()) {
11652 // There can only be one bit-perfect client active. If it is mute internally,
11653 // there is no need to stream bit-perfectly.
11654 break;
11655 }
jiabin220eea12024-05-17 17:55:20 +000011656 bitPerfectTrack = track;
11657 } else if (track->getFinalVolume() != 0.f) {
11658 allOtherTracksMuted = false;
11659 if (bitPerfectTrack != nullptr) {
11660 break;
11661 }
11662 }
11663 }
11664 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11665 } else {
11666 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11667 return mActiveTracks[0];
11668 }
11669 }
11670 return nullptr;
11671}
11672
Glenn Kasten63238ef2015-03-02 15:50:29 -080011673} // namespace android