blob: 7c7d812eaeeeddfcc4d0659f70f66b331ceb328d [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung25a80ac2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
jiabin220eea12024-05-17 17:55:20 +000036#include <com_android_media_audioserver.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070037#ifdef DEBUG_CPU_USAGE
38#include <audio_utils/Statistics.h>
39#include <cpustats/ThreadCpuUsage.h>
40#endif
41#include <audio_utils/channels.h>
42#include <audio_utils/format.h>
43#include <audio_utils/minifloat.h>
44#include <audio_utils/mono_blend.h>
45#include <audio_utils/primitives.h>
46#include <audio_utils/safe_math.h>
47#include <audiomanager/AudioManager.h>
48#include <binder/IPCThreadState.h>
49#include <binder/IServiceManager.h>
50#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010051#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070052#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070054#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070055#include <media/AudioContainers.h>
56#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070057#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070058#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070059#ifdef ADD_BATTERY_DATA
60#include <media/IMediaPlayerService.h>
61#include <media/IMediaDeathNotifier.h>
62#endif
63#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080064#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070065#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070066#include <media/audiohal/EffectsFactoryHalInterface.h>
67#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070068#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069#include <media/nbaio/AudioStreamOutSink.h>
70#include <media/nbaio/MonoPipe.h>
71#include <media/nbaio/MonoPipeReader.h>
72#include <media/nbaio/Pipe.h>
73#include <media/nbaio/PipeReader.h>
74#include <media/nbaio/SourceAudioBufferProvider.h>
Atneya Nair5997a652024-06-14 17:24:45 -070075#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080076#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070077#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070078#include <mediautils/SchedulingPolicyService.h>
79#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070080#include <powermanager/PowerManager.h>
81#include <private/android_filesystem_config.h>
82#include <private/media/AudioTrackShared.h>
83#include <system/audio_effects/effect_aec.h>
84#include <system/audio_effects/effect_downmix.h>
85#include <system/audio_effects/effect_ns.h>
86#include <system/audio_effects/effect_spatializer.h>
87#include <utils/Log.h>
88#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080089
Andy Hung25a80ac2023-07-19 12:47:35 -070090#include <fcntl.h>
91#include <linux/futex.h>
92#include <math.h>
93#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080094#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070095#include <sstream>
96#include <string>
97#include <sys/stat.h>
98#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100// ----------------------------------------------------------------------------
101
102// Note: the following macro is used for extremely verbose logging message. In
103// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
104// 0; but one side effect of this is to turn all LOGV's as well. Some messages
105// are so verbose that we want to suppress them even when we have ALOG_ASSERT
106// turned on. Do not uncomment the #def below unless you really know what you
107// are doing and want to see all of the extremely verbose messages.
108//#define VERY_VERY_VERBOSE_LOGGING
109#ifdef VERY_VERY_VERBOSE_LOGGING
110#define ALOGVV ALOGV
111#else
112#define ALOGVV(a...) do { } while(0)
113#endif
114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700116#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700117
Andy Hung6770c6f2015-04-07 13:43:36 -0700118template <typename T>
119static inline T min(const T& a, const T& b)
120{
121 return a < b ? a : b;
122}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700123
Atneya Nair5997a652024-06-14 17:24:45 -0700124using com::android::media::permission::ValidatedAttributionSourceState;
125
Eric Laurent81784c32012-11-19 14:55:58 -0800126namespace android {
127
Andy Hungee58e4a2023-07-07 13:47:37 -0700128using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000130using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131
Andy Hung25a80ac2023-07-19 12:47:35 -0700132// Keep in sync with java definition in media/java/android/media/AudioRecord.java
133static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// retry counts for buffer fill timeout
136// 50 * ~20msecs = 1 second
137static const int8_t kMaxTrackRetries = 50;
138static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700139
Eric Laurent81784c32012-11-19 14:55:58 -0800140// allow less retry attempts on direct output thread.
141// direct outputs can be a scarce resource in audio hardware and should
142// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700143// Notes:
144// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
145// in case the data write is bursty for the AudioTrack. The application
146// should endeavor to write at least once every kMaxTrackRetriesDirectMs
147// to prevent an underrun situation. If the data is bursty, then
148// the application can also throttle the data sent to be even.
149// 2) For compressed audio data, any data present in the AudioTrack buffer
150// will be sent and reset the retry count. This delivers data as
151// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
152// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
153// of data to be available, then any remaining data is delivered.
154// This is required to ensure the last bit of data is delivered before underrun.
155//
156// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
157// or the size of the HAL period for proportional / linear PCM tracks.
158static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800159
160// don't warn about blocked writes or record buffer overflows more often than this
161static const nsecs_t kWarningThrottleNs = seconds(5);
162
163// RecordThread loop sleep time upon application overrun or audio HAL read error
164static const int kRecordThreadSleepUs = 5000;
165
Eric Laurent10351942014-05-08 18:49:52 -0700166// maximum time to wait in sendConfigEvent_l() for a status to be received
167static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent3fddffe2024-07-31 14:18:34 +0000168// longer timeout for create audio patch to account for specific scenarii
169// with Bluetooth devices
170static const nsecs_t kCreatePatchEventTimeoutNs = seconds(4);
Eric Laurent81784c32012-11-19 14:55:58 -0800171
172// minimum sleep time for the mixer thread loop when tracks are active but in underrun
173static const uint32_t kMinThreadSleepTimeUs = 5000;
174// maximum divider applied to the active sleep time in the mixer thread loop
175static const uint32_t kMaxThreadSleepTimeShift = 2;
176
Andy Hung09a50072014-02-27 14:30:47 -0800177// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700178// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800179static const uint32_t kMinNormalSinkBufferSizeMs = 20;
180// maximum normal sink buffer size
181static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800182
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700183// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
184// FIXME This should be based on experimentally observed scheduling jitter
185static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
186
Eric Laurent972a1732013-09-04 09:42:59 -0700187// Offloaded output thread standby delay: allows track transition without going to standby
188static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
189
Eric Laurent51716182016-02-29 18:00:56 -0800190// Direct output thread minimum sleep time in idle or active(underrun) state
191static const nsecs_t kDirectMinSleepTimeUs = 10000;
192
Brian Lindahl65e90012022-07-27 18:01:07 +0200193// Minimum amount of time between checking to see if the timestamp is advancing
194// for underrun detection. If we check too frequently, we may not detect a
195// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800196static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200197
Glenn Kasten1b291842016-07-18 14:55:21 -0700198// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
199// balance between power consumption and latency, and allows threads to be scheduled reliably
200// by the CFS scheduler.
201// FIXME Express other hardcoded references to 20ms with references to this constant and move
202// it appropriately.
203#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800204
Eric Laurent81784c32012-11-19 14:55:58 -0800205// Whether to use fast mixer
206static const enum {
207 FastMixer_Never, // never initialize or use: for debugging only
208 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
209 // normal mixer multiplier is 1
210 FastMixer_Static, // initialize if needed, then use all the time if initialized,
211 // multiplier is calculated based on min & max normal mixer buffer size
212 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
213 // multiplier is calculated based on min & max normal mixer buffer size
214 // FIXME for FastMixer_Dynamic:
215 // Supporting this option will require fixing HALs that can't handle large writes.
216 // For example, one HAL implementation returns an error from a large write,
217 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
218 // We could either fix the HAL implementations, or provide a wrapper that breaks
219 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
220} kUseFastMixer = FastMixer_Static;
221
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700222// Whether to use fast capture
223static const enum {
224 FastCapture_Never, // never initialize or use: for debugging only
225 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
226 FastCapture_Static, // initialize if needed, then use all the time if initialized
227} kUseFastCapture = FastCapture_Static;
228
Eric Laurent81784c32012-11-19 14:55:58 -0800229// Priorities for requestPriority
230static const int kPriorityAudioApp = 2;
231static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700232static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000233// Request real-time priority for PlaybackThread in ARC
234static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800235
Glenn Kastenea38ee72016-04-18 11:08:01 -0700236// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
237// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
238// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700239
240// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800241static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800242
Glenn Kasten03490092014-05-27 12:30:54 -0700243// The minimum and maximum allowed values
244static const int kFastTrackMultiplierMin = 1;
245static const int kFastTrackMultiplierMax = 2;
246
247// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
248static int sFastTrackMultiplier = kFastTrackMultiplier;
249
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700250// See Thread::readOnlyHeap().
251// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
252// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
253// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700254static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700255
Andy Hung25a80ac2023-07-19 12:47:35 -0700256static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700257
258static nsecs_t getStandbyTimeInNanos() {
259 static nsecs_t standbyTimeInNanos = []() {
260 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
261 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
262 ALOGI("%s: Using %d ms as standby time", __func__, ms);
263 return milliseconds(ms);
264 }();
265 return standbyTimeInNanos;
266}
267
Andy Hung81994d62023-07-20 21:44:14 -0700268// Set kEnableExtendedChannels to true to enable greater than stereo output
269// for the MixerThread and device sink. Number of channels allowed is
270// FCC_2 <= channels <= FCC_LIMIT.
271constexpr bool kEnableExtendedChannels = true;
272
273// Returns true if channel mask is permitted for the PCM sink in the MixerThread
274/* static */
275bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
276 switch (audio_channel_mask_get_representation(channelMask)) {
277 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
278 // Haptic channel mask is only applicable for channel position mask.
279 const uint32_t channelCount = audio_channel_count_from_out_mask(
280 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
281 const uint32_t maxChannelCount = kEnableExtendedChannels
282 ? FCC_LIMIT : FCC_2;
283 if (channelCount < FCC_2 // mono is not supported at this time
284 || channelCount > maxChannelCount) {
285 return false;
286 }
287 // check that channelMask is the "canonical" one we expect for the channelCount.
288 return audio_channel_position_mask_is_out_canonical(channelMask);
289 }
290 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
291 if (kEnableExtendedChannels) {
292 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
293 if (channelCount >= FCC_2 // mono is not supported at this time
294 && channelCount <= FCC_LIMIT) {
295 return true;
296 }
297 }
298 return false;
299 default:
300 return false;
301 }
302}
303
304// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
305constexpr bool kEnableExtendedPrecision = true;
306
307// Returns true if format is permitted for the PCM sink in the MixerThread
308/* static */
309bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
310 switch (format) {
311 case AUDIO_FORMAT_PCM_16_BIT:
312 return true;
313 case AUDIO_FORMAT_PCM_FLOAT:
314 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
315 case AUDIO_FORMAT_PCM_32_BIT:
316 case AUDIO_FORMAT_PCM_8_24_BIT:
317 return kEnableExtendedPrecision;
318 default:
319 return false;
320 }
321}
322
Eric Laurent81784c32012-11-19 14:55:58 -0800323// ----------------------------------------------------------------------------
324
Andy Hung25a80ac2023-07-19 12:47:35 -0700325// formatToString() needs to be exact for MediaMetrics purposes.
326// Do not use media/TypeConverter.h toString().
327/* static */
328std::string IAfThreadBase::formatToString(audio_format_t format) {
329 std::string result;
330 FormatConverter::toString(format, result);
331 return result;
332}
333
Andy Hungb68f5eb2019-12-03 16:49:17 -0800334// TODO: move all toString helpers to audio.h
335// under #ifdef __cplusplus #endif
336static std::string patchSinksToString(const struct audio_patch *patch)
337{
338 std::stringstream ss;
339 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700340 if (i > 0) {
341 ss << "|";
342 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800343 ss << "(" << toString(patch->sinks[i].ext.device.type)
344 << ", " << patch->sinks[i].ext.device.address << ")";
345 }
346 return ss.str();
347}
348
349static std::string patchSourcesToString(const struct audio_patch *patch)
350{
351 std::stringstream ss;
352 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700353 if (i > 0) {
354 ss << "|";
355 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800356 ss << "(" << toString(patch->sources[i].ext.device.type)
357 << ", " << patch->sources[i].ext.device.address << ")";
358 }
359 return ss.str();
360}
361
Andy Hung4bd53e72022-11-17 17:21:45 -0800362static std::string toString(audio_latency_mode_t mode) {
363 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000364 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
365 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800366}
367
368// Could be made a template, but other toString overloads for std::vector are confused.
369static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
370 std::string s("{ ");
371 for (const auto& e : elements) {
372 s.append(toString(e));
373 s.append(" ");
374 }
375 s.append("}");
376 return s;
377}
378
Glenn Kasten03490092014-05-27 12:30:54 -0700379static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
380
381static void sFastTrackMultiplierInit()
382{
383 char value[PROPERTY_VALUE_MAX];
384 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
385 char *endptr;
386 unsigned long ul = strtoul(value, &endptr, 0);
387 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
388 sFastTrackMultiplier = (int) ul;
389 }
390 }
391}
392
393// ----------------------------------------------------------------------------
394
Eric Laurent81784c32012-11-19 14:55:58 -0800395#ifdef ADD_BATTERY_DATA
396// To collect the amplifier usage
397static void addBatteryData(uint32_t params) {
398 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
399 if (service == NULL) {
400 // it already logged
401 return;
402 }
403
404 service->addBatteryData(params);
405}
406#endif
407
Andy Hung3f0c9022016-01-15 17:49:46 -0800408// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
409struct {
410 // call when you acquire a partial wakelock
411 void acquire(const sp<IBinder> &wakeLockToken) {
412 pthread_mutex_lock(&mLock);
413 if (wakeLockToken.get() == nullptr) {
414 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
415 } else {
416 if (mCount == 0) {
417 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
418 }
419 ++mCount;
420 }
421 pthread_mutex_unlock(&mLock);
422 }
423
424 // call when you release a partial wakelock.
425 void release(const sp<IBinder> &wakeLockToken) {
426 if (wakeLockToken.get() == nullptr) {
427 return;
428 }
429 pthread_mutex_lock(&mLock);
430 if (--mCount < 0) {
431 ALOGE("negative wakelock count");
432 mCount = 0;
433 }
434 pthread_mutex_unlock(&mLock);
435 }
436
437 // retrieves the boottime timebase offset from monotonic.
438 int64_t getBoottimeOffset() {
439 pthread_mutex_lock(&mLock);
440 int64_t boottimeOffset = mBoottimeOffset;
441 pthread_mutex_unlock(&mLock);
442 return boottimeOffset;
443 }
444
445 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
446 // and the selected timebase.
447 // Currently only TIMEBASE_BOOTTIME is allowed.
448 //
449 // This only needs to be called upon acquiring the first partial wakelock
450 // after all other partial wakelocks are released.
451 //
452 // We do an empirical measurement of the offset rather than parsing
453 // /proc/timer_list since the latter is not a formal kernel ABI.
454 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
455 int clockbase;
456 switch (timebase) {
457 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
458 clockbase = SYSTEM_TIME_BOOTTIME;
459 break;
460 default:
461 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
462 break;
463 }
464 // try three times to get the clock offset, choose the one
465 // with the minimum gap in measurements.
466 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700467 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800468 for (int i = 0; i < tries; ++i) {
469 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
470 const nsecs_t tbase = systemTime(clockbase);
471 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
472 const nsecs_t gap = tmono2 - tmono;
473 if (i == 0 || gap < bestGap) {
474 bestGap = gap;
475 measured = tbase - ((tmono + tmono2) >> 1);
476 }
477 }
478
479 // to avoid micro-adjusting, we don't change the timebase
480 // unless it is significantly different.
481 //
482 // Assumption: It probably takes more than toleranceNs to
483 // suspend and resume the device.
484 static int64_t toleranceNs = 10000; // 10 us
485 if (llabs(*offset - measured) > toleranceNs) {
486 ALOGV("Adjusting timebase offset old: %lld new: %lld",
487 (long long)*offset, (long long)measured);
488 *offset = measured;
489 }
490 }
491
492 pthread_mutex_t mLock;
493 int32_t mCount;
494 int64_t mBoottimeOffset;
495} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800496
497// ----------------------------------------------------------------------------
498// CPU Stats
499// ----------------------------------------------------------------------------
500
501class CpuStats {
502public:
503 CpuStats();
504 void sample(const String8 &title);
505#ifdef DEBUG_CPU_USAGE
506private:
507 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700508 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800509
Andy Hung16698b82018-08-01 10:48:38 -0700510 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800511
512 int mCpuNum; // thread's current CPU number
513 int mCpukHz; // frequency of thread's current CPU in kHz
514#endif
515};
516
517CpuStats::CpuStats()
518#ifdef DEBUG_CPU_USAGE
519 : mCpuNum(-1), mCpukHz(-1)
520#endif
521{
522}
523
Glenn Kasten0f11b512014-01-31 16:18:54 -0800524void CpuStats::sample(const String8 &title
525#ifndef DEBUG_CPU_USAGE
526 __unused
527#endif
528 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800529#ifdef DEBUG_CPU_USAGE
530 // get current thread's delta CPU time in wall clock ns
531 double wcNs;
532 bool valid = mCpuUsage.sampleAndEnable(wcNs);
533
534 // record sample for wall clock statistics
535 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700536 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800537 }
538
539 // get the current CPU number
540 int cpuNum = sched_getcpu();
541
542 // get the current CPU frequency in kHz
543 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
544
545 // check if either CPU number or frequency changed
546 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
547 mCpuNum = cpuNum;
548 mCpukHz = cpukHz;
549 // ignore sample for purposes of cycles
550 valid = false;
551 }
552
553 // if no change in CPU number or frequency, then record sample for cycle statistics
554 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700555 const double cycles = wcNs * cpukHz * 0.000001;
556 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800557 }
558
Eric Tan5b13ff82018-07-27 11:20:17 -0700559 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800560 // mCpuUsage.elapsed() is expensive, so don't call it every loop
561 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700562 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800563 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700564 const double perLoop = elapsed / (double) n;
565 const double perLoop100 = perLoop * 0.01;
566 const double perLoop1k = perLoop * 0.001;
567 const double mean = mWcStats.getMean();
568 const double stddev = mWcStats.getStdDev();
569 const double minimum = mWcStats.getMin();
570 const double maximum = mWcStats.getMax();
571 const double meanCycles = mHzStats.getMean();
572 const double stddevCycles = mHzStats.getStdDev();
573 const double minCycles = mHzStats.getMin();
574 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800575 mCpuUsage.resetElapsed();
576 mWcStats.reset();
577 mHzStats.reset();
578 ALOGD("CPU usage for %s over past %.1f secs\n"
579 " (%u mixer loops at %.1f mean ms per loop):\n"
580 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
581 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
582 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000583 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800584 elapsed * .000000001, n, perLoop * .000001,
585 mean * .001,
586 stddev * .001,
587 minimum * .001,
588 maximum * .001,
589 mean / perLoop100,
590 stddev / perLoop100,
591 minimum / perLoop100,
592 maximum / perLoop100,
593 meanCycles / perLoop1k,
594 stddevCycles / perLoop1k,
595 minCycles / perLoop1k,
596 maxCycles / perLoop1k);
597
598 }
599 }
600#endif
601};
602
603// ----------------------------------------------------------------------------
604// ThreadBase
605// ----------------------------------------------------------------------------
606
Glenn Kasten97b7b752014-09-28 13:04:24 -0700607// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700608const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700609{
610 switch (type) {
611 case MIXER:
612 return "MIXER";
613 case DIRECT:
614 return "DIRECT";
615 case DUPLICATING:
616 return "DUPLICATING";
617 case RECORD:
618 return "RECORD";
619 case OFFLOAD:
620 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700621 case MMAP_PLAYBACK:
622 return "MMAP_PLAYBACK";
623 case MMAP_CAPTURE:
624 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200625 case SPATIALIZER:
626 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000627 case BIT_PERFECT:
628 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700629 default:
630 return "unknown";
631 }
632}
633
Andy Hung583043b2023-07-17 17:05:00 -0700634ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700635 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800636 : Thread(false /*canCallJava*/),
637 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700638 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700639 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
640 isOut),
641 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700642 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800643 // are set by PlaybackThread::readOutputParameters_l() or
644 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700645 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700646 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700647 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800648 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700649 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800650 mSystemReady(systemReady),
651 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800652{
Andy Hungcf10d742020-04-28 15:38:24 -0700653 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700654 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800655}
656
Andy Hungee58e4a2023-07-07 13:47:37 -0700657ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800658{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700659 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700660 mConfigEvents.clear();
661
Eric Laurent81784c32012-11-19 14:55:58 -0800662 // do not lock the mutex in destructor
663 releaseWakeLock_l();
664 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800665 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800666 binder->unlinkToDeath(mDeathRecipient);
667 }
Andy Hungd0979812019-02-21 15:51:44 -0800668
669 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800670}
671
Andy Hungee58e4a2023-07-07 13:47:37 -0700672status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700673{
674 status_t status = initCheck();
675 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800676 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700677 } else {
678 ALOGE("No working audio driver found.");
679 }
680 return status;
681}
682
Andy Hungee58e4a2023-07-07 13:47:37 -0700683void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800684{
685 ALOGV("ThreadBase::exit");
686 // do any cleanup required for exit to succeed
687 preExit();
688 {
689 // This lock prevents the following race in thread (uniprocessor for illustration):
690 // if (!exitPending()) {
691 // // context switch from here to exit()
692 // // exit() calls requestExit(), what exitPending() observes
693 // // exit() calls signal(), which is dropped since no waiters
694 // // context switch back from exit() to here
695 // mWaitWorkCV.wait(...);
696 // // now thread is hung
697 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700698 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800699 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700700 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800701 }
702 // When Thread::requestExitAndWait is made virtual and this method is renamed to
703 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700704
705 // For TimeCheck: track waiting on the thread join of getTid().
706 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
707
Eric Laurent81784c32012-11-19 14:55:58 -0800708 requestExitAndWait();
709}
710
Andy Hungee58e4a2023-07-07 13:47:37 -0700711status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800712{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000713 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700714 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800715
Eric Laurent10351942014-05-08 18:49:52 -0700716 return sendSetParameterConfigEvent_l(keyValuePairs);
717}
718
719// sendConfigEvent_l() must be called with ThreadBase::mLock held
720// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700721status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700722NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700723{
724 status_t status = NO_ERROR;
725
Eric Laurent72e3f392015-05-20 14:43:50 -0700726 if (event->mRequiresSystemReady && !mSystemReady) {
727 event->mWaitStatus = false;
728 mPendingConfigEvents.add(event);
729 return status;
730 }
Eric Laurent10351942014-05-08 18:49:52 -0700731 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700732 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700733 mWaitWorkCV.notify_one();
734 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700735 {
Andy Hungc5007f82023-08-29 14:26:09 -0700736 audio_utils::unique_lock _l(event->mutex());
Eric Laurent3fddffe2024-07-31 14:18:34 +0000737 nsecs_t timeoutNs = event->mType == CFG_EVENT_CREATE_AUDIO_PATCH ?
738 kCreatePatchEventTimeoutNs : kConfigEventTimeoutNs;
Eric Laurent10351942014-05-08 18:49:52 -0700739 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800740 if (event->mCondition.wait_for(
Eric Laurent3fddffe2024-07-31 14:18:34 +0000741 _l, std::chrono::nanoseconds(timeoutNs), getTid())
Andy Hung02ea2a02024-01-25 17:02:30 -0800742 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700743 event->mStatus = TIMED_OUT;
744 event->mWaitStatus = false;
745 }
746 }
747 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800748 }
Andy Hungc5007f82023-08-29 14:26:09 -0700749 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800750 return status;
751}
752
Andy Hungee58e4a2023-07-07 13:47:37 -0700753void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700754 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800755{
Andy Hung972bec12023-08-31 16:13:39 -0700756 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700757 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800758}
759
Andy Hungc5007f82023-08-29 14:26:09 -0700760// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700761void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700762 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800763{
Andy Hungd0979812019-02-21 15:51:44 -0800764 // The audio statistics history is exponentially weighted to forget events
765 // about five or more seconds in the past. In order to have
766 // crisper statistics for mediametrics, we reset the statistics on
767 // an IoConfigEvent, to reflect different properties for a new device.
768 mIoJitterMs.reset();
769 mLatencyMs.reset();
770 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000771 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100772 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800773
Eric Laurent09f1ed22019-04-24 17:45:17 -0700774 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700775 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800776}
777
Andy Hungee58e4a2023-07-07 13:47:37 -0700778void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700779{
Andy Hung972bec12023-08-31 16:13:39 -0700780 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800781 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700782}
783
Andy Hungc5007f82023-08-29 14:26:09 -0700784// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700785void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800786 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800787{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800788 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700789 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800790}
791
Andy Hungc5007f82023-08-29 14:26:09 -0700792// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700793status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800794{
Andy Hung2ddee192015-12-18 17:34:44 -0800795 sp<ConfigEvent> configEvent;
796 AudioParameter param(keyValuePair);
797 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700798 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800799 setMasterMono_l(value != 0);
800 if (param.size() == 1) {
801 return NO_ERROR; // should be a solo parameter - we don't pass down
802 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700803 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800804 configEvent = new SetParameterConfigEvent(param.toString());
805 } else {
806 configEvent = new SetParameterConfigEvent(keyValuePair);
807 }
Eric Laurent10351942014-05-08 18:49:52 -0700808 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700809}
810
Andy Hungee58e4a2023-07-07 13:47:37 -0700811status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700812 const struct audio_patch *patch,
813 audio_patch_handle_t *handle)
814{
Andy Hung972bec12023-08-31 16:13:39 -0700815 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700816 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
817 status_t status = sendConfigEvent_l(configEvent);
818 if (status == NO_ERROR) {
819 CreateAudioPatchConfigEventData *data =
820 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
821 *handle = data->mHandle;
822 }
823 return status;
824}
825
Andy Hungee58e4a2023-07-07 13:47:37 -0700826status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700827 const audio_patch_handle_t handle)
828{
Andy Hung972bec12023-08-31 16:13:39 -0700829 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700830 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
831 return sendConfigEvent_l(configEvent);
832}
833
Andy Hungee58e4a2023-07-07 13:47:37 -0700834status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700835 const DeviceDescriptorBaseVector& outDevices)
836{
837 if (type() != RECORD) {
838 // The update out device operation is only for record thread.
839 return INVALID_OPERATION;
840 }
Andy Hung972bec12023-08-31 16:13:39 -0700841 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700842 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
843 return sendConfigEvent_l(configEvent);
844}
845
Andy Hungee58e4a2023-07-07 13:47:37 -0700846void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200847{
848 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
849 sp<ConfigEvent> configEvent =
850 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
851 sendConfigEvent_l(configEvent);
852}
Eric Laurent1c333e22014-05-20 10:48:17 -0700853
Andy Hungee58e4a2023-07-07 13:47:37 -0700854void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200855{
Andy Hung972bec12023-08-31 16:13:39 -0700856 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200857 sendCheckOutputStageEffectsEvent_l();
858}
859
Andy Hungee58e4a2023-07-07 13:47:37 -0700860void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200861{
862 sp<ConfigEvent> configEvent =
863 (ConfigEvent *)new CheckOutputStageEffectsEvent();
864 sendConfigEvent_l(configEvent);
865}
866
Andy Hungee58e4a2023-07-07 13:47:37 -0700867void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200868{
869 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
870 sendConfigEvent_l(configEvent);
871}
872
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700873// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700874void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700875{
Eric Laurent10351942014-05-08 18:49:52 -0700876 bool configChanged = false;
877
Eric Laurent81784c32012-11-19 14:55:58 -0800878 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700879 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700880 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800881 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700882 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700883 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700884 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
885 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800886 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700887 true /*asynchronous*/);
888 if (err != 0) {
889 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700890 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700891 }
892 } break;
893 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700894 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700895 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700896 } break;
897 case CFG_EVENT_SET_PARAMETER: {
898 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
899 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
900 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700901 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000902 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700903 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700904 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700905 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700906 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700907 CreateAudioPatchConfigEventData *data =
908 (CreateAudioPatchConfigEventData *)event->mData.get();
909 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700910 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200911 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700912 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
913 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
914 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700915 } break;
916 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700917 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700918 ReleaseAudioPatchConfigEventData *data =
919 (ReleaseAudioPatchConfigEventData *)event->mData.get();
920 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700921 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200922 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700923 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
924 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
925 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
926 } break;
927 case CFG_EVENT_UPDATE_OUT_DEVICE: {
928 UpdateOutDevicesConfigEventData *data =
929 (UpdateOutDevicesConfigEventData *)event->mData.get();
930 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700931 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200932 case CFG_EVENT_RESIZE_BUFFER: {
933 ResizeBufferConfigEventData *data =
934 (ResizeBufferConfigEventData *)event->mData.get();
935 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
936 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200937
938 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
939 setCheckOutputStageEffects();
940 } break;
941
Eric Laurent68a40a82022-05-03 18:15:04 +0200942 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
943 onHalLatencyModesChanged_l();
944 } break;
945
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700946 default:
Eric Laurent10351942014-05-08 18:49:52 -0700947 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700948 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800949 }
Eric Laurent10351942014-05-08 18:49:52 -0700950 {
Andy Hung972bec12023-08-31 16:13:39 -0700951 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700952 if (event->mWaitStatus) {
953 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700954 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700955 }
956 }
957 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
958 }
959
960 if (configChanged) {
961 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800962 }
Eric Laurent81784c32012-11-19 14:55:58 -0800963}
964
Marco Nelissenb2208842014-02-07 14:00:50 -0800965String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
966 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700967 const audio_channel_representation_t representation =
968 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700969
970 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800971 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700972 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
973 if (output) {
974 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
975 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
976 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700977 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700978 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
980 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
981 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
982 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
983 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
984 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
985 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
986 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
987 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
988 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
989 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700990 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
991 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
992 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
993 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
994 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
995 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
996 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700997 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700998 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
999 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001000 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
1001 } else {
1002 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
1003 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
1004 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1005 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1006 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1007 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1008 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1009 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1010 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1011 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1012 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1013 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001014 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1015 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1016 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001017 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001018 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1019 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001020 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1021 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1022 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1023 }
1024 const int len = s.length();
1025 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001026 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001027 s.unlockBuffer(len - 2); // remove trailing ", "
1028 }
1029 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001030 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001031 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1032 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1033 return s;
1034 default:
1035 s.appendFormat("unknown mask, representation:%d bits:%#x",
1036 representation, audio_channel_mask_get_bits(mask));
1037 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001038 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001039}
1040
Andy Hungee58e4a2023-07-07 13:47:37 -07001041void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001042NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001043{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001044 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1045 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1046
Andy Hungc5007f82023-08-29 14:26:09 -07001047 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001048 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001049 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001050 }
1051
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001052 dumpBase_l(fd, args);
1053 dumpInternals_l(fd, args);
1054 dumpTracks_l(fd, args);
1055 dumpEffectChains_l(fd, args);
1056
1057 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001058 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001059 }
1060
1061 dprintf(fd, " Local log:\n");
1062 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001063
1064 // --all does the statistics
1065 bool dumpAll = false;
1066 for (const auto &arg : args) {
1067 if (arg == String16("--all")) {
1068 dumpAll = true;
1069 }
1070 }
1071 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001072 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001073 if (!sched.empty()) {
1074 (void)write(fd, sched.c_str(), sched.size());
1075 }
1076 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001077}
1078
Andy Hungee58e4a2023-07-07 13:47:37 -07001079void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001080{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001081 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001082 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001083 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001084 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001085 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1086 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001087 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001088 dprintf(fd, " Channel count: %u\n", mChannelCount);
1089 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001090 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001091 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1092 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001093 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001094 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001095 size_t numConfig = mConfigEvents.size();
1096 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001097 const size_t SIZE = 256;
1098 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001099 for (size_t i = 0; i < numConfig; i++) {
1100 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001101 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001102 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001103 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001104 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001105 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001106 }
Andy Hung293558a2017-03-21 12:19:20 -07001107 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001108 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001109 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001110 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001111 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001112 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001113
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001114 // Dump timestamp statistics for the Thread types that support it.
1115 if (mType == RECORD
1116 || mType == MIXER
1117 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001118 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001119 || mType == OFFLOAD
1120 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001121 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001122 dprintf(fd, " Timestamp corrected: %s\n",
1123 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001124 }
1125
Andy Hung446f4df2019-02-21 12:26:41 -08001126 if (mLastIoBeginNs > 0) { // MMAP may not set this
1127 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1128 isOutput() ? "write" : "read",
1129 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1130 }
1131
1132 if (mProcessTimeMs.getN() > 0) {
1133 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1134 }
1135
1136 if (mIoJitterMs.getN() > 0) {
1137 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1138 isOutput() ? "write" : "read",
1139 mIoJitterMs.toString().c_str());
1140 }
1141
Andy Hunge6c37112019-02-26 17:38:10 -08001142 if (mLatencyMs.getN() > 0) {
1143 dprintf(fd, " Threadloop %s latency stats: %s\n",
1144 isOutput() ? "write" : "read",
1145 mLatencyMs.toString().c_str());
1146 }
Robert Wu06db0a32021-08-10 19:05:34 +00001147
1148 if (mMonopipePipeDepthStats.getN() > 0) {
1149 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1150 isOutput() ? "write" : "read",
1151 mMonopipePipeDepthStats.toString().c_str());
1152 }
Eric Laurent81784c32012-11-19 14:55:58 -08001153}
1154
Andy Hungee58e4a2023-07-07 13:47:37 -07001155void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001156{
1157 const size_t SIZE = 256;
1158 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001159
Marco Nelissenb2208842014-02-07 14:00:50 -08001160 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001161 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001162 write(fd, buffer, strlen(buffer));
1163
Marco Nelissenb2208842014-02-07 14:00:50 -08001164 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001165 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001166 if (chain != 0) {
1167 chain->dump(fd, args);
1168 }
1169 }
1170}
1171
Andy Hungee58e4a2023-07-07 13:47:37 -07001172void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001173{
Andy Hung972bec12023-08-31 16:13:39 -07001174 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001175 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001176}
1177
Andy Hungee58e4a2023-07-07 13:47:37 -07001178String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001179{
1180 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001181 case MIXER:
1182 return String16("AudioMix");
1183 case DIRECT:
1184 return String16("AudioDirectOut");
1185 case DUPLICATING:
1186 return String16("AudioDup");
1187 case RECORD:
1188 return String16("AudioIn");
1189 case OFFLOAD:
1190 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001191 case MMAP_PLAYBACK:
1192 return String16("MmapPlayback");
1193 case MMAP_CAPTURE:
1194 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001195 case SPATIALIZER:
1196 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001197 default:
1198 ALOG_ASSERT(false);
1199 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001200 }
1201}
1202
Andy Hungee58e4a2023-07-07 13:47:37 -07001203void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001204{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001205 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001206 if (mPowerManager != 0) {
1207 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001208 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001209 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1210 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001211 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001212 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001213 {} /* workSource */,
1214 {} /* historyTag */);
1215 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001216 mWakeLockToken = binder;
1217 }
Chris Ye6597d732020-02-28 22:38:25 -08001218 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001219 }
Wei Jia3f273d12015-11-24 09:06:49 -08001220
Andy Hung3f0c9022016-01-15 17:49:46 -08001221 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001222 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1223 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001224}
1225
Andy Hungee58e4a2023-07-07 13:47:37 -07001226void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001227{
Andy Hung972bec12023-08-31 16:13:39 -07001228 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001229 releaseWakeLock_l();
1230}
1231
Andy Hungee58e4a2023-07-07 13:47:37 -07001232void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001233{
Andy Hung3f0c9022016-01-15 17:49:46 -08001234 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001235 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001236 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001237 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001238 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001239 }
1240 mWakeLockToken.clear();
1241 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001242}
1243
Andy Hungee58e4a2023-07-07 13:47:37 -07001244void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001245 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001246 // use checkService() to avoid blocking if power service is not up yet
1247 sp<IBinder> binder =
1248 defaultServiceManager()->checkService(String16("power"));
1249 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001250 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001251 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001252 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001253 binder->linkToDeath(mDeathRecipient);
1254 }
1255 }
1256}
1257
Andy Hungee58e4a2023-07-07 13:47:37 -07001258void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001259 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001260
1261#if !LOG_NDEBUG
1262 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001263 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001264 s << uid << " ";
1265 }
1266 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1267#endif
1268
Andy Hung438e7572015-12-14 15:51:17 -08001269 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1270 if (mSystemReady) {
1271 ALOGE("no wake lock to update, but system ready!");
1272 } else {
1273 ALOGW("no wake lock to update, system not ready yet");
1274 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001275 return;
1276 }
1277 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001278 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001279 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1280 mWakeLockToken, uidsAsInt);
1281 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001282 }
1283}
1284
Andy Hungee58e4a2023-07-07 13:47:37 -07001285void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001286{
Andy Hung972bec12023-08-31 16:13:39 -07001287 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001288 releaseWakeLock_l();
1289 mPowerManager.clear();
1290}
1291
Andy Hungee58e4a2023-07-07 13:47:37 -07001292void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001293 const DeviceDescriptorBaseVector& outDevices __unused)
1294{
1295 ALOGE("%s should only be called in RecordThread", __func__);
1296}
1297
Andy Hungee58e4a2023-07-07 13:47:37 -07001298void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001299{
1300 ALOGE("%s should only be called in RecordThread", __func__);
1301}
1302
Andy Hungee58e4a2023-07-07 13:47:37 -07001303void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001304{
1305 sp<ThreadBase> thread = mThread.promote();
1306 if (thread != 0) {
1307 thread->clearPowerManager();
1308 }
1309 ALOGW("power manager service died !!!");
1310}
1311
Andy Hungee58e4a2023-07-07 13:47:37 -07001312void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001313 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001314{
Andy Hung116bc262023-06-20 18:56:17 -07001315 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001316 if (chain != 0) {
1317 if (type != NULL) {
1318 chain->setEffectSuspended_l(type, suspend);
1319 } else {
1320 chain->setEffectSuspendedAll_l(suspend);
1321 }
1322 }
1323
1324 updateSuspendedSessions_l(type, suspend, sessionId);
1325}
1326
Andy Hungee58e4a2023-07-07 13:47:37 -07001327void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001328{
1329 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1330 if (index < 0) {
1331 return;
1332 }
1333
1334 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1335 mSuspendedSessions.valueAt(index);
1336
1337 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001338 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001339 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001340 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001341 chain->setEffectSuspendedAll_l(true);
1342 } else {
1343 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1344 desc->mType.timeLow);
1345 chain->setEffectSuspended_l(&desc->mType, true);
1346 }
1347 }
1348 }
1349}
1350
Andy Hungee58e4a2023-07-07 13:47:37 -07001351void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001352 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001353 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001354{
1355 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1356
1357 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1358
1359 if (suspend) {
1360 if (index >= 0) {
1361 sessionEffects = mSuspendedSessions.valueAt(index);
1362 } else {
1363 mSuspendedSessions.add(sessionId, sessionEffects);
1364 }
1365 } else {
1366 if (index < 0) {
1367 return;
1368 }
1369 sessionEffects = mSuspendedSessions.valueAt(index);
1370 }
1371
1372
Andy Hung116bc262023-06-20 18:56:17 -07001373 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001374 if (type != NULL) {
1375 key = type->timeLow;
1376 }
1377 index = sessionEffects.indexOfKey(key);
1378
1379 sp<SuspendedSessionDesc> desc;
1380 if (suspend) {
1381 if (index >= 0) {
1382 desc = sessionEffects.valueAt(index);
1383 } else {
1384 desc = new SuspendedSessionDesc();
1385 if (type != NULL) {
1386 desc->mType = *type;
1387 }
1388 sessionEffects.add(key, desc);
1389 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1390 }
1391 desc->mRefCount++;
1392 } else {
1393 if (index < 0) {
1394 return;
1395 }
1396 desc = sessionEffects.valueAt(index);
1397 if (--desc->mRefCount == 0) {
1398 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1399 sessionEffects.removeItemsAt(index);
1400 if (sessionEffects.isEmpty()) {
1401 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1402 sessionId);
1403 mSuspendedSessions.removeItem(sessionId);
1404 }
1405 }
1406 }
1407 if (!sessionEffects.isEmpty()) {
1408 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1409 }
1410}
1411
Andy Hungee58e4a2023-07-07 13:47:37 -07001412void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001413 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001414 bool threadLocked)
1415NO_THREAD_SAFETY_ANALYSIS // manual locking
1416{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001417 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001418 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001419 }
Eric Laurent81784c32012-11-19 14:55:58 -08001420
Eric Laurent81784c32012-11-19 14:55:58 -08001421 if (mType != RECORD) {
1422 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1423 // another session. This gives the priority to well behaved effect control panels
1424 // and applications not using global effects.
1425 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1426 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001427 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001428 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1429 }
1430 }
1431
Eric Laurent6b446ce2019-12-13 10:56:31 -08001432 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001433 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001434 }
1435}
1436
Andy Hungc5007f82023-08-29 14:26:09 -07001437// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001438status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001439 const effect_descriptor_t *desc, audio_session_t sessionId)
1440{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001441 // No global output effect sessions on record threads
1442 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1443 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001444 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1445 desc->name, mThreadName);
1446 return BAD_VALUE;
1447 }
1448 // only pre processing effects on record thread
1449 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1450 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1451 desc->name, mThreadName);
1452 return BAD_VALUE;
1453 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001454
1455 // always allow effects without processing load or latency
1456 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1457 return NO_ERROR;
1458 }
1459
Eric Laurent4c415062016-06-17 16:14:16 -07001460 audio_input_flags_t flags = mInput->flags;
1461 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1462 if (flags & AUDIO_INPUT_FLAG_RAW) {
1463 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1464 desc->name, mThreadName);
1465 return BAD_VALUE;
1466 }
1467 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1468 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1469 desc->name, mThreadName);
1470 return BAD_VALUE;
1471 }
1472 }
jiabineb3bda02020-06-30 14:07:03 -07001473
Andy Hung116bc262023-06-20 18:56:17 -07001474 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001475 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1476 return BAD_VALUE;
1477 }
Eric Laurent4c415062016-06-17 16:14:16 -07001478 return NO_ERROR;
1479}
1480
Andy Hungc5007f82023-08-29 14:26:09 -07001481// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001482status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001483 const effect_descriptor_t *desc, audio_session_t sessionId)
1484{
1485 // no preprocessing on playback threads
1486 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001487 ALOGW("%s: pre processing effect %s created on playback"
1488 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001489 return BAD_VALUE;
1490 }
1491
Eric Laurent3e4de772017-07-16 16:55:08 -07001492 // always allow effects without processing load or latency
1493 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1494 return NO_ERROR;
1495 }
1496
Andy Hung116bc262023-06-20 18:56:17 -07001497 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001498 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1499 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001500 return BAD_VALUE;
1501 }
1502
Eric Laurent4eb45d02023-12-20 12:07:17 +01001503 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001504 && mType != SPATIALIZER) {
1505 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1506 __func__, mType);
1507 return BAD_VALUE;
1508 }
1509
Eric Laurent4c415062016-06-17 16:14:16 -07001510 switch (mType) {
1511 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001512 audio_output_flags_t flags = mOutput->flags;
1513 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1514 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1515 // global effects are applied only to non fast tracks if they are SW
1516 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1517 break;
1518 }
1519 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1520 // only post processing on output stage session
1521 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001522 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1523 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001524 return BAD_VALUE;
1525 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001526 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1527 // only post processing on output stage session
1528 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001529 ALOGW("%s: non post processing effect %s not allowed on device session",
1530 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001531 return BAD_VALUE;
1532 }
Eric Laurent4c415062016-06-17 16:14:16 -07001533 } else {
1534 // no restriction on effects applied on non fast tracks
1535 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1536 break;
1537 }
1538 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001539
Eric Laurent4c415062016-06-17 16:14:16 -07001540 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001541 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001542 return BAD_VALUE;
1543 }
1544 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001545 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1546 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001547 return BAD_VALUE;
1548 }
1549 }
1550 } break;
1551 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001552 // nothing actionable on offload threads, if the effect:
1553 // - is offloadable: the effect can be created
1554 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1555 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001556 break;
1557 case DIRECT:
1558 // Reject any effect on Direct output threads for now, since the format of
1559 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001560 ALOGW("%s: effect %s on DIRECT output thread %s",
1561 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001562 return BAD_VALUE;
1563 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001564 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001565 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1566 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001567 return BAD_VALUE;
1568 }
1569 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001570 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1571 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001572 return BAD_VALUE;
1573 }
1574 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001575 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1576 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001577 return BAD_VALUE;
1578 }
1579 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001580 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001581 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1582 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1583 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1584 // are supported and added after the spatializer.
1585 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1586 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1587 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001588 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001589 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1590 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001591 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001592 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1593 break;
1594 }
1595 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1596 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1597 __func__, desc->name);
1598 return BAD_VALUE;
1599 }
1600 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1601 // only post processing on output stage session
1602 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1603 ALOGW("%s: non post processing effect %s not allowed on device session",
1604 __func__, desc->name);
1605 return BAD_VALUE;
1606 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001607 }
1608 break;
jiabinc658e452022-10-21 20:52:21 +00001609 case BIT_PERFECT:
1610 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1611 // Allow HW accelerated effects of tunnel type
1612 break;
1613 }
1614 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1615 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1616 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1617 // 3) there is any bit-perfect track with the given session id.
1618 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1619 sessionId == AUDIO_SESSION_DEVICE) {
1620 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1621 __func__, desc->name, mThreadName);
1622 return BAD_VALUE;
1623 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1624 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1625 __func__, desc->name, sessionId);
1626 return BAD_VALUE;
1627 }
1628 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001629 default:
1630 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1631 }
1632
1633 return NO_ERROR;
1634}
1635
Andy Hungc5007f82023-08-29 14:26:09 -07001636// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001637sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001638 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001639 const sp<IEffectClient>& effectClient,
1640 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001641 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001642 effect_descriptor_t *desc,
1643 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001644 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001645 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001646 bool probe,
1647 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001648{
Andy Hung116bc262023-06-20 18:56:17 -07001649 sp<IAfEffectModule> effect;
1650 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001651 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001652 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001653 bool chainCreated = false;
1654 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001655 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001656
1657 lStatus = initCheck();
1658 if (lStatus != NO_ERROR) {
1659 ALOGW("createEffect_l() Audio driver not initialized.");
1660 goto Exit;
1661 }
1662
Eric Laurent81784c32012-11-19 14:55:58 -08001663 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1664
Andy Hungc5007f82023-08-29 14:26:09 -07001665 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001666 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001667
Eric Laurent4c415062016-06-17 16:14:16 -07001668 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001669 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001670 goto Exit;
1671 }
1672
Eric Laurent81784c32012-11-19 14:55:58 -08001673 // check for existing effect chain with the requested audio session
1674 chain = getEffectChain_l(sessionId);
1675 if (chain == 0) {
1676 // create a new chain for this session
1677 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001678 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001679 addEffectChain_l(chain);
1680 chain->setStrategy(getStrategyForSession_l(sessionId));
1681 chainCreated = true;
1682 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001683 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001684 }
1685
1686 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1687
1688 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001689 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001690 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001691 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001692 if (lStatus != NO_ERROR) {
1693 goto Exit;
1694 }
1695 effectCreated = true;
1696
jiabinc52b1ff2019-10-31 17:20:42 -07001697 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001698 effect->setDevices(outDeviceTypeAddrs());
1699 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001700 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001701 effect->setAudioSource(mAudioSource);
1702 }
jiabin1319f5a2021-03-30 22:21:24 +00001703 if (effect->isHapticGenerator()) {
1704 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1705 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001706 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001707 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001708 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001709 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001710 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001711 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001712 }
1713 }
Eric Laurent81784c32012-11-19 14:55:58 -08001714 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001715 handle = IAfEffectHandle::create(
1716 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001717 lStatus = handle->initCheck();
1718 if (lStatus == OK) {
1719 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001720 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001721 }
Eric Laurent81784c32012-11-19 14:55:58 -08001722 if (enabled != NULL) {
1723 *enabled = (int)effect->isEnabled();
1724 }
1725 }
1726
1727Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001728 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001729 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001730 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001731 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001732 }
Eric Laurent81784c32012-11-19 14:55:58 -08001733 if (chainCreated) {
1734 removeEffectChain_l(chain);
1735 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001736 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001737 }
1738
Glenn Kasten9156ef32013-08-06 15:39:08 -07001739 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001740 return handle;
1741}
1742
Andy Hungee58e4a2023-07-07 13:47:37 -07001743void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001744 bool unpinIfLast)
1745{
1746 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001747 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001748 {
Andy Hung972bec12023-08-31 16:13:39 -07001749 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001750 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001751 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001752 return;
1753 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001754 effect = effectBase->asEffectModule();
1755 if (effect == nullptr) {
1756 return;
1757 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001758 // restore suspended effects if the disconnected handle was enabled and the last one.
1759 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1760 if (remove) {
1761 removeEffect_l(effect, true);
1762 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001763 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001764 }
1765 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001766 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001767 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001768 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001769 }
1770 }
1771}
1772
Andy Hungee58e4a2023-07-07 13:47:37 -07001773void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001774 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001775 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001776 broadcast_l();
1777 }
1778 if (!effect->isOffloadable()) {
1779 if (mType == ThreadBase::OFFLOAD) {
1780 PlaybackThread *t = (PlaybackThread *)this;
1781 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1782 }
1783 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001784 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001785 }
1786 }
1787}
1788
Andy Hungee58e4a2023-07-07 13:47:37 -07001789void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001790 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001791 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001792 broadcast_l();
1793 }
1794}
1795
Andy Hungee58e4a2023-07-07 13:47:37 -07001796sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001797 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001798{
Andy Hung972bec12023-08-31 16:13:39 -07001799 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001800 return getEffect_l(sessionId, effectId);
1801}
1802
Andy Hungee58e4a2023-07-07 13:47:37 -07001803sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001804 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001805{
Andy Hung116bc262023-06-20 18:56:17 -07001806 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001807 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1808}
1809
Andy Hungee58e4a2023-07-07 13:47:37 -07001810std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001811{
Andy Hung116bc262023-06-20 18:56:17 -07001812 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001813 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001814}
1815
Andy Hung972bec12023-08-31 16:13:39 -07001816// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1817// ThreadBase::mutex() held
1818status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001819{
1820 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001821 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001822 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001823 bool chainCreated = false;
1824
Eric Laurent5baf2af2013-09-12 17:37:00 -07001825 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001826 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1827 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001828
Eric Laurent81784c32012-11-19 14:55:58 -08001829 if (chain == 0) {
1830 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001831 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001832 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001833 addEffectChain_l(chain);
1834 chain->setStrategy(getStrategyForSession_l(sessionId));
1835 chainCreated = true;
1836 }
Andy Hung972bec12023-08-31 16:13:39 -07001837 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001838
1839 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001840 ALOGW("%s: %p effect %s already present in chain %p",
1841 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001842 return BAD_VALUE;
1843 }
1844
Shunkai Yaod125e402024-01-20 03:19:06 +00001845 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001846
Shunkai Yao29d10572024-03-19 04:31:47 +00001847 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001848 if (status != NO_ERROR) {
1849 if (chainCreated) {
1850 removeEffectChain_l(chain);
1851 }
1852 return status;
1853 }
1854
jiabin8f278ee2019-11-11 12:16:27 -08001855 effect->setDevices(outDeviceTypeAddrs());
1856 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001857 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001858 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001859
Eric Laurent81784c32012-11-19 14:55:58 -08001860 return NO_ERROR;
1861}
1862
Andy Hungee58e4a2023-07-07 13:47:37 -07001863void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001864
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001865 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001866 effect_descriptor_t desc = effect->desc();
1867 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1868 detachAuxEffect_l(effect->id());
1869 }
1870
Andy Hung116bc262023-06-20 18:56:17 -07001871 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001872 if (chain != 0) {
1873 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001874 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001875 removeEffectChain_l(chain);
1876 }
1877 } else {
1878 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1879 }
1880}
1881
Shunkai Yaof4847652024-01-12 00:25:20 +00001882void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1883 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001884{
1885 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001886 for (const auto& effectChain : effectChains) {
1887 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001888 }
1889}
1890
Shunkai Yaof4847652024-01-12 00:25:20 +00001891void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1892 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001893{
Shunkai Yaof4847652024-01-12 00:25:20 +00001894 for (const auto& effectChain : effectChains) {
1895 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001896 }
1897}
1898
Andy Hungee58e4a2023-07-07 13:47:37 -07001899sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001900{
Andy Hung972bec12023-08-31 16:13:39 -07001901 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001902 return getEffectChain_l(sessionId);
1903}
1904
Andy Hungee58e4a2023-07-07 13:47:37 -07001905sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001906 const
Eric Laurent81784c32012-11-19 14:55:58 -08001907{
1908 size_t size = mEffectChains.size();
1909 for (size_t i = 0; i < size; i++) {
1910 if (mEffectChains[i]->sessionId() == sessionId) {
1911 return mEffectChains[i];
1912 }
1913 }
1914 return 0;
1915}
1916
Andy Hungee58e4a2023-07-07 13:47:37 -07001917void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001918{
Andy Hung972bec12023-08-31 16:13:39 -07001919 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001920 size_t size = mEffectChains.size();
1921 for (size_t i = 0; i < size; i++) {
1922 mEffectChains[i]->setMode_l(mode);
1923 }
1924}
1925
Andy Hungee58e4a2023-07-07 13:47:37 -07001926void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001927{
1928 config->type = AUDIO_PORT_TYPE_MIX;
1929 config->ext.mix.handle = mId;
1930 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001931 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001932 config->channel_mask = mChannelMask;
1933 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1934 AUDIO_PORT_CONFIG_FORMAT;
1935}
1936
Andy Hungee58e4a2023-07-07 13:47:37 -07001937void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001938{
Andy Hung972bec12023-08-31 16:13:39 -07001939 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001940 if (mSystemReady) {
1941 return;
1942 }
1943 mSystemReady = true;
1944
1945 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1946 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1947 }
1948 mPendingConfigEvents.clear();
1949}
1950
Andy Hungdae27702016-10-31 14:01:16 -07001951template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001952ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001953 ssize_t index = mActiveTracks.indexOf(track);
1954 if (index >= 0) {
1955 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1956 return index;
1957 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001958 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001959 mActiveTracksGeneration++;
1960 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001961 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001962 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001963 return mActiveTracks.add(track);
1964}
1965
1966template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001967ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001968 ssize_t index = mActiveTracks.remove(track);
1969 if (index < 0) {
1970 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1971 return index;
1972 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001973 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001974 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001975 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001976 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001977 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001978#ifdef TEE_SINK
1979 track->dumpTee(-1 /* fd */, "_REMOVE");
1980#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001981 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001982 return index;
1983}
1984
1985template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001986void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001987 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001988 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001989 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001990 }
1991 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001992 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001993 mActiveTracks.clear();
1994 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001995}
1996
1997template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001998void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001999 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002000 // Updates ActiveTracks client uids to the thread wakelock.
2001 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2002 thread->updateWakeLockUids_l(getWakeLockUids());
2003 mLastActiveTracksGeneration = mActiveTracksGeneration;
2004 }
Andy Hungdae27702016-10-31 14:01:16 -07002005}
Eric Laurent83b88082014-06-20 18:31:16 -07002006
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002007template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002008bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002009 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002010 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002011
2012 for (const sp<T> &track : mActiveTracks) {
2013 // Do not short-circuit as all hasChanged states must be reset
2014 // as all the metadata are going to be sent
2015 hasChanged |= track->readAndClearHasChanged();
2016 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002017 return hasChanged;
2018}
2019
2020template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002021void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002022 const char *funcName, const sp<T> &track) const {
2023 if (mLocalLog != nullptr) {
2024 String8 result;
2025 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002026 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002027 }
2028}
2029
Andy Hungee58e4a2023-07-07 13:47:37 -07002030void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002031{
2032 // Thread could be blocked waiting for async
2033 // so signal it to handle state changes immediately
2034 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2035 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2036 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002037 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002038}
2039
Andy Hungd0979812019-02-21 15:51:44 -08002040// Call only from threadLoop() or when it is idle.
2041// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002042void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002043NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002044{
2045 // Do not log if we have no stats.
2046 // We choose the timestamp verifier because it is the most likely item to be present.
2047 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2048 if (nstats == 0) {
2049 return;
2050 }
2051
2052 // Don't log more frequently than once per 12 hours.
2053 // We use BOOTTIME to include suspend time.
2054 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2055 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2056 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2057 return;
2058 }
2059
2060 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2061 mLastRecordedTimeNs = timeNs;
2062
Ray Essickf27e9872019-12-07 06:28:46 -08002063 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002064
2065#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2066
2067 // thread configuration
2068 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2069 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2070 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2071 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2072 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2073 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2074 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002075 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2076 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002077
2078 // thread statistics
2079 if (mIoJitterMs.getN() > 0) {
2080 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2081 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2082 }
2083 if (mProcessTimeMs.getN() > 0) {
2084 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2085 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2086 }
2087 const auto tsjitter = mTimestampVerifier.getJitterMs();
2088 if (tsjitter.getN() > 0) {
2089 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2090 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2091 }
2092 if (mLatencyMs.getN() > 0) {
2093 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2094 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2095 }
Robert Wu06db0a32021-08-10 19:05:34 +00002096 if (mMonopipePipeDepthStats.getN() > 0) {
2097 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2098 mMonopipePipeDepthStats.getMean());
2099 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2100 mMonopipePipeDepthStats.getStdDev());
2101 }
Andy Hungd0979812019-02-21 15:51:44 -08002102
2103 item->selfrecord();
2104}
2105
Andy Hungee58e4a2023-07-07 13:47:37 -07002106product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002107{
Andy Hung583043b2023-07-17 17:05:00 -07002108 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002109 return PRODUCT_STRATEGY_NONE;
2110 }
2111 return AudioSystem::getStrategyForStream(stream);
2112}
2113
Andy Hungc5007f82023-08-29 14:26:09 -07002114// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002115void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002116 const sp<audio_utils::MelProcessor>& /*processor*/)
2117{
2118 // Do nothing
2119 ALOGW("%s: ThreadBase does not support CSD", __func__);
2120}
2121
Andy Hungc5007f82023-08-29 14:26:09 -07002122// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002123void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002124{
2125 // Do nothing
2126 ALOGW("%s: ThreadBase does not support CSD", __func__);
2127}
2128
Eric Laurent81784c32012-11-19 14:55:58 -08002129// ----------------------------------------------------------------------------
2130// Playback
2131// ----------------------------------------------------------------------------
2132
Andy Hung583043b2023-07-17 17:05:00 -07002133PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002134 AudioStreamOut* output,
2135 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002136 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002137 bool systemReady,
2138 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002139 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002140 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002141 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002142 mMixerBuffer(NULL),
2143 mMixerBufferSize(0),
2144 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2145 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002146 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002147 mEffectBuffer(NULL),
2148 mEffectBufferSize(0),
2149 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2150 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002151 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002152 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002153 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002154 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002155 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002156 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002157 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002158 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002159 mMixerStatus(MIXER_IDLE),
2160 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002161 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002162 mBytesRemaining(0),
2163 mCurrentWriteLength(0),
2164 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002165 mWriteAckSequence(0),
2166 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002167 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002168 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002169 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002170 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002171 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002172 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002173 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002174{
Glenn Kastend7dca052015-03-05 16:05:54 -08002175 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002176 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002177
Andy Hungc5007f82023-08-29 14:26:09 -07002178 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002179 // it would be safer to explicitly pass initial masterVolume/masterMute as
2180 // parameter.
2181 //
2182 // If the HAL we are using has support for master volume or master mute,
2183 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2184 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002185 mMasterVolume = afThreadCallback->masterVolume_l();
2186 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002187 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002188 if (mOutput->audioHwDev->canSetMasterVolume()) {
2189 mMasterVolume = 1.0;
2190 }
2191
2192 if (mOutput->audioHwDev->canSetMasterMute()) {
2193 mMasterMute = false;
2194 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002195 mIsMsdDevice = strcmp(
2196 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002197 }
2198
Eric Laurentf1f22e72021-07-13 14:04:14 +02002199 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2200 mMixerChannelMask = mixerConfig->channel_mask;
2201 }
2202
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002203 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002204
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002205 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002206 && mMixerChannelMask != mChannelMask) {
2207 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2208 mChannelMask, mMixerChannelMask);
2209 }
2210
Andy Hungc8fddf32018-08-08 18:32:37 -07002211 // TODO: We may also match on address as well as device type for
2212 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002213 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002214 // TODO: This property should be ensure that only contains one single device type.
2215 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2216 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002217 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2218 : AUDIO_DEVICE_NONE));
2219 }
Eric Laurent277a37e2024-07-29 18:37:52 +00002220
2221 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2222 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2223 mStreamTypes[stream].volume = 0.0f;
2224 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002225 }
Eric Laurent277a37e2024-07-29 18:37:52 +00002226 // Audio patch and call assistant volume are always max
2227 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2228 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2229 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2230 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002231}
2232
Andy Hungee58e4a2023-07-07 13:47:37 -07002233PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002234{
Andy Hung583043b2023-07-17 17:05:00 -07002235 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002236 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002237 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002238 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002239 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002240}
2241
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002242// Thread virtuals
2243
Andy Hungee58e4a2023-07-07 13:47:37 -07002244void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002245{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002246 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002247 ALOGE("The stream is not open yet"); // This should not happen.
2248 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002249 // Callbacks take strong or weak pointers as a parameter.
2250 // Since PlaybackThread passes itself as a callback handler, it can only
2251 // be done outside of the constructor. Creating weak and especially strong
2252 // pointers to a refcounted object in its own constructor is strongly
2253 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2254 // Even if a function takes a weak pointer, it is possible that it will
2255 // need to convert it to a strong pointer down the line.
2256 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2257 mOutput->stream->setCallback(this) == OK) {
2258 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002259 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002260 }
2261
jiabinf6eb4c32020-02-25 14:06:25 -08002262 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002263 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002264 }
2265 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002266 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002267 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002268}
2269
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002270// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002271void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002272{
2273 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002274 status_t result = mOutput->stream->exit();
2275 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002276}
2277
Andy Hungee58e4a2023-07-07 13:47:37 -07002278void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002279{
Eric Laurent81784c32012-11-19 14:55:58 -08002280 String8 result;
Eric Laurent277a37e2024-07-29 18:37:52 +00002281
2282 result.appendFormat(" Stream volumes in dB: ");
2283 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2284 const stream_type_t *st = &mStreamTypes[i];
2285 if (i > 0) {
2286 result.appendFormat(", ");
2287 }
2288 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2289 if (st->mute) {
2290 result.append("M");
Eric Laurent81784c32012-11-19 14:55:58 -08002291 }
2292 }
2293 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002294 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002295 result.clear();
2296
Eric Laurent81784c32012-11-19 14:55:58 -08002297 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2298 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002299 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002300 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002301
2302 size_t numtracks = mTracks.size();
2303 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002304 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002305 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002306 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002307 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002308 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002309 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002310 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002311 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002312 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002313 if (track != 0) {
2314 bool active = mActiveTracks.indexOf(track) >= 0;
2315 if (active) {
2316 numactiveseen++;
2317 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002318 result.append(prefix);
2319 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 }
2321 }
2322 } else {
2323 result.append("\n");
2324 }
2325 if (numactiveseen != numactive) {
2326 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002327 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002328 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002329 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002330 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002331 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002332 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002333 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002334 result.append(prefix);
2335 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002336 }
2337 }
2338 }
2339
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002340 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002341}
2342
Andy Hungee58e4a2023-07-07 13:47:37 -07002343void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002344{
Andy Hung04cb8f72020-03-20 13:44:33 -07002345 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002346 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002347 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2348 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002349 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2350 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2351 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2352 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002353 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002354 dprintf(fd, " Total writes: %d\n", mNumWrites);
2355 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2356 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002357 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002358 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002359 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002360 AudioStreamOut *output = mOutput;
2361 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002362 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002363 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002364 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2365 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2366 if (mPipeSink.get() != nullptr) {
2367 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2368 }
2369 if (output != nullptr) {
2370 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002371 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002372 }
Eric Laurent81784c32012-11-19 14:55:58 -08002373}
2374
Andy Hungc5007f82023-08-29 14:26:09 -07002375// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002376sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002377 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002378 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002379 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002380 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002381 audio_format_t format,
2382 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002383 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002384 size_t *pNotificationFrameCount,
2385 uint32_t notificationsPerBuffer,
2386 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002387 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002388 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002389 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002390 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002391 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002392 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002393 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002394 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002395 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002396 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002397 bool isBitPerfect,
Eric Laurent277a37e2024-07-29 18:37:52 +00002398 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002399{
Glenn Kasten74935e42013-12-19 08:56:45 -08002400 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002401 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002402 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002403 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002404 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002405 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002406 uint32_t sampleRate;
2407
2408 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2409 lStatus = BAD_VALUE;
2410 goto Exit;
2411 }
Eric Laurent21da6472017-11-09 16:29:26 -08002412
2413 if (*pSampleRate == 0) {
2414 *pSampleRate = mSampleRate;
2415 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002416 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002417
2418 // special case for FAST flag considered OK if fast mixer is present
2419 if (hasFastMixer()) {
2420 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2421 }
2422
2423 // Check if requested flags are compatible with output stream flags
2424 if ((*flags & outputFlags) != *flags) {
2425 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2426 *flags, outputFlags);
2427 *flags = (audio_output_flags_t)(*flags & outputFlags);
2428 }
Eric Laurent81784c32012-11-19 14:55:58 -08002429
jiabinc658e452022-10-21 20:52:21 +00002430 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002431 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002432 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002433 if (chain.get() != nullptr) {
2434 // Bit-perfect is required according to the configuration and preferred mixer
2435 // attributes, but it is not in the output flag from the client's request. Explicitly
2436 // adding bit-perfect flag to check the compatibility
2437 audio_output_flags_t flagsToCheck =
2438 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2439 chain->checkOutputFlagCompatibility(&flagsToCheck);
2440 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2441 ALOGE("%s cannot create track as there is data-processing effect attached to "
2442 "given session id(%d)", __func__, sessionId);
2443 lStatus = BAD_VALUE;
2444 goto Exit;
2445 }
2446 *flags = flagsToCheck;
2447 }
2448 }
2449
Eric Laurent81784c32012-11-19 14:55:58 -08002450 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002451 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002452 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002453 // PCM data
2454 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002455 // TODO: extract as a data library function that checks that a computationally
2456 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002457 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002458 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2459 (channelMask == AUDIO_CHANNEL_OUT_MONO
2460 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002461 // hardware sample rate
2462 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002463 // normal mixer has an associated fast mixer
2464 hasFastMixer() &&
2465 // there are sufficient fast track slots available
2466 (mFastTrackAvailMask != 0)
2467 // FIXME test that MixerThread for this fast track has a capable output HAL
2468 // FIXME add a permission test also?
2469 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002470 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2471 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002472 // read the fast track multiplier property the first time it is needed
2473 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2474 if (ok != 0) {
2475 ALOGE("%s pthread_once failed: %d", __func__, ok);
2476 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002477 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002478 }
Eric Laurent4c415062016-06-17 16:14:16 -07002479
2480 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002481 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002482 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002483 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002484 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002485 AUDIO_SESSION_OUTPUT_STAGE,
2486 AUDIO_SESSION_OUTPUT_MIX,
2487 sessionId,
2488 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002489 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002490 if (chain.get() != nullptr) {
2491 audio_output_flags_t old = *flags;
2492 chain->checkOutputFlagCompatibility(flags);
2493 if (old != *flags) {
2494 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2495 (int)session, (int)old, (int)*flags);
2496 }
Eric Laurent4c415062016-06-17 16:14:16 -07002497 }
2498 }
2499 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002500 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002501 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2502 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002503 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002504 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002505 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002506 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002507 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002508 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002509 audio_is_linear_pcm(format), channelMask, sampleRate,
2510 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002511 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002512 }
2513 }
Eric Laurent21da6472017-11-09 16:29:26 -08002514
2515 if (!audio_has_proportional_frames(format)) {
2516 if (sharedBuffer != 0) {
2517 // Same comment as below about ignoring frameCount parameter for set()
2518 frameCount = sharedBuffer->size();
2519 } else if (frameCount == 0) {
2520 frameCount = mNormalFrameCount;
2521 }
2522 if (notificationFrameCount != frameCount) {
2523 notificationFrameCount = frameCount;
2524 }
2525 } else if (sharedBuffer != 0) {
2526 // FIXME: Ensure client side memory buffers need
2527 // not have additional alignment beyond sample
2528 // (e.g. 16 bit stereo accessed as 32 bit frame).
2529 size_t alignment = audio_bytes_per_sample(format);
2530 if (alignment & 1) {
2531 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2532 alignment = 1;
2533 }
2534 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2535 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2536 if (channelCount > 1) {
2537 // More than 2 channels does not require stronger alignment than stereo
2538 alignment <<= 1;
2539 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002540 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002541 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002542 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002543 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002544 goto Exit;
2545 }
Eric Laurent21da6472017-11-09 16:29:26 -08002546
2547 // When initializing a shared buffer AudioTrack via constructors,
2548 // there's no frameCount parameter.
2549 // But when initializing a shared buffer AudioTrack via set(),
2550 // there _is_ a frameCount parameter. We silently ignore it.
2551 frameCount = sharedBuffer->size() / frameSize;
2552 } else {
2553 size_t minFrameCount = 0;
2554 // For fast tracks we try to respect the application's request for notifications per buffer.
2555 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2556 if (notificationsPerBuffer > 0) {
2557 // Avoid possible arithmetic overflow during multiplication.
2558 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2559 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2560 notificationsPerBuffer, mFrameCount);
2561 } else {
2562 minFrameCount = mFrameCount * notificationsPerBuffer;
2563 }
2564 }
2565 } else {
2566 // For normal PCM streaming tracks, update minimum frame count.
2567 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2568 // cover audio hardware latency.
2569 // This is probably too conservative, but legacy application code may depend on it.
2570 // If you change this calculation, also review the start threshold which is related.
2571 uint32_t latencyMs = latency_l();
2572 if (latencyMs == 0) {
2573 ALOGE("Error when retrieving output stream latency");
2574 lStatus = UNKNOWN_ERROR;
2575 goto Exit;
2576 }
2577
2578 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2579 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2580
Eric Laurent81784c32012-11-19 14:55:58 -08002581 }
Eric Laurent21da6472017-11-09 16:29:26 -08002582 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002583 frameCount = minFrameCount;
2584 }
Eric Laurent81784c32012-11-19 14:55:58 -08002585 }
Eric Laurent21da6472017-11-09 16:29:26 -08002586
2587 // Make sure that application is notified with sufficient margin before underrun.
2588 // The client can divide the AudioTrack buffer into sub-buffers,
2589 // and expresses its desire to server as the notification frame count.
2590 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2591 size_t maxNotificationFrames;
2592 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2593 // notify every HAL buffer, regardless of the size of the track buffer
2594 maxNotificationFrames = mFrameCount;
2595 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002596 // Triple buffer the notification period for a triple buffered mixer period;
2597 // otherwise, double buffering for the notification period is fine.
2598 //
2599 // TODO: This should be moved to AudioTrack to modify the notification period
2600 // on AudioTrack::setBufferSizeInFrames() changes.
2601 const int nBuffering =
2602 (uint64_t{frameCount} * mSampleRate)
2603 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2604
Eric Laurent21da6472017-11-09 16:29:26 -08002605 maxNotificationFrames = frameCount / nBuffering;
2606 // If client requested a fast track but this was denied, then use the smaller maximum.
2607 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2608 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2609 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2610 maxNotificationFrames = maxNotificationFramesFastDenied;
2611 }
2612 }
2613 }
2614 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2615 if (notificationFrameCount == 0) {
2616 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2617 maxNotificationFrames, frameCount);
2618 } else {
2619 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2620 notificationFrameCount, maxNotificationFrames, frameCount);
2621 }
2622 notificationFrameCount = maxNotificationFrames;
2623 }
2624 }
2625
Glenn Kasten74935e42013-12-19 08:56:45 -08002626 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002627 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002628
Glenn Kastenc3df8382014-03-13 15:05:25 -07002629 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002630 case BIT_PERFECT:
2631 if (isBitPerfect) {
2632 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2633 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2634 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2635 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2636 mChannelMask);
2637 lStatus = BAD_VALUE;
2638 goto Exit;
2639 }
2640 }
2641 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002642
2643 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002644 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002645 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002646 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2647 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002648 sampleRate, format, channelMask, mOutput, mFormat);
2649 lStatus = BAD_VALUE;
2650 goto Exit;
2651 }
2652 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002653 break;
2654
2655 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002656 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002657 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2658 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002659 sampleRate, format, channelMask, mOutput, mFormat);
2660 lStatus = BAD_VALUE;
2661 goto Exit;
2662 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002663 break;
2664
2665 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002666 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002667 ALOGE("createTrack_l() Bad parameter: format %#x \""
2668 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002669 format, mOutput, mFormat);
2670 lStatus = BAD_VALUE;
2671 goto Exit;
2672 }
Andy Hungcd044842014-08-07 11:04:34 -07002673 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002674 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2675 lStatus = BAD_VALUE;
2676 goto Exit;
2677 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002678 break;
2679
Eric Laurent81784c32012-11-19 14:55:58 -08002680 }
2681
2682 lStatus = initCheck();
2683 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002684 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002685 goto Exit;
2686 }
2687
Andy Hungc5007f82023-08-29 14:26:09 -07002688 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002689 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002690
2691 // all tracks in same audio session must share the same routing strategy otherwise
2692 // conflicts will happen when tracks are moved from one output to another by audio policy
2693 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002694 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002695 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002696 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002697 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002698 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002699 if (sessionId == t->sessionId() && strategy != actual) {
2700 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2701 strategy, actual);
2702 lStatus = BAD_VALUE;
2703 goto Exit;
2704 }
2705 }
2706 }
2707
Deeraj Soman2b515232024-05-14 12:58:24 +05302708 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2709 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002710 // dynamic audio policy.
2711 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302712 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002713 audio_output_flags_t trackFlags = *flags;
2714 if (mType == DIRECT) {
2715 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302716 } else if (mType == OFFLOAD) {
2717 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2718 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002719 }
jiabin94ed47c2023-07-27 23:34:20 +00002720 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002721
Andy Hung8d31fd22023-06-26 19:20:57 -07002722 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002723 channelMask, frameCount,
2724 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002725 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002726 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Eric Laurent277a37e2024-07-29 18:37:52 +00002727 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002728
Glenn Kasten03003332013-08-06 15:40:54 -07002729 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2730 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002731 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002732 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002733 goto Exit;
2734 }
2735 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002736 {
Andy Hung972bec12023-08-31 16:13:39 -07002737 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002738 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002739 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002740 }
2741 }
Eric Laurent81784c32012-11-19 14:55:58 -08002742
Andy Hung116bc262023-06-20 18:56:17 -07002743 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002744 if (chain != 0) {
2745 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2746 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002747 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002748 chain->incTrackCnt();
2749 }
2750
Eric Laurent05067782016-06-01 18:27:28 -07002751 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002752 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2753 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2754 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002755 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002756 }
2757 }
2758
2759 lStatus = NO_ERROR;
2760
2761Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002762 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002763 return track;
2764}
2765
Andy Hung1bc088a2018-02-09 15:57:31 -08002766template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002767ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002768{
Andy Hungc0691382018-09-12 18:01:57 -07002769 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002770 const ssize_t index = mTracks.remove(track);
2771 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002772 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002773 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002774 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002775 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002776 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002777 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002778 }
2779 return index;
2780}
2781
Andy Hungee58e4a2023-07-07 13:47:37 -07002782uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002783{
2784 return latency;
2785}
2786
Andy Hungee58e4a2023-07-07 13:47:37 -07002787uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002788{
Andy Hung972bec12023-08-31 16:13:39 -07002789 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002790 return latency_l();
2791}
Andy Hungee58e4a2023-07-07 13:47:37 -07002792uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002793NO_THREAD_SAFETY_ANALYSIS
2794// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002795{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002796 uint32_t latency;
2797 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2798 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002799 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002800 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002801}
2802
Andy Hungee58e4a2023-07-07 13:47:37 -07002803void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002804{
Andy Hung972bec12023-08-31 16:13:39 -07002805 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002806 // Don't apply master volume in SW if our HAL can do it for us.
2807 if (mOutput && mOutput->audioHwDev &&
2808 mOutput->audioHwDev->canSetMasterVolume()) {
2809 mMasterVolume = 1.0;
2810 } else {
2811 mMasterVolume = value;
2812 }
2813}
2814
Andy Hungee58e4a2023-07-07 13:47:37 -07002815void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002816{
2817 mMasterBalance.store(balance);
2818}
2819
Andy Hungee58e4a2023-07-07 13:47:37 -07002820void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002821{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002822 if (isDuplicating()) {
2823 return;
2824 }
Andy Hung972bec12023-08-31 16:13:39 -07002825 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002826 // Don't apply master mute in SW if our HAL can do it for us.
2827 if (mOutput && mOutput->audioHwDev &&
2828 mOutput->audioHwDev->canSetMasterMute()) {
2829 mMasterMute = false;
2830 } else {
2831 mMasterMute = muted;
2832 }
2833}
2834
Andy Hungee58e4a2023-07-07 13:47:37 -07002835void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002836{
Andy Hung972bec12023-08-31 16:13:39 -07002837 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002838 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002839 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002840}
2841
Andy Hungee58e4a2023-07-07 13:47:37 -07002842void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002843{
Andy Hung972bec12023-08-31 16:13:39 -07002844 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002845 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002846 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002847}
2848
Andy Hungee58e4a2023-07-07 13:47:37 -07002849float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002850{
Andy Hung972bec12023-08-31 16:13:39 -07002851 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002852 return mStreamTypes[stream].volume;
2853}
2854
Andy Hungee58e4a2023-07-07 13:47:37 -07002855void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002856{
2857 mOutput->stream->setVolume(left, right);
2858}
2859
Andy Hungc5007f82023-08-29 14:26:09 -07002860// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002861status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002862{
2863 status_t status = ALREADY_EXISTS;
2864
Eric Laurent81784c32012-11-19 14:55:58 -08002865 if (mActiveTracks.indexOf(track) < 0) {
2866 // the track is newly added, make sure it fills up all its
2867 // buffers before playing. This is to ensure the client will
2868 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002869 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002870 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002871 // Because the track is not on the ActiveTracks,
2872 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002873 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002874 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002875 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002877 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002878 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002879 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002880 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002881 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002882 }
2883 return INVALID_OPERATION;
2884 }
2885 // abort if start is rejected by audio policy manager
2886 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002887 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2888 // current playback thread is reopened, which may happen when clients set preferred
2889 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2890 // immediately.
2891 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002892 }
2893#ifdef ADD_BATTERY_DATA
2894 // to track the speaker usage
2895 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2896#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002897 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002898 }
2899
Eric Laurent51716182016-02-29 18:00:56 -08002900 // set retry count for buffer fill
2901 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002902 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002903 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002904 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002905 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002906 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002907 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002908 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002909 track->retryCount() = kMaxTrackStartupRetries;
2910 track->fillingStatus() =
2911 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002912 }
2913
Andy Hung116bc262023-06-20 18:56:17 -07002914 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002915 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2916 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002917 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002918 // Unlock due to VibratorService will lock for this call and will
2919 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002920 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002921 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002922 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002923 std::optional<media::AudioVibratorInfo> vibratorInfo;
2924 {
2925 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2926 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002927 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002928 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002929 }
Andy Hungc5007f82023-08-29 14:26:09 -07002930 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002931 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002932 if (vibratorInfo) {
2933 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2934 }
2935
jiabin57303cc2018-12-18 15:45:57 -08002936 // Haptic playback should be enabled by vibrator service.
2937 if (track->getHapticPlaybackEnabled()) {
2938 // Disable haptic playback of all active track to ensure only
2939 // one track playing haptic if current track should play haptic.
2940 for (const auto &t : mActiveTracks) {
2941 t->setHapticPlaybackEnabled(false);
2942 }
jiabin245cdd92018-12-07 17:55:15 -08002943 }
jiabine70bc7f2020-06-30 22:07:55 -07002944
2945 // Set haptic intensity for effect
2946 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002947 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002948 }
jiabin245cdd92018-12-07 17:55:15 -08002949 }
2950
Andy Hung8d31fd22023-06-26 19:20:57 -07002951 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002952 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002953
2954 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2955 // all key changes are complete. It is possible that the threadLoop will begin
2956 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002957 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002958
Eric Laurentd0107bc2013-06-11 14:38:48 -07002959 if (chain != 0) {
2960 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2961 track->sessionId());
2962 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002963 }
2964
Andy Hungc2b11cb2020-04-22 09:04:01 -07002965 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002966 status = NO_ERROR;
2967 }
2968
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002969 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002970 return status;
2971}
2972
Andy Hungee58e4a2023-07-07 13:47:37 -07002973bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002974{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002975 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002976 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002977 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002978 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002979 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002980 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002981 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002982 if (track->isPausePending()) {
2983 track->pauseAck();
2984 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002985 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002986 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002987
2988 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002989}
2990
Andy Hungee58e4a2023-07-07 13:47:37 -07002991void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002992{
2993 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002994
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002995 String8 result;
2996 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002997 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002998
Eric Laurent81784c32012-11-19 14:55:58 -08002999 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003000 {
Andy Hung972bec12023-08-31 16:13:39 -07003001 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003002 mAudioTrackCallbacks.erase(track);
3003 }
Eric Laurent81784c32012-11-19 14:55:58 -08003004 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003005 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003006 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003007 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3008 mFastTrackAvailMask |= 1 << index;
3009 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003010 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003011 }
Andy Hung116bc262023-06-20 18:56:17 -07003012 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003013 if (chain != 0) {
3014 chain->decTrackCnt();
3015 }
3016}
3017
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003018std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3019{
3020 std::set<int32_t> result;
3021 for (const auto& t : mTracks) {
3022 if (t->isExternalTrack()) {
3023 result.insert(t->portId());
3024 }
3025 }
3026 return result;
3027}
3028
3029std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3030{
3031 audio_utils::lock_guard _l(mutex());
3032 return getTrackPortIds_l();
3033}
3034
Andy Hungee58e4a2023-07-07 13:47:37 -07003035String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003036{
Andy Hung972bec12023-08-31 16:13:39 -07003037 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003038 String8 out_s8;
3039 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3040 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003041 }
Andy Hung920f6572022-10-06 12:09:49 -07003042 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003043}
3044
Andy Hungee58e4a2023-07-07 13:47:37 -07003045status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003046 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003047 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003048 return NO_INIT;
3049 }
3050 return mOutput->stream->selectPresentation(presentationId, programId);
3051}
3052
Andy Hungab65b182023-09-06 19:41:47 -07003053void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003054 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003055 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003056 sp<AudioIoDescriptor> desc;
3057 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003058 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003059 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003060 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003061 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003062 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3063 mSampleRate, mFormat, mChannelMask,
3064 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3065 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003066 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003067 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003068 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003069 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003070 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003071 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003072 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003073 break;
3074 }
Andy Hungab65b182023-09-06 19:41:47 -07003075 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003076}
3077
Andy Hungee58e4a2023-07-07 13:47:37 -07003078void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003079{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003080 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081}
3082
Andy Hungee58e4a2023-07-07 13:47:37 -07003083void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003084{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003085 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003086}
3087
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003088void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003089{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003090 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003091}
3092
Andy Hungee58e4a2023-07-07 13:47:37 -07003093void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003094 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003095{
Andy Hungee58e4a2023-07-07 13:47:37 -07003096 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003097 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003098 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003099 if (playbackThread == nullptr) {
3100 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3101 return;
3102 }
3103
jiabinf6eb4c32020-02-25 14:06:25 -08003104 audio_utils::metadata::Data metadata =
3105 audio_utils::metadata::dataFromByteString(metadataBs);
3106 if (metadata.empty()) {
3107 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3108 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3109 (int)metadataBs.size());
3110 return;
3111 }
3112
3113 audio_utils::metadata::ByteString metaDataStr =
3114 audio_utils::metadata::byteStringFromData(metadata);
3115 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003116 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003117 for (const auto& callbackPair : mAudioTrackCallbacks) {
3118 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003119 }
3120 }).detach();
3121}
3122
Andy Hungee58e4a2023-07-07 13:47:37 -07003123void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003124{
Andy Hung972bec12023-08-31 16:13:39 -07003125 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003126 // reject out of sequence requests
3127 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3128 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003129 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003130 }
3131}
3132
Andy Hungee58e4a2023-07-07 13:47:37 -07003133void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003134{
Andy Hung972bec12023-08-31 16:13:39 -07003135 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003136 // reject out of sequence requests
3137 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003138 // Register discontinuity when HW drain is completed because that can cause
3139 // the timestamp frame position to reset to 0 for direct and offload threads.
3140 // (Out of sequence requests are ignored, since the discontinuity would be handled
3141 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003142 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003143 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003144 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003145 }
3146}
3147
Andy Hungee58e4a2023-07-07 13:47:37 -07003148void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003149NO_THREAD_SAFETY_ANALYSIS
3150// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003151{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003152 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003153 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3154 mSampleRate = audioConfig.sample_rate;
3155 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003156 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003157 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003158 }
Andy Hung81994d62023-07-20 21:44:14 -07003159 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003160 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3161 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003162 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003163
3164 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3165 mMixerChannelMask = mChannelMask;
3166 }
3167
Andy Hunge5412692014-05-16 11:25:07 -07003168 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003169 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003170
Eric Laurentf1f22e72021-07-13 14:04:14 +02003171 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3172
Phil Burkca5e6142015-07-14 09:42:29 -07003173 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003174 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003175 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003176 // Get format from the shim, which will be different than the HAL format
3177 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003178 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003179 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003180 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003181 }
Andy Hung81994d62023-07-20 21:44:14 -07003182 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003183 LOG_FATAL("HAL format %#x not supported for mixed output",
3184 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003185 }
Phil Burk062e67a2015-02-11 13:40:50 -08003186 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003187 result = mOutput->stream->getBufferSize(&mBufferSize);
3188 LOG_ALWAYS_FATAL_IF(result != OK,
3189 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003190 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003191 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003192 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003193 mFrameCount);
3194 }
3195
Eric Laurentd1f69b02014-12-15 14:33:13 -08003196 mHwSupportsPause = false;
3197 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003198 bool supportsPause = false, supportsResume = false;
3199 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3200 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003201 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003202 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003203 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003204 } else if (supportsResume) {
3205 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003206 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003207 }
3208 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003209 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3210 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3211 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003212
Andy Hungfbfc3952015-01-15 13:33:51 -08003213 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3214 // For best precision, we use float instead of the associated output
3215 // device format (typically PCM 16 bit).
3216
3217 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3218 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3219 mBufferSize = mFrameSize * mFrameCount;
3220
3221 // TODO: We currently use the associated output device channel mask and sample rate.
3222 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3223 // (if a valid mask) to avoid premature downmix.
3224 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3225 // instead of the output device sample rate to avoid loss of high frequency information.
3226 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3227 }
3228
Andy Hung09a50072014-02-27 14:30:47 -08003229 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003230 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003231 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003232 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3233 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003234 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3235 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003236
Eric Laurent81784c32012-11-19 14:55:58 -08003237 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3238 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3239 maxNormalFrameCount = maxNormalFrameCount & ~15;
3240 if (maxNormalFrameCount < minNormalFrameCount) {
3241 maxNormalFrameCount = minNormalFrameCount;
3242 }
3243 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3244 if (multiplier <= 1.0) {
3245 multiplier = 1.0;
3246 } else if (multiplier <= 2.0) {
3247 if (2 * mFrameCount <= maxNormalFrameCount) {
3248 multiplier = 2.0;
3249 } else {
3250 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3251 }
3252 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003253 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003254 }
3255 }
3256 mNormalFrameCount = multiplier * mFrameCount;
3257 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003258 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003259 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3260 }
Andy Hungab65b182023-09-06 19:41:47 -07003261 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3262 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003263
Andy Hung08fb1742015-05-31 23:22:10 -07003264 // Check if we want to throttle the processing to no more than 2x normal rate
3265 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003266 mThreadThrottleTimeMs = 0;
3267 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003268 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3269
Andy Hung010a1a12014-03-13 13:57:33 -07003270 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3271 // Originally this was int16_t[] array, need to remove legacy implications.
3272 free(mSinkBuffer);
3273 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003274
Andy Hung5b10a202014-03-13 13:59:29 -07003275 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3276 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3277 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003278 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003279
Andy Hung69aed5f2014-02-25 17:24:40 -08003280 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3281 // drives the output.
3282 free(mMixerBuffer);
3283 mMixerBuffer = NULL;
3284 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003285 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003286 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003287 * audio_bytes_per_sample(mMixerBufferFormat);
3288 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3289 }
Andy Hung98ef9782014-03-04 14:46:50 -08003290 free(mEffectBuffer);
3291 mEffectBuffer = NULL;
3292 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003293 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003294 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003295 * audio_bytes_per_sample(mEffectBufferFormat);
3296 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3297 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003298
Eric Laurentb62d0362021-10-26 17:40:18 +02003299 if (mType == SPATIALIZER) {
3300 free(mPostSpatializerBuffer);
3301 mPostSpatializerBuffer = nullptr;
3302 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3303 * audio_bytes_per_sample(mEffectBufferFormat);
3304 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3305 }
3306
Mikhail Naganov55773032020-10-01 15:08:13 -07003307 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3308 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003309 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3310 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003311 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003312
Eric Laurent81784c32012-11-19 14:55:58 -08003313 // force reconfiguration of effect chains and engines to take new buffer size and audio
3314 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003315 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003316 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3317 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003318 // create a copy of mEffectChains as calling moveEffectChain_ll()
3319 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003320 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003321 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003322 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003323 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003324 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003325
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003326 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003327 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003328 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003329 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003330 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3331 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3332 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3333 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3334 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3335 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3336 (int32_t)mHapticChannelMask)
3337 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3338 (int32_t)mHapticChannelCount)
3339 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003340 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003341 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3342 (int32_t)mFrameCount) // sic - added HAL
3343 ;
3344 uint32_t latencyMs;
3345 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3346 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3347 }
3348 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003349}
3350
Andy Hungee58e4a2023-07-07 13:47:37 -07003351ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003352{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003353 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003354 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003355 }
3356 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003357 static const bool stereo_spatialization_property =
3358 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3359 const bool stereo_spatialization_enabled =
3360 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3361 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003362 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3363 for (const sp<IAfTrack>& track : mActiveTracks) {
3364 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3365 allSessionsMetadata[track->sessionId()];
3366 auto backInserter = std::back_inserter(sessionMetadata);
3367 // No track is invalid as this is called after prepareTrack_l in the same
3368 // critical section
3369 track->copyMetadataTo(backInserter);
3370 }
3371 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3372 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3373 metadata.tracks.insert(metadata.tracks.end(),
3374 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3375 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3376 chain->sendMetadata_l(sessionTrackMetadata, {});
3377 }
3378 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3379 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3380 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3381 }
3382 }
3383 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3384 chain->sendMetadata_l(metadata.tracks, {});
3385 }
3386 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3387 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3388 }
3389 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3390 chain->sendMetadata_l(metadata.tracks, {});
3391 }
3392 } else {
3393 auto backInserter = std::back_inserter(metadata.tracks);
3394 for (const sp<IAfTrack>& track : mActiveTracks) {
3395 // No track is invalid as this is called after prepareTrack_l in the same
3396 // critical section
3397 track->copyMetadataTo(backInserter);
3398 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003399 }
Kevin Rocard12381092018-04-11 09:19:59 -07003400 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003401 MetadataUpdate change;
3402 change.playbackMetadataUpdate = metadata.tracks;
3403 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003404}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003405
Andy Hungee58e4a2023-07-07 13:47:37 -07003406void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003407 const StreamOutHalInterface::SourceMetadata& metadata)
3408{
3409 mOutput->stream->updateSourceMetadata(metadata);
3410};
3411
Andy Hungee58e4a2023-07-07 13:47:37 -07003412status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003413 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003414{
3415 if (halFrames == NULL || dspFrames == NULL) {
3416 return BAD_VALUE;
3417 }
Andy Hung972bec12023-08-31 16:13:39 -07003418 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003419 if (initCheck() != NO_ERROR) {
3420 return INVALID_OPERATION;
3421 }
Andy Hung818e7a32016-02-16 18:08:07 -08003422 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003423 *halFrames = framesWritten;
3424
3425 if (isSuspended()) {
3426 // return an estimation of rendered frames when the output is suspended
3427 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003428 *dspFrames = (uint32_t)
3429 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003430 return NO_ERROR;
3431 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003432 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003433 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003434 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003435 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003436 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003437 }
3438}
3439
Andy Hungee58e4a2023-07-07 13:47:37 -07003440product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003441{
3442 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3443 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3444 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003445 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003446 }
3447 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003448 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003449 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003450 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003451 }
3452 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003453 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003454}
3455
3456
Andy Hungee58e4a2023-07-07 13:47:37 -07003457AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003458{
Andy Hung972bec12023-08-31 16:13:39 -07003459 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003460 return mOutput;
3461}
3462
Andy Hungee58e4a2023-07-07 13:47:37 -07003463AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003464{
Andy Hung972bec12023-08-31 16:13:39 -07003465 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003466 AudioStreamOut *output = mOutput;
3467 mOutput = NULL;
3468 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3469 // must push a NULL and wait for ack
3470 mOutputSink.clear();
3471 mPipeSink.clear();
3472 mNormalSink.clear();
3473 return output;
3474}
3475
Andy Hungc5007f82023-08-29 14:26:09 -07003476// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003477sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003478{
3479 if (mOutput == NULL) {
3480 return NULL;
3481 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003482 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003483}
3484
Andy Hungee58e4a2023-07-07 13:47:37 -07003485uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003486{
3487 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3488}
3489
Andy Hungee58e4a2023-07-07 13:47:37 -07003490status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003491{
3492 if (!isValidSyncEvent(event)) {
3493 return BAD_VALUE;
3494 }
3495
Andy Hung972bec12023-08-31 16:13:39 -07003496 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003497
3498 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003499 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003500 if (event->triggerSession() == track->sessionId()) {
3501 (void) track->setSyncEvent(event);
3502 return NO_ERROR;
3503 }
3504 }
3505
3506 return NAME_NOT_FOUND;
3507}
3508
Andy Hungee58e4a2023-07-07 13:47:37 -07003509bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003510{
3511 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3512}
3513
Andy Hungee58e4a2023-07-07 13:47:37 -07003514void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003515 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003516{
Andy Hungfe726a62018-09-27 15:17:25 -07003517 // Miscellaneous track cleanup when removed from the active list,
3518 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003519#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003520 for (const auto& track : tracksToRemove) {
3521 if (track->isExternalTrack()) {
3522 // to track the speaker usage
3523 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003524 }
3525 }
Andy Hungfe726a62018-09-27 15:17:25 -07003526#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003527}
3528
Andy Hungee58e4a2023-07-07 13:47:37 -07003529void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003530{
3531 if (!mMasterMute) {
3532 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003533 if (mOutDeviceTypeAddrs.empty()) {
3534 ALOGD("ro.audio.silent is ignored since no output device is set");
3535 return;
3536 }
Andy Hungab65b182023-09-06 19:41:47 -07003537 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003538 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3539 return;
3540 }
Eric Laurent81784c32012-11-19 14:55:58 -08003541 if (property_get("ro.audio.silent", value, "0") > 0) {
3542 char *endptr;
3543 unsigned long ul = strtoul(value, &endptr, 0);
3544 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003545 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003546 // The setprop command will not allow a property to be changed after
3547 // the first time it is set, so we don't have to worry about un-muting.
3548 setMasterMute_l(true);
3549 }
3550 }
3551 }
3552}
3553
3554// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003555ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003556{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003557 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003558 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003559 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003560 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003561
3562 // If an NBAIO sink is present, use it to write the normal mixer's submix
3563 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003564
Andy Hung010a1a12014-03-13 13:57:33 -07003565 const size_t count = mBytesRemaining / mFrameSize;
3566
Simon Wilson2d590962012-11-29 15:18:50 -08003567 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003568 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003569 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003570 if (screenState != mScreenState) {
3571 mScreenState = screenState;
3572 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3573 if (pipe != NULL) {
3574 pipe->setAvgFrames((mScreenState & 1) ?
3575 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3576 }
3577 }
Andy Hung010a1a12014-03-13 13:57:33 -07003578 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003579 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003580
Eric Laurent81784c32012-11-19 14:55:58 -08003581 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003582 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003583
Andy Hung8946a282018-04-19 20:04:56 -07003584#ifdef TEE_SINK
3585 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3586#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003587 } else {
3588 bytesWritten = framesWritten;
3589 }
3590 // otherwise use the HAL / AudioStreamOut directly
3591 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003592 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003593
Eric Laurentbfb1b832013-01-07 09:53:42 -08003594 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003595 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3596 mWriteAckSequence += 2;
3597 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003598 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003599 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003600 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003601 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003602 // FIXME We should have an implementation of timestamps for direct output threads.
3603 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003604 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003605 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003606
Eric Laurentbfb1b832013-01-07 09:53:42 -08003607 if (mUseAsyncWrite &&
3608 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3609 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003610 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003611 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003612 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613 }
Eric Laurent81784c32012-11-19 14:55:58 -08003614 }
3615
Eric Laurent81784c32012-11-19 14:55:58 -08003616 mNumWrites++;
3617 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003618 if (mStandby) {
3619 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003620 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003621 mStandby = false;
3622 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623 return bytesWritten;
3624}
3625
Andy Hungc5007f82023-08-29 14:26:09 -07003626// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003627void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003628 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003629{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003630 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003631 if (outputSink != nullptr) {
3632 outputSink->startMelComputation(processor);
3633 }
Vlad Popab042ee62022-10-20 18:05:00 +02003634}
3635
Andy Hungc5007f82023-08-29 14:26:09 -07003636// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003637void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003638{
3639 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003640 if (outputSink != nullptr) {
3641 outputSink->stopMelComputation();
3642 }
Vlad Popab042ee62022-10-20 18:05:00 +02003643}
3644
Andy Hungee58e4a2023-07-07 13:47:37 -07003645void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003646{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003647 bool supportsDrain = false;
3648 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003649 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3650 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003651 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3652 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003653 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003654 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003655 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003656 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003657 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003658 }
3659}
3660
Andy Hungee58e4a2023-07-07 13:47:37 -07003661void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003662{
Eric Laurent275e8e92014-11-30 15:14:47 -08003663 {
Andy Hung972bec12023-08-31 16:13:39 -07003664 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003665 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003666 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003667 track->invalidate();
3668 }
Andy Hungdae27702016-10-31 14:01:16 -07003669 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3670 // After we exit there are no more track changes sent to BatteryNotifier
3671 // because that requires an active threadLoop.
3672 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3673 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003674 }
Eric Laurent81784c32012-11-19 14:55:58 -08003675}
3676
3677/*
3678The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003679 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003680 - mActiveSleepTimeUs from activeSleepTimeUs()
3681 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003682 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3683 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003684 - maxPeriod from frame count and sample rate (MIXER only)
3685
3686The parameters that affect these derived values are:
3687 - frame count
3688 - frame size
3689 - sample rate
3690 - device type: A2DP or not
3691 - device latency
3692 - format: PCM or not
3693 - active sleep time
3694 - idle sleep time
3695*/
3696
Andy Hungee58e4a2023-07-07 13:47:37 -07003697void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003698{
Andy Hung25c2dac2014-02-27 14:56:00 -08003699 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003700 mActiveSleepTimeUs = activeSleepTimeUs();
3701 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003702
Andy Hung8fe87eb2023-07-20 21:31:38 -07003703 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003704
Eric Laurent42537be2016-01-08 17:16:42 -08003705 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3706 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003707 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003708 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3709 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3710 }
3711 }
Eric Laurent81784c32012-11-19 14:55:58 -08003712}
3713
Andy Hungee58e4a2023-07-07 13:47:37 -07003714bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003715{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003716 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003717 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003718 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003719 size_t size = mTracks.size();
3720 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003721 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003722 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003723 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003724 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003725 }
3726 }
Eric Laurent13084622016-05-17 10:51:49 -07003727 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003728}
3729
Andy Hungee58e4a2023-07-07 13:47:37 -07003730void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003731{
Andy Hung972bec12023-08-31 16:13:39 -07003732 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003733 invalidateTracks_l(streamType);
3734}
3735
Andy Hungee58e4a2023-07-07 13:47:37 -07003736void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003737 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003738 invalidateTracks_l(portIds);
3739}
3740
Andy Hungee58e4a2023-07-07 13:47:37 -07003741bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003742 bool trackMatch = false;
3743 const size_t size = mTracks.size();
3744 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003745 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003746 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3747 t->invalidate();
3748 portIds.erase(t->portId());
3749 trackMatch = true;
3750 }
3751 if (portIds.empty()) {
3752 break;
3753 }
3754 }
3755 return trackMatch;
3756}
3757
jiabinf042b9b2021-05-07 23:46:28 +00003758// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003759IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003760 audio_port_handle_t trackPortId) {
3761 for (size_t i = 0; i < mTracks.size(); i++) {
3762 if (mTracks[i]->portId() == trackPortId) {
3763 return mTracks[i].get();
3764 }
3765 }
3766 return nullptr;
3767}
3768
Andy Hungee58e4a2023-07-07 13:47:37 -07003769status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003770{
Glenn Kastend848eb42016-03-08 13:42:11 -08003771 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003772 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003773 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003774
Andy Hungd3639922022-04-28 18:00:49 -07003775 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003776 if (!audio_is_global_session(session)) {
3777 // player sessions on a spatializer output will use a dedicated input buffer and
3778 // will either output multi channel to mEffectBuffer if the track is spatilaized
3779 // or stereo to mPostSpatializerBuffer if not spatialized.
3780 uint32_t channelMask;
3781 bool isSessionSpatialized =
3782 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3783 if (isSessionSpatialized) {
3784 channelMask = mMixerChannelMask;
3785 } else {
3786 channelMask = mChannelMask;
3787 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003788 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003789 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003790 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003791 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003792 &halInBuffer);
3793 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003794
Andy Hung583043b2023-07-17 17:05:00 -07003795 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003796 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3797 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3798 &halOutBuffer);
3799 if (result != OK) return result;
3800
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003801 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003802
Mikhail Naganov022b9952017-01-04 16:36:51 -08003803 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3804 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003805 } else {
3806 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3807 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3808 // mPostSpatializerBuffer as output buffer
3809 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003810 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003811 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3812 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003813 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003814 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3815 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003816
Eric Laurentb62d0362021-10-26 17:40:18 +02003817 if (session == AUDIO_SESSION_DEVICE) {
3818 halInBuffer = halOutBuffer;
3819 }
3820 }
3821 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003822 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003823 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3824 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3825 &halInBuffer);
3826 if (result != OK) return result;
3827 halOutBuffer = halInBuffer;
3828 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3829 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003830 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003831 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003832 // Only one effect chain can be present in direct output thread and it uses
3833 // the sink buffer as input
3834 if (mType != DIRECT) {
3835 size_t numSamples = mNormalFrameCount
3836 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3837 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003838 const status_t allocateStatus =
3839 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003840 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003841 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003842 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003843
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003844 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003845 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3846 buffer, session);
3847 }
3848 }
3849 }
3850
3851 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003852 // Attach all tracks with same session ID to this chain.
3853 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003854 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003855 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003856 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3857 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003858 track->setMainBuffer(buffer);
3859 chain->incTrackCnt();
3860 }
3861 }
3862
3863 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003864 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003865 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003866 ALOGV("addEffectChain_l() activating track %p on session %d",
3867 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003868 chain->incActiveTrackCnt();
3869 }
3870 }
3871 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003872
Eric Laurentaaa44472014-09-12 17:41:50 -07003873 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003874 chain->setInBuffer(halInBuffer);
3875 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003876 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3877 // chains list in order to be processed last as it contains output device effects.
3878 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3879 // processing effects specific to an output stream before effects applied to all streams
3880 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003881 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3882 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003883 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003884 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003885 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003886 // Effect chain for other sessions are inserted at beginning of effect
3887 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003888 // sessions is not important.
3889 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003890 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3891 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003892 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003893 size_t size = mEffectChains.size();
3894 size_t i = 0;
3895 for (i = 0; i < size; i++) {
3896 if (mEffectChains[i]->sessionId() < session) {
3897 break;
3898 }
3899 }
3900 mEffectChains.insertAt(chain, i);
3901 checkSuspendOnAddEffectChain_l(chain);
3902
3903 return NO_ERROR;
3904}
3905
Andy Hungee58e4a2023-07-07 13:47:37 -07003906size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003907{
Glenn Kastend848eb42016-03-08 13:42:11 -08003908 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003909
3910 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3911
3912 for (size_t i = 0; i < mEffectChains.size(); i++) {
3913 if (chain == mEffectChains[i]) {
3914 mEffectChains.removeAt(i);
3915 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003916 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003917 if (session == track->sessionId()) {
3918 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3919 chain.get(), session);
3920 chain->decActiveTrackCnt();
3921 }
3922 }
3923
3924 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003925 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003926 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003927 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003928 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003929 chain->decTrackCnt();
3930 }
3931 }
3932 break;
3933 }
3934 }
3935 return mEffectChains.size();
3936}
3937
Andy Hungee58e4a2023-07-07 13:47:37 -07003938status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003939 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003940{
Andy Hung972bec12023-08-31 16:13:39 -07003941 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003942 return attachAuxEffect_l(track, EffectId);
3943}
3944
Andy Hungee58e4a2023-07-07 13:47:37 -07003945status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003946 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003947{
3948 status_t status = NO_ERROR;
3949
3950 if (EffectId == 0) {
3951 track->setAuxBuffer(0, NULL);
3952 } else {
3953 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003954 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003955 if (effect != 0) {
3956 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3957 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3958 } else {
3959 status = INVALID_OPERATION;
3960 }
3961 } else {
3962 status = BAD_VALUE;
3963 }
3964 }
3965 return status;
3966}
3967
Andy Hungee58e4a2023-07-07 13:47:37 -07003968void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003969{
3970 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003971 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003972 if (track->auxEffectId() == effectId) {
3973 attachAuxEffect_l(track, 0);
3974 }
3975 }
3976}
3977
Andy Hungee58e4a2023-07-07 13:47:37 -07003978bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003979NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003980{
Andy Hung78d8d952023-05-30 18:10:23 -07003981 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003982
Andy Hung077d62e2023-10-03 10:49:34 -07003983 if (mType == SPATIALIZER) {
3984 const pid_t tid = getTid();
3985 if (tid == -1) { // odd: we are here, we must be a running thread.
3986 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3987 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003988 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3989 if (priorityBoost > 0) {
3990 stream()->setHalThreadPriority(priorityBoost);
3991 }
Andy Hung077d62e2023-10-03 10:49:34 -07003992 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003993 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3994 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3995 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3996 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3997 // only on ARC.
3998 const pid_t tid = getTid();
3999 if (tid == -1) {
4000 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4001 } else {
4002 const status_t status = requestPriority(getpid(),
4003 tid,
4004 kPriorityPlaybackThreadArc,
4005 false /* isForApp */,
4006 true /* asynchronous */);
4007 if (status != OK) {
4008 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4009 status);
4010 } else {
4011 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4012 }
4013 }
Andy Hung077d62e2023-10-03 10:49:34 -07004014 }
4015
Andy Hung8d31fd22023-06-26 19:20:57 -07004016 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004017
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004018 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004019 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004020
4021 // MIXER
4022 nsecs_t lastWarning = 0;
4023
4024 // DUPLICATING
4025 // FIXME could this be made local to while loop?
4026 writeFrames = 0;
4027
4028 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004029 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004030
Andy Hungd3639922022-04-28 18:00:49 -07004031 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004032 sleepTimeShift = 0;
4033 }
4034
4035 CpuStats cpuStats;
4036 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4037
4038 acquireWakeLock();
4039
Glenn Kasteneef598c2017-04-03 14:41:13 -07004040 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4041 // thread associated with this PlaybackThread.
4042 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4043 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004044 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4045 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004046 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004047 const char *logString = NULL;
4048
rago1bb90822017-05-02 18:31:48 -07004049 // Estimated time for next buffer to be written to hal. This is used only on
4050 // suspended mode (for now) to help schedule the wait time until next iteration.
4051 nsecs_t timeLoopNextNs = 0;
4052
Eric Laurent664539d2013-09-23 18:24:31 -07004053 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004054
Andy Hung2dbffc22018-08-08 18:50:41 -07004055 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004056
Eric Laurentb3f315a2021-07-13 15:09:05 +02004057 sendCheckOutputStageEffectsEvent();
4058
Andy Hung446f4df2019-02-21 12:26:41 -08004059 // loopCount is used for statistics and diagnostics.
4060 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004061 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004062 // Log merge requests are performed during AudioFlinger binder transactions, but
4063 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004064 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004065
Eric Laurent81784c32012-11-19 14:55:58 -08004066 cpuStats.sample(myName);
4067
Andy Hung116bc262023-06-20 18:56:17 -07004068 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004069 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004070 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004071 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004072
Andy Hung2dbffc22018-08-08 18:50:41 -07004073 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4074 //
Andy Hungc5007f82023-08-29 14:26:09 -07004075 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004076 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004077 // Here, we try for the AF lock, but do not block on it as the latency
4078 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004079 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004080 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004081 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004082 status_t status = INVALID_OPERATION;
4083 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004084 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004085 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004086 && swPatches.size() > 0) {
4087 status = swPatches[0].getLatencyMs_l(&latencyMs);
4088 downstreamPatchHandle = swPatches[0].getPatchHandle();
4089 }
4090 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004091 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004092 lastDownstreamPatchHandle = downstreamPatchHandle;
4093 }
4094 if (status == OK) {
4095 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004096 // latency of 5 seconds).
4097 const double minLatency = 0., maxLatency = 5000.;
4098 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004099 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004100 } else {
4101 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004102 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004103 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004104 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004105 }
Andy Hung583043b2023-07-17 17:05:00 -07004106 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004107 }
4108 } else {
4109 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4110 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004111 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004112 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4113 }
4114 }
4115
Eric Laurentb3f315a2021-07-13 15:09:05 +02004116 if (mCheckOutputStageEffects.exchange(false)) {
4117 checkOutputStageEffects();
4118 }
4119
Vlad Popa7e81cea2023-01-19 16:34:16 +01004120 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004121 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004122
Andy Hungc5007f82023-08-29 14:26:09 -07004123 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004124
Eric Laurent021cf962014-05-13 10:18:14 -07004125 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004126 if (mCheckOutputStageEffects.load()) {
4127 continue;
4128 }
Eric Laurent10351942014-05-08 18:49:52 -07004129
Andy Hungc5007f82023-08-29 14:26:09 -07004130 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004131 if (logString != NULL) {
4132 mNBLogWriter->logTimestamp();
4133 mNBLogWriter->log(logString);
4134 logString = NULL;
4135 }
4136
Dean Wheatley12473e92021-03-18 23:00:55 +11004137 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004138
Eric Laurent81784c32012-11-19 14:55:58 -08004139 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004140 if (mSignalPending) {
4141 // A signal was raised while we were unlocked
4142 mSignalPending = false;
4143 } else if (waitingAsyncCallback_l()) {
4144 if (exitPending()) {
4145 break;
4146 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004147 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004148 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004149 releaseWakeLock_l();
4150 released = true;
4151 }
Andy Hung10cbff12017-02-21 17:30:14 -08004152
4153 const int64_t waitNs = computeWaitTimeNs_l();
4154 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004155 std::cv_status cvstatus =
4156 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4157 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004158 mSignalPending = true; // if timeout recheck everything
4159 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004160 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004161 if (released) {
4162 acquireWakeLock_l();
4163 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004164 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4165 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004166
4167 continue;
4168 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004169 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004170 isSuspended()) {
4171 // put audio hardware into standby after short delay
4172 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004173
4174 threadLoop_standby();
4175
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004176 // This is where we go into standby
4177 if (!mStandby) {
4178 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004179 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004180 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004181 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004182 }
Andy Hungd0979812019-02-21 15:51:44 -08004183 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004184 }
4185
Eric Tan39ec8d62018-07-24 09:49:29 -07004186 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004187 // we're about to wait, flush the binder command buffer
4188 IPCThreadState::self()->flushCommands();
4189
4190 clearOutputTracks();
4191
4192 if (exitPending()) {
4193 break;
4194 }
4195
4196 releaseWakeLock_l();
4197 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004198 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004199 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004200 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004201 acquireWakeLock_l();
4202
4203 mMixerStatus = MIXER_IDLE;
4204 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4205 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004206 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004207 checkSilentMode_l();
4208
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004209 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4210 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004211 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004212 sleepTimeShift = 0;
4213 }
4214
4215 continue;
4216 }
4217 }
Eric Laurent81784c32012-11-19 14:55:58 -08004218 // mMixerStatusIgnoringFastTracks is also updated internally
4219 mMixerStatus = prepareTracks_l(&tracksToRemove);
4220
Andy Hungab65b182023-09-06 19:41:47 -07004221 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004222
Vlad Popa7e81cea2023-01-19 16:34:16 +01004223 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004224
Andy Hungf302e812024-01-26 11:55:15 -08004225 // Acquire a local copy of active tracks with lock (release w/o lock).
4226 //
4227 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4228 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4229 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4230 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4231
4232 setHalLatencyMode_l();
4233
4234 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4235 // so this is done before we lock our effect chains.
4236 for (const auto& track : mActiveTracks) {
4237 track->updateTeePatches_l();
4238 }
4239
4240 // signal actual start of output stream when the render position reported by
4241 // the kernel starts moving.
4242 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4243 && (mKernelPositionOnStandby
4244 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4245 mHalStarted = true;
4246 mWaitHalStartCV.notify_all();
4247 }
4248
Eric Laurent81784c32012-11-19 14:55:58 -08004249 // prevent any changes in effect chain list and in each effect chain
4250 // during mixing and effect process as the audio buffers could be deleted
4251 // or modified if an effect is created or deleted
4252 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004253
4254 // Determine which session to pick up haptic data.
4255 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004256 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004257 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004258 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004259 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004260 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004261 if (effectChain != nullptr
4262 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004263 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004264 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004265 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004266 break;
4267 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004268 if (activeHapticSessionId == AUDIO_SESSION_NONE
4269 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004270 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004271 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004272 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004273 }
4274 }
4275 }
Andy Hungc5007f82023-08-29 14:26:09 -07004276 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004277
Eric Laurentbfb1b832013-01-07 09:53:42 -08004278 if (mBytesRemaining == 0) {
4279 mCurrentWriteLength = 0;
4280 if (mMixerStatus == MIXER_TRACKS_READY) {
4281 // threadLoop_mix() sets mCurrentWriteLength
4282 threadLoop_mix();
4283 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4284 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004285 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004286 // must be written to HAL
4287 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004288 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004289 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004290
4291 // Tally underrun frames as we are inserting 0s here.
4292 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004293 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004294 && !track->isStopped()
4295 && !track->isPaused()
4296 && !track->isTerminated()) {
4297 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4298 __func__, track->id(), track->getTrackStateAsString(),
4299 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004300 track->audioTrackServerProxy()->tallyUnderrunFrames(
4301 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004302 }
4303 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004304 }
4305 }
Andy Hung98ef9782014-03-04 14:46:50 -08004306 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004307 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004308 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004309 // or mSinkBuffer (if there are no effects and there is no data already copied to
4310 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004311 //
4312 // This is done pre-effects computation; if effects change to
4313 // support higher precision, this needs to move.
4314 //
4315 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004316 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004317 uint32_t mixerChannelCount = mEffectBufferValid ?
4318 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004319 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004320 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4321 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4322
David Li88ee0902022-06-22 10:01:21 +08004323 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4324 // do these processes after effects are applied.
4325 if (!mEffectBufferValid) {
4326 // mono blend occurs for mixer threads only (not direct or offloaded)
4327 // and is handled here if we're going directly to the sink.
4328 if (requireMonoBlend()) {
4329 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4330 mNormalFrameCount, true /*limit*/);
4331 }
Andy Hung2ddee192015-12-18 17:34:44 -08004332
David Li88ee0902022-06-22 10:01:21 +08004333 if (!hasFastMixer()) {
4334 // Balance must take effect after mono conversion.
4335 // We do it here if there is no FastMixer.
4336 // mBalance detects zero balance within the class for speed
4337 // (not needed here).
4338 mBalance.setBalance(mMasterBalance.load());
4339 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4340 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004341 }
4342
Andy Hung98ef9782014-03-04 14:46:50 -08004343 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004344 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004345
4346 // If we're going directly to the sink and there are haptic channels,
4347 // we should adjust channels as the sample data is partially interleaved
4348 // in this case.
4349 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4350 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4351 mChannelCount + mHapticChannelCount,
4352 audio_bytes_per_sample(format),
4353 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4354 }
Andy Hung98ef9782014-03-04 14:46:50 -08004355 }
4356
Eric Laurentbfb1b832013-01-07 09:53:42 -08004357 mBytesRemaining = mCurrentWriteLength;
4358 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004359 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4360 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4361 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4362 mBytesWritten += mBytesRemaining;
4363 mFramesWritten += framesRemaining;
4364 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004365 mBytesRemaining = 0;
4366 }
Eric Laurent81784c32012-11-19 14:55:58 -08004367
Eric Laurentbfb1b832013-01-07 09:53:42 -08004368 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004369 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004370 for (size_t i = 0; i < effectChains.size(); i ++) {
4371 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004372 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004373 if (activeHapticSessionId != AUDIO_SESSION_NONE
4374 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004375 // Haptic data is active in this case, copy it directly from
4376 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004377 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4378 audio_channel_count_from_out_mask(mMixerChannelMask) :
4379 mChannelCount;
4380 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4381 hapticSessionChannelCount = mChannelCount;
4382 }
4383
jiabin47affe52019-04-04 18:02:07 -07004384 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004385 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004386 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004387 memcpy_by_audio_format(
4388 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004389 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004390 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004391 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004392 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004393 }
Eric Laurent81784c32012-11-19 14:55:58 -08004394 }
4395 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004396 // Process effect chains for offloaded thread even if no audio
4397 // was read from audio track: process only updates effect state
4398 // and thus does have to be synchronized with audio writes but may have
4399 // to be called while waiting for async write callback
4400 if (mType == OFFLOAD) {
4401 for (size_t i = 0; i < effectChains.size(); i ++) {
4402 effectChains[i]->process_l();
4403 }
4404 }
Eric Laurent81784c32012-11-19 14:55:58 -08004405
Andy Hung98ef9782014-03-04 14:46:50 -08004406 // Only if the Effects buffer is enabled and there is data in the
4407 // Effects buffer (buffer valid), we need to
4408 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004409 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004410 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004411 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004412 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004413 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004414 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004415 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004416 }
4417
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004418 if (!hasFastMixer()) {
4419 // Balance must take effect after mono conversion.
4420 // We do it here if there is no FastMixer.
4421 // mBalance detects zero balance within the class for speed (not needed here).
4422 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004423 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004424 }
4425
Eric Laurentb62d0362021-10-26 17:40:18 +02004426 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4427 // mPostSpatializerBuffer if the haptics track is spatialized.
4428 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4429 // For other thread types, the haptics channels are already in mEffectBuffer.
4430 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4431 const size_t srcBufferSize = mNormalFrameCount *
4432 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4433 mEffectBufferFormat);
4434 const size_t dstBufferSize = mNormalFrameCount
4435 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4436
4437 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4438 mEffectBufferFormat,
4439 (uint8_t*)mEffectBuffer + srcBufferSize,
4440 mEffectBufferFormat,
4441 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004442 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004443 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4444 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4445 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4446 // Clamp PCM float values more than this distance from 0 to insulate
4447 // a HAL which doesn't handle NaN correctly.
4448 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4449 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4450 static_cast<const float*>(effectBuffer),
4451 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4452 } else {
4453 memcpy_by_audio_format(mSinkBuffer, mFormat,
4454 effectBuffer, mEffectBufferFormat, framesToCopy);
4455 }
jiabin245cdd92018-12-07 17:55:15 -08004456 // The sample data is partially interleaved when haptic channels exist,
4457 // we need to adjust channels here.
4458 if (mHapticChannelCount > 0) {
4459 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4460 mChannelCount + mHapticChannelCount,
4461 audio_bytes_per_sample(mFormat),
4462 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4463 }
Andy Hung98ef9782014-03-04 14:46:50 -08004464 }
4465
Eric Laurent81784c32012-11-19 14:55:58 -08004466 // enable changes in effect chain
4467 unlockEffectChains(effectChains);
4468
Vlad Popafce10862023-02-03 10:37:07 +01004469 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004470 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004471 metadataUpdate.playbackMetadataUpdate);
4472 }
4473
Eric Laurentbfb1b832013-01-07 09:53:42 -08004474 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004475 // mSleepTimeUs == 0 means we must write to audio hardware
4476 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004477 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004478 // writePeriodNs is updated >= 0 when ret > 0.
4479 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004481 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004482 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004483 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004484 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004485 if (ret < 0) {
4486 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004487 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004488 mBytesWritten += ret;
4489 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004490 const int64_t frames = ret / mFrameSize;
4491 mFramesWritten += frames;
4492
4493 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4494 // process information relating to write time.
4495 if (audio_has_proportional_frames(mFormat)) {
4496 // we are in a continuous mixing cycle
4497 if (mMixerStatus == MIXER_TRACKS_READY &&
4498 loopCount == lastLoopCountWritten + 1) {
4499
4500 const double jitterMs =
4501 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4502 {frames, writePeriodNs},
4503 {0, 0} /* lastTimestamp */, mSampleRate);
4504 const double processMs =
4505 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4506
Andy Hung972bec12023-08-31 16:13:39 -07004507 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004508 mIoJitterMs.add(jitterMs);
4509 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004510
4511 if (mPipeSink.get() != nullptr) {
4512 // Using the Monopipe availableToWrite, we estimate the current
4513 // buffer size.
4514 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4515 const ssize_t
4516 availableToWrite = mPipeSink->availableToWrite();
4517 const size_t pipeFrames = monoPipe->maxFrames();
4518 const size_t
4519 remainingFrames = pipeFrames - max(availableToWrite, 0);
4520 mMonopipePipeDepthStats.add(remainingFrames);
4521 }
Andy Hung446f4df2019-02-21 12:26:41 -08004522 }
4523
4524 // write blocked detection
4525 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004526 if ((mType == MIXER || mType == SPATIALIZER)
4527 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004528 mNumDelayedWrites++;
4529 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4530 ATRACE_NAME("underrun");
4531 ALOGW("write blocked for %lld msecs, "
4532 "%d delayed writes, thread %d",
4533 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4534 mNumDelayedWrites, mId);
4535 lastWarning = lastIoEndNs;
4536 }
4537 }
4538 }
4539 // update timing info.
4540 mLastIoBeginNs = lastIoBeginNs;
4541 mLastIoEndNs = lastIoEndNs;
4542 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004543 }
4544 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4545 (mMixerStatus == MIXER_DRAIN_ALL)) {
4546 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004547 }
Andy Hungd3639922022-04-28 18:00:49 -07004548 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004549
4550 if (mThreadThrottle
4551 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004552 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004553 // Limit MixerThread data processing to no more than twice the
4554 // expected processing rate.
4555 //
4556 // This helps prevent underruns with NuPlayer and other applications
4557 // which may set up buffers that are close to the minimum size, or use
4558 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4559 //
4560 // The throttle smooths out sudden large data drains from the device,
4561 // e.g. when it comes out of standby, which often causes problems with
4562 // (1) mixer threads without a fast mixer (which has its own warm-up)
4563 // (2) minimum buffer sized tracks (even if the track is full,
4564 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004565 //
4566 // Total time spent in last processing cycle equals time spent in
4567 // 1. threadLoop_write, as well as time spent in
4568 // 2. threadLoop_mix (significant for heavy mixing, especially
4569 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004570
Andy Hung446f4df2019-02-21 12:26:41 -08004571 // it's OK if deltaMs is an overestimate.
4572
4573 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004574
Ivan Lozanoea04d392017-11-07 14:37:07 -08004575 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004576 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004577 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004578
Andy Hung08fb1742015-05-31 23:22:10 -07004579 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004580 // notify of throttle start on verbose log
4581 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4582 "mixer(%p) throttle begin:"
4583 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004584 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004585 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004586 // Throttle must be attributed to the previous mixer loop's write time
4587 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004588 // This also ensures proper timing statistics.
4589 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004590 } else {
4591 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4592 if (diff > 0) {
4593 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004594 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004595 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004596 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004597 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004598 outDeviceTypes_l(),
4599 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004600 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004601 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4602 }
Andy Hung08fb1742015-05-31 23:22:10 -07004603 }
4604 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004605 }
Eric Laurent81784c32012-11-19 14:55:58 -08004606
Eric Laurentbfb1b832013-01-07 09:53:42 -08004607 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004608 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004609 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004610 // suspended requires accurate metering of sleep time.
4611 if (isSuspended()) {
4612 // advance by expected sleepTime
4613 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4614 const nsecs_t nowNs = systemTime();
4615
4616 // compute expected next time vs current time.
4617 // (negative deltas are treated as delays).
4618 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4619 if (deltaNs < -kMaxNextBufferDelayNs) {
4620 // Delays longer than the max allowed trigger a reset.
4621 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4622 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4623 timeLoopNextNs = nowNs + deltaNs;
4624 } else if (deltaNs < 0) {
4625 // Delays within the max delay allowed: zero the delta/sleepTime
4626 // to help the system catch up in the next iteration(s)
4627 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4628 deltaNs = 0;
4629 }
4630 // update sleep time (which is >= 0)
4631 mSleepTimeUs = deltaNs / 1000;
4632 }
Eric Laurente93cc032016-05-05 10:15:10 -07004633 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004634 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004635 }
Glenn Kastene7754022014-10-31 12:11:26 -07004636 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004637 }
Eric Laurent81784c32012-11-19 14:55:58 -08004638 }
4639
4640 // Finally let go of removed track(s), without the lock held
4641 // since we can't guarantee the destructors won't acquire that
4642 // same lock. This will also mutate and push a new fast mixer state.
4643 threadLoop_removeTracks(tracksToRemove);
4644 tracksToRemove.clear();
4645
4646 // FIXME I don't understand the need for this here;
4647 // it was in the original code but maybe the
4648 // assignment in saveOutputTracks() makes this unnecessary?
4649 clearOutputTracks();
4650
4651 // Effect chains will be actually deleted here if they were removed from
4652 // mEffectChains list during mixing or effects processing
4653 effectChains.clear();
4654
4655 // FIXME Note that the above .clear() is no longer necessary since effectChains
4656 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004657
4658 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004659 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004660 mThreadloopExecutor.process(); // process any remaining deferred actions.
4661 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004662
Eric Laurentbfb1b832013-01-07 09:53:42 -08004663 threadLoop_exit();
4664
Eric Laurentcf817a22014-08-04 20:36:31 -07004665 if (!mStandby) {
4666 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004667 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004668 }
4669
4670 releaseWakeLock();
4671
4672 ALOGV("Thread %p type %d exiting", this, mType);
4673 return false;
4674}
4675
Andy Hungee58e4a2023-07-07 13:47:37 -07004676void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004677{
Dean Wheatley12473e92021-03-18 23:00:55 +11004678 if (mStandby) {
4679 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4680 return;
4681 } else if (mHwPaused) {
4682 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4683 return;
4684 }
4685
4686 // Gather the framesReleased counters for all active tracks,
4687 // and associate with the sink frames written out. We need
4688 // this to convert the sink timestamp to the track timestamp.
4689 bool kernelLocationUpdate = false;
4690 ExtendedTimestamp timestamp; // use private copy to fetch
4691
4692 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4693 // HAL may be draining some small duration buffered data for fade out.
4694 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4695 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4696 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4697 mSampleRate);
4698
Andy Hungab65b182023-09-06 19:41:47 -07004699 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004700 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4701 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4702 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4703 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4704 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4705 = correctedTimestamp.mFrames;
4706 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4707 = correctedTimestamp.mTimeNs;
4708 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4709 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4710 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4711
4712 // Note: Downstream latency only added if timestamp correction enabled.
4713 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4714 const int64_t newPosition =
4715 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4716 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4717 // prevent retrograde
4718 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4719 newPosition,
4720 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4721 - mSuspendedFrames));
4722 }
4723 }
4724
4725 // We always fetch the timestamp here because often the downstream
4726 // sink will block while writing.
4727
4728 // We keep track of the last valid kernel position in case we are in underrun
4729 // and the normal mixer period is the same as the fast mixer period, or there
4730 // is some error from the HAL.
4731 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4732 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4733 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4734 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4735 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4736
4737 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4738 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4739 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4740 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4741 }
4742
4743 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4744 kernelLocationUpdate = true;
4745 } else {
4746 ALOGVV("getTimestamp error - no valid kernel position");
4747 }
4748
4749 // copy over kernel info
4750 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4751 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4752 + mSuspendedFrames; // add frames discarded when suspended
4753 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4754 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4755 } else {
4756 mTimestampVerifier.error();
4757 }
4758
4759 // mFramesWritten for non-offloaded tracks are contiguous
4760 // even after standby() is called. This is useful for the track frame
4761 // to sink frame mapping.
4762 bool serverLocationUpdate = false;
4763 if (mFramesWritten != mLastFramesWritten) {
4764 serverLocationUpdate = true;
4765 mLastFramesWritten = mFramesWritten;
4766 }
4767 // Only update timestamps if there is a meaningful change.
4768 // Either the kernel timestamp must be valid or we have written something.
4769 if (kernelLocationUpdate || serverLocationUpdate) {
4770 if (serverLocationUpdate) {
4771 // use the time before we called the HAL write - it is a bit more accurate
4772 // to when the server last read data than the current time here.
4773 //
4774 // If we haven't written anything, mLastIoBeginNs will be -1
4775 // and we use systemTime().
4776 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4777 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004778 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004779 }
4780
Andy Hung8d31fd22023-06-26 19:20:57 -07004781 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004782 if (!t->isFastTrack()) {
4783 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004784 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004785 mFramesWritten,
4786 mSampleRate,
4787 mTimestamp);
4788 }
4789 }
4790 }
4791
4792 if (audio_has_proportional_frames(mFormat)) {
4793 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4794 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4795 mLatencyMs.add(latencyMs);
4796 }
4797 }
4798#if 0
4799 // logFormat example
4800 if (z % 100 == 0) {
4801 timespec ts;
4802 clock_gettime(CLOCK_MONOTONIC, &ts);
4803 LOGT("This is an integer %d, this is a float %f, this is my "
4804 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4805 LOGT("A deceptive null-terminated string %\0");
4806 }
4807 ++z;
4808#endif
4809}
4810
Andy Hungc5007f82023-08-29 14:26:09 -07004811// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004812void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004813NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004814{
Andy Hung6c498e92023-12-05 17:28:17 -08004815 if (tracksToRemove.empty()) return;
4816
4817 // Block all incoming TrackHandle requests until we are finished with the release.
4818 setThreadBusy_l(true);
4819
Andy Hungfe726a62018-09-27 15:17:25 -07004820 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004821 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004822 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004823 if (chain != 0) {
4824 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4825 __func__, track->id(), chain.get(), track->sessionId());
4826 chain->decActiveTrackCnt();
4827 }
Andy Hung6c498e92023-12-05 17:28:17 -08004828
Andy Hungfe726a62018-09-27 15:17:25 -07004829 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004830 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004831 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004832 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004833 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004834 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004835 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004836 }
Andy Hung6c498e92023-12-05 17:28:17 -08004837 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004838 }
jiabineb3bda02020-06-30 14:07:03 -07004839 if (mHapticChannelCount > 0 &&
4840 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004841 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004842 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004843 // Unlock due to VibratorService will lock for this call and will
4844 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004845 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004846 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004847
4848 // When the track is stop, set the haptic intensity as MUTE
4849 // for the HapticGenerator effect.
4850 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004851 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004852 }
jiabin245cdd92018-12-07 17:55:15 -08004853 }
Andy Hung6c498e92023-12-05 17:28:17 -08004854
4855 // Under lock, the track is removed from the active tracks list.
4856 //
4857 // Once the track is no longer active, the TrackHandle may directly
4858 // modify it as the threadLoop() is no longer responsible for its maintenance.
4859 // Do not modify the track from threadLoop after the mutex is unlocked
4860 // if it is not active.
4861 mActiveTracks.remove(track);
4862
4863 if (track->isTerminated()) {
4864 // remove from our tracks vector
4865 removeTrack_l(track);
4866 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867 }
Andy Hung6c498e92023-12-05 17:28:17 -08004868
4869 // Allow incoming TrackHandle requests. We still hold the mutex,
4870 // so pending TrackHandle requests will occur after we unlock it.
4871 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004872}
Eric Laurent81784c32012-11-19 14:55:58 -08004873
Andy Hungee58e4a2023-07-07 13:47:37 -07004874status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004875{
4876 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004877 ExtendedTimestamp ets;
4878 status_t status = mNormalSink->getTimestamp(ets);
4879 if (status == NO_ERROR) {
4880 status = ets.getBestTimestamp(&timestamp);
4881 }
4882 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004883 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004884 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004885 collectTimestamps_l();
4886 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4887 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004888 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004889 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4890 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4891 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4892 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4893 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004894 }
4895 return INVALID_OPERATION;
4896}
Eric Laurent1c333e22014-05-20 10:48:17 -07004897
Eric Laurenteab90452019-06-24 15:17:46 -07004898// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4899// still applied by the mixer.
4900// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4901// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4902// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004903status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004904{
4905 status_t result = NO_ERROR;
4906 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4907 if (*volume != mLeftVolFloat) {
4908 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004909 // HAL can return INVALID_OPERATION if operation is not supported.
4910 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004911 "Error when setting output stream volume: %d", result);
4912 if (result == NO_ERROR) {
4913 mLeftVolFloat = *volume;
4914 }
4915 }
4916 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4917 // remove stream volume contribution from software volume.
4918 if (mLeftVolFloat == *volume) {
4919 *volume = 1.0f;
4920 }
4921 }
4922 return result;
4923}
4924
Andy Hungee58e4a2023-07-07 13:47:37 -07004925status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004926 audio_patch_handle_t *handle)
4927{
Andy Hungf60abce2016-08-26 11:37:54 -07004928 status_t status;
4929 if (property_get_bool("af.patch_park", false /* default_value */)) {
4930 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4931 // or if HAL does not properly lock against access.
4932 AutoPark<FastMixer> park(mFastMixer);
4933 status = PlaybackThread::createAudioPatch_l(patch, handle);
4934 } else {
4935 status = PlaybackThread::createAudioPatch_l(patch, handle);
4936 }
Eric Laurentb0463942022-12-20 16:31:10 +01004937
4938 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004939 return status;
4940}
4941
Andy Hungee58e4a2023-07-07 13:47:37 -07004942status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004943 audio_patch_handle_t *handle)
4944{
4945 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004946
4947 // store new device and send to effects
4948 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004949 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004950 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004951 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4952 && !mOutput->audioHwDev->supportsAudioPatches(),
4953 "Enumerated device type(%#x) must not be used "
4954 "as it does not support audio patches",
4955 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004956 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004957 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4958 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004959 }
4960
François Gaffie0c280aa2018-07-25 10:02:15 +02004961 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004962#ifdef ADD_BATTERY_DATA
4963 // when changing the audio output device, call addBatteryData to notify
4964 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004965 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004966 uint32_t params = 0;
4967 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004968 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004969 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004970 }
4971
Eric Laurent054d9d32015-04-24 08:48:48 -07004972 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004973 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004974 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4975 }
4976
4977 if (params != 0) {
4978 addBatteryData(params);
4979 }
4980 }
4981#endif
4982
4983 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004984 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004985 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004986
jiabinc52b1ff2019-10-31 17:20:42 -07004987 // mPatch.num_sinks is not set when the thread is created so that
4988 // the first patch creation triggers an ioConfigChanged callback
4989 bool configChanged = (mPatch.num_sinks == 0) ||
4990 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004991 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004992 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004993 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004994
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004995 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004996 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4997 status = hwDevice->createAudioPatch(patch->num_sources,
4998 patch->sources,
4999 patch->num_sinks,
5000 patch->sinks,
5001 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005002 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005003 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005004 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005005 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005006 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005007
5008 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005009 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005010 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005011 // also dispatch to active AudioTracks for MediaMetrics
5012 for (const auto &track : mActiveTracks) {
5013 track->logEndInterval();
5014 track->logBeginInterval(patchSinksAsString);
5015 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005016
Eric Laurente8726fe2015-06-26 09:39:24 -07005017 if (configChanged) {
5018 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5019 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005020 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005021 mActiveTracks.setHasChanged();
5022
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 return status;
5024}
5025
Andy Hungee58e4a2023-07-07 13:47:37 -07005026status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005027{
Andy Hungf60abce2016-08-26 11:37:54 -07005028 status_t status;
5029 if (property_get_bool("af.patch_park", false /* default_value */)) {
5030 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5031 // or if HAL does not properly lock against access.
5032 AutoPark<FastMixer> park(mFastMixer);
5033 status = PlaybackThread::releaseAudioPatch_l(handle);
5034 } else {
5035 status = PlaybackThread::releaseAudioPatch_l(handle);
5036 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005037 return status;
5038}
5039
Andy Hungee58e4a2023-07-07 13:47:37 -07005040status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005041{
5042 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005043
jiabinc52b1ff2019-10-31 17:20:42 -07005044 mPatch = audio_patch{};
5045 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005046
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005047 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005048 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5049 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005050 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005051 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005052 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005053 // Force meteadata update after a route change
5054 mActiveTracks.setHasChanged();
5055
Eric Laurent1c333e22014-05-20 10:48:17 -07005056 return status;
5057}
5058
Andy Hungee58e4a2023-07-07 13:47:37 -07005059void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005060{
Andy Hung972bec12023-08-31 16:13:39 -07005061 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005062 mTracks.add(track);
5063}
5064
Andy Hungee58e4a2023-07-07 13:47:37 -07005065void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005066{
Andy Hung972bec12023-08-31 16:13:39 -07005067 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005068 destroyTrack_l(track);
5069}
5070
Andy Hungee58e4a2023-07-07 13:47:37 -07005071void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005072{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005073 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005074 config->role = AUDIO_PORT_ROLE_SOURCE;
5075 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5076 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005077 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5078 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5079 config->flags.output = mOutput->flags;
5080 }
Eric Laurent83b88082014-06-20 18:31:16 -07005081}
5082
Eric Laurent81784c32012-11-19 14:55:58 -08005083// ----------------------------------------------------------------------------
5084
Andy Hungee58e4a2023-07-07 13:47:37 -07005085/* static */
5086sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005087 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005088 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005089 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005090}
5091
Andy Hung583043b2023-07-17 17:05:00 -07005092MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005093 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005094 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005095 // mAudioMixer below
5096 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005097 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005098 mFastMixerFutex(0),
5099 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005100 // mOutputSink below
5101 // mPipeSink below
5102 // mNormalSink below
5103{
jiabinc52b1ff2019-10-31 17:20:42 -07005104 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005105 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005106 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005107 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5108 mNormalFrameCount);
5109 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5110
Andy Hungfbfc3952015-01-15 13:33:51 -08005111 if (type == DUPLICATING) {
5112 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5113 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5114 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005115 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5116 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005117 return;
5118 }
Eric Laurent81784c32012-11-19 14:55:58 -08005119 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005120 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005121 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005122 const NBAIO_Format offers[1] = {Format_from_SR_C(
5123 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005124#if !LOG_NDEBUG
5125 ssize_t index =
5126#else
5127 (void)
5128#endif
5129 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005130 ALOG_ASSERT(index == 0);
5131
5132 // initialize fast mixer depending on configuration
5133 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005134 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005135 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005136 } else {
5137 switch (kUseFastMixer) {
5138 case FastMixer_Never:
5139 initFastMixer = false;
5140 break;
5141 case FastMixer_Always:
5142 initFastMixer = true;
5143 break;
5144 case FastMixer_Static:
5145 case FastMixer_Dynamic:
5146 initFastMixer = mFrameCount < mNormalFrameCount;
5147 break;
5148 }
5149 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5150 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5151 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005152 }
5153 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005154 audio_format_t fastMixerFormat;
5155 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5156 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5157 } else {
5158 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5159 }
5160 if (mFormat != fastMixerFormat) {
5161 // change our Sink format to accept our intermediate precision
5162 mFormat = fastMixerFormat;
5163 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005164 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005165 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5166 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5167 }
Eric Laurent81784c32012-11-19 14:55:58 -08005168
5169 // create a MonoPipe to connect our submix to FastMixer
5170 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005171
Andy Hung1258c1a2014-05-23 21:22:17 -07005172 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005173 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005174 format.mFormat = fastMixerFormat;
5175 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5176
Eric Laurent81784c32012-11-19 14:55:58 -08005177 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5178 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5179 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5180 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005181 const NBAIO_Format offersFast[1] = {format};
5182 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005183#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005184 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005185#else
5186 (void)
5187#endif
Andy Hung920f6572022-10-06 12:09:49 -07005188 monoPipe->negotiate(offersFast, std::size(offersFast),
5189 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005190 ALOG_ASSERT(index == 0);
5191 monoPipe->setAvgFrames((mScreenState & 1) ?
5192 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5193 mPipeSink = monoPipe;
5194
Eric Laurent81784c32012-11-19 14:55:58 -08005195 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005196 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005197 FastMixerStateQueue *sq = mFastMixer->sq();
5198#ifdef STATE_QUEUE_DUMP
5199 sq->setObserverDump(&mStateQueueObserverDump);
5200 sq->setMutatorDump(&mStateQueueMutatorDump);
5201#endif
5202 FastMixerState *state = sq->begin();
5203 FastTrack *fastTrack = &state->mFastTracks[0];
5204 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5205 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5206 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005207 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5208 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5209 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005210 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005211 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005212 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005213 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005214 fastTrack->mGeneration++;
5215 state->mFastTracksGen++;
5216 state->mTrackMask = 1;
5217 // fast mixer will use the HAL output sink
5218 state->mOutputSink = mOutputSink.get();
5219 state->mOutputSinkGen++;
5220 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005221 // specify sink channel mask when haptic channel mask present as it can not
5222 // be calculated directly from channel count
5223 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005224 ? AUDIO_CHANNEL_NONE
5225 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005226 state->mCommand = FastMixerState::COLD_IDLE;
5227 // already done in constructor initialization list
5228 //mFastMixerFutex = 0;
5229 state->mColdFutexAddr = &mFastMixerFutex;
5230 state->mColdGen++;
5231 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005232 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005233 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005234 sq->end();
5235 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5236
Eric Tan0513b5d2018-09-17 10:32:48 -07005237 NBLog::thread_info_t info;
5238 info.id = mId;
5239 info.type = NBLog::FASTMIXER;
5240 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5241
Eric Laurent81784c32012-11-19 14:55:58 -08005242 // start the fast mixer
5243 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5244 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005245 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005246 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005247
5248#ifdef AUDIO_WATCHDOG
5249 // create and start the watchdog
5250 mAudioWatchdog = new AudioWatchdog();
5251 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5252 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5253 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005254 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005255#endif
Andy Hung8946a282018-04-19 20:04:56 -07005256 } else {
5257#ifdef TEE_SINK
5258 // Only use the MixerThread tee if there is no FastMixer.
5259 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5260 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5261#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005262 }
5263
5264 switch (kUseFastMixer) {
5265 case FastMixer_Never:
5266 case FastMixer_Dynamic:
5267 mNormalSink = mOutputSink;
5268 break;
5269 case FastMixer_Always:
5270 mNormalSink = mPipeSink;
5271 break;
5272 case FastMixer_Static:
5273 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5274 break;
5275 }
Andy Hung922617c2024-06-25 17:07:58 -07005276 // setMasterBalance needs to be called after the FastMixer
5277 // (if any) is set up, in order to deliver the balance settings to it.
5278 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005279}
5280
Andy Hungee58e4a2023-07-07 13:47:37 -07005281MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005282{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005283 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005284 FastMixerStateQueue *sq = mFastMixer->sq();
5285 FastMixerState *state = sq->begin();
5286 if (state->mCommand == FastMixerState::COLD_IDLE) {
5287 int32_t old = android_atomic_inc(&mFastMixerFutex);
5288 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005289 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005290 }
5291 }
5292 state->mCommand = FastMixerState::EXIT;
5293 sq->end();
5294 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5295 mFastMixer->join();
5296 // Though the fast mixer thread has exited, it's state queue is still valid.
5297 // We'll use that extract the final state which contains one remaining fast track
5298 // corresponding to our sub-mix.
5299 state = sq->begin();
5300 ALOG_ASSERT(state->mTrackMask == 1);
5301 FastTrack *fastTrack = &state->mFastTracks[0];
5302 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5303 delete fastTrack->mBufferProvider;
5304 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005305 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005306#ifdef AUDIO_WATCHDOG
5307 if (mAudioWatchdog != 0) {
5308 mAudioWatchdog->requestExit();
5309 mAudioWatchdog->requestExitAndWait();
5310 mAudioWatchdog.clear();
5311 }
5312#endif
5313 }
Andy Hung583043b2023-07-17 17:05:00 -07005314 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005315 delete mAudioMixer;
5316}
5317
Andy Hungee58e4a2023-07-07 13:47:37 -07005318void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005319 PlaybackThread::onFirstRef();
5320
Andy Hung972bec12023-08-31 16:13:39 -07005321 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005322 if (mOutput != nullptr && mOutput->stream != nullptr) {
5323 status_t status = mOutput->stream->setLatencyModeCallback(this);
5324 if (status != INVALID_OPERATION) {
5325 updateHalSupportedLatencyModes_l();
5326 }
5327 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5328 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5329 mBluetoothLatencyModesEnabled.store(
5330 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5331 }
5332}
Eric Laurent81784c32012-11-19 14:55:58 -08005333
Andy Hungee58e4a2023-07-07 13:47:37 -07005334uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005335{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005336 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005337 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5338 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5339 }
5340 return latency;
5341}
5342
Andy Hungee58e4a2023-07-07 13:47:37 -07005343ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005344{
5345 // FIXME we should only do one push per cycle; confirm this is true
5346 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005347 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005348 FastMixerStateQueue *sq = mFastMixer->sq();
5349 FastMixerState *state = sq->begin();
5350 if (state->mCommand != FastMixerState::MIX_WRITE &&
5351 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5352 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005353
5354 // FIXME workaround for first HAL write being CPU bound on some devices
5355 ATRACE_BEGIN("write");
5356 mOutput->write((char *)mSinkBuffer, 0);
5357 ATRACE_END();
5358
Eric Laurent81784c32012-11-19 14:55:58 -08005359 int32_t old = android_atomic_inc(&mFastMixerFutex);
5360 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005361 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005362 }
5363#ifdef AUDIO_WATCHDOG
5364 if (mAudioWatchdog != 0) {
5365 mAudioWatchdog->resume();
5366 }
5367#endif
5368 }
5369 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005370#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005371 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005372 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005373#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005374 sq->end();
5375 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5376 if (kUseFastMixer == FastMixer_Dynamic) {
5377 mNormalSink = mPipeSink;
5378 }
5379 } else {
5380 sq->end(false /*didModify*/);
5381 }
5382 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005383 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005384}
5385
Andy Hungee58e4a2023-07-07 13:47:37 -07005386void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005387{
5388 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005389 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005390 FastMixerStateQueue *sq = mFastMixer->sq();
5391 FastMixerState *state = sq->begin();
5392 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005393 // Report any frames trapped in the Monopipe
5394 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5395 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5396 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5397 "monoPipeWritten:%lld monoPipeLeft:%lld",
5398 (long long)mFramesWritten, (long long)mSuspendedFrames,
5399 (long long)mPipeSink->framesWritten(), pipeFrames);
5400 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5401
Eric Laurent81784c32012-11-19 14:55:58 -08005402 state->mCommand = FastMixerState::COLD_IDLE;
5403 state->mColdFutexAddr = &mFastMixerFutex;
5404 state->mColdGen++;
5405 mFastMixerFutex = 0;
5406 sq->end();
5407 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5408 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5409 if (kUseFastMixer == FastMixer_Dynamic) {
5410 mNormalSink = mOutputSink;
5411 }
5412#ifdef AUDIO_WATCHDOG
5413 if (mAudioWatchdog != 0) {
5414 mAudioWatchdog->pause();
5415 }
5416#endif
5417 } else {
5418 sq->end(false /*didModify*/);
5419 }
5420 }
5421 PlaybackThread::threadLoop_standby();
5422}
5423
Andy Hungee58e4a2023-07-07 13:47:37 -07005424bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005425{
5426 return false;
5427}
5428
Andy Hungee58e4a2023-07-07 13:47:37 -07005429bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005430{
5431 return !mStandby;
5432}
5433
Andy Hungee58e4a2023-07-07 13:47:37 -07005434bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005435{
Andy Hung972bec12023-08-31 16:13:39 -07005436 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 return waitingAsyncCallback_l();
5438}
5439
Eric Laurent81784c32012-11-19 14:55:58 -08005440// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005441void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005442{
Andy Hung8d672e02023-09-15 18:19:28 -07005443 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5444 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005445 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005447 // discard any pending drain or write ack by incrementing sequence
5448 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5449 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005450 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005451 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5452 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005453 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005454 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005455 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005456}
5457
Andy Hungee58e4a2023-07-07 13:47:37 -07005458void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005459{
5460 ALOGV("signal playback thread");
5461 broadcast_l();
5462}
5463
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005464void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005465{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005466 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005467 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5468 invalidateTracks((audio_stream_type_t)i);
5469 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005470 if (isHardError) {
5471 mAfThreadCallback->onHardError(allTrackPortIds);
5472 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005473}
5474
Andy Hungee58e4a2023-07-07 13:47:37 -07005475void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005476{
Eric Laurent81784c32012-11-19 14:55:58 -08005477 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005478 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005479 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005480 // increase sleep time progressively when application underrun condition clears.
5481 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5482 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5483 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005484 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005485 sleepTimeShift--;
5486 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005487 mSleepTimeUs = 0;
5488 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005489 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005490
Eric Laurent81784c32012-11-19 14:55:58 -08005491}
5492
Andy Hungee58e4a2023-07-07 13:47:37 -07005493void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005494{
5495 // If no tracks are ready, sleep once for the duration of an output
5496 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005497 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005498 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005499 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5500 // Using the Monopipe availableToWrite, we estimate the
5501 // sleep time to retry for more data (before we underrun).
5502 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5503 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5504 const size_t pipeFrames = monoPipe->maxFrames();
5505 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5506 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5507 const size_t framesDelay = std::min(
5508 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5509 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5510 pipeFrames, framesLeft, framesDelay);
5511 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5512 } else {
5513 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5514 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5515 mSleepTimeUs = kMinThreadSleepTimeUs;
5516 }
5517 // reduce sleep time in case of consecutive application underruns to avoid
5518 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5519 // duration we would end up writing less data than needed by the audio HAL if
5520 // the condition persists.
5521 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5522 sleepTimeShift++;
5523 }
Eric Laurent81784c32012-11-19 14:55:58 -08005524 }
5525 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005526 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005527 }
5528 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005529 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5530 // before effects processing or output.
5531 if (mMixerBufferValid) {
5532 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005533 if (mType == SPATIALIZER) {
5534 memset(mSinkBuffer, 0, mSinkBufferSize);
5535 }
Andy Hung98ef9782014-03-04 14:46:50 -08005536 } else {
5537 memset(mSinkBuffer, 0, mSinkBufferSize);
5538 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005539 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005540 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5541 "anticipated start");
5542 }
5543 // TODO add standby time extension fct of effect tail
5544}
5545
Andy Hungc5007f82023-08-29 14:26:09 -07005546// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005547PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005548 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005549{
Andy Hungc0691382018-09-12 18:01:57 -07005550 // clean up deleted track ids in AudioMixer before allocating new tracks
5551 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5552 // for each trackId, destroy it in the AudioMixer
5553 if (mAudioMixer->exists(trackId)) {
5554 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005555 }
5556 });
Andy Hungc0691382018-09-12 18:01:57 -07005557 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005558
5559 mixer_state mixerStatus = MIXER_IDLE;
5560 // find out which tracks need to be processed
5561 size_t count = mActiveTracks.size();
5562 size_t mixedTracks = 0;
5563 size_t tracksWithEffect = 0;
5564 // counts only _active_ fast tracks
5565 size_t fastTracks = 0;
5566 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5567
5568 float masterVolume = mMasterVolume;
5569 bool masterMute = mMasterMute;
5570
5571 if (masterMute) {
5572 masterVolume = 0;
5573 }
5574 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005575 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005576 if (chain != 0) {
5577 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005578 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005579 masterVolume = (float)((v + (1 << 23)) >> 24);
5580 chain.clear();
5581 }
5582
5583 // prepare a new state to push
5584 FastMixerStateQueue *sq = NULL;
5585 FastMixerState *state = NULL;
5586 bool didModify = false;
5587 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005588 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005589 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005590 sq = mFastMixer->sq();
5591 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005592 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005593 }
5594
Andy Hung69aed5f2014-02-25 17:24:40 -08005595 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005596 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005597
Andy Hungbd3b2b02018-05-21 10:53:11 -07005598 // DeferredOperations handles statistics after setting mixerStatus.
5599 class DeferredOperations {
5600 public:
Andy Hungea840382020-05-05 21:50:17 -07005601 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5602 : mMixerStatus(mixerStatus)
5603 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005604
5605 // when leaving scope, tally frames properly.
5606 ~DeferredOperations() {
5607 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5608 // because that is when the underrun occurs.
5609 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005610 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005611 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005612 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005613 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005614 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005615 }
5616 }
Andy Hungea840382020-05-05 21:50:17 -07005617 // send the max underrun frames for this mixer period
5618 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005619 }
5620
5621 // tallyUnderrunFrames() is called to update the track counters
5622 // with the number of underrun frames for a particular mixer period.
5623 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005624 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005625 mUnderrunFrames.emplace_back(track, underrunFrames);
5626 }
5627
5628 private:
5629 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005630 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005631 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005632 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005633 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005634
jiabin245cdd92018-12-07 17:55:15 -08005635 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005636 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005637 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005638
5639 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005640 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005641
5642 // process fast tracks
5643 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005644 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5645 "%s(%d): FastTrack(%d) present without FastMixer",
5646 __func__, id(), track->id());
5647
jiabin245cdd92018-12-07 17:55:15 -08005648 if (track->getHapticPlaybackEnabled()) {
5649 noFastHapticTrack = false;
5650 }
Eric Laurent81784c32012-11-19 14:55:58 -08005651
5652 // It's theoretically possible (though unlikely) for a fast track to be created
5653 // and then removed within the same normal mix cycle. This is not a problem, as
5654 // the track never becomes active so it's fast mixer slot is never touched.
5655 // The converse, of removing an (active) track and then creating a new track
5656 // at the identical fast mixer slot within the same normal mix cycle,
5657 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005658 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005659 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005660 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5661 FastTrack *fastTrack = &state->mFastTracks[j];
5662
5663 // Determine whether the track is currently in underrun condition,
5664 // and whether it had a recent underrun.
5665 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5666 FastTrackUnderruns underruns = ftDump->mUnderruns;
5667 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005668 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005669 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005670 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005671 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005672 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005673 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005674 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005675 // don't count underruns that occur while stopping or pausing
5676 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005677 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005678 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5679 recentUnderruns > 0) {
5680 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005681 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005682 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005683 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005684 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005685
5686 // This is similar to the state machine for normal tracks,
5687 // with a few modifications for fast tracks.
5688 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005689 switch (track->state()) {
5690 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005691 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005692 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005693 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005694 }
5695 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005696 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005697 // ramp down is not yet implemented
5698 track->setPaused();
5699 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005700 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005701 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005702 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005703 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005704 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005705 if (recentFull > 0 || recentPartial > 0) {
5706 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005707 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005708 }
5709 if (recentUnderruns == 0) {
5710 // no recent underruns: stay active
5711 break;
5712 }
5713 // there has recently been an underrun of some kind
5714 if (track->sharedBuffer() == 0) {
5715 // were any of the recent underruns "empty" (no frames available)?
5716 if (recentEmpty == 0) {
5717 // no, then ignore the partial underruns as they are allowed indefinitely
5718 break;
5719 }
5720 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005721 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005722 break;
5723 }
5724 // indicate to client process that the track was disabled because of underrun;
5725 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005726 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005727 // remove from active list, but state remains ACTIVE [confusing but true]
5728 isActive = false;
5729 break;
5730 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005731 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005732 case IAfTrackBase::STOPPING_2:
5733 case IAfTrackBase::PAUSED:
5734 case IAfTrackBase::STOPPED:
5735 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005736 // Check for presentation complete if track is inactive
5737 // We have consumed all the buffers of this track.
5738 // This would be incomplete if we auto-paused on underrun
5739 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005740 uint32_t latency = 0;
5741 status_t result = mOutput->stream->getLatency(&latency);
5742 ALOGE_IF(result != OK,
5743 "Error when retrieving output stream latency: %d", result);
5744 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005745 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005746 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5747 // track stays in active list until presentation is complete
5748 break;
5749 }
5750 }
5751 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005752 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005753 }
5754 if (track->isStopped()) {
5755 // Can't reset directly, as fast mixer is still polling this track
5756 // track->reset();
5757 // So instead mark this track as needing to be reset after push with ack
5758 resetMask |= 1 << i;
5759 }
5760 isActive = false;
5761 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005762 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005763 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005764 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005765 }
5766
5767 if (isActive) {
5768 // was it previously inactive?
5769 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005770 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5771 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005772 fastTrack->mBufferProvider = eabp;
5773 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005774 fastTrack->mChannelMask = track->channelMask();
5775 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005776 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005777 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005778 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005779 fastTrack->mGeneration++;
5780 state->mTrackMask |= 1 << j;
5781 didModify = true;
5782 // no acknowledgement required for newly active tracks
5783 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005784 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005785 float volume;
Eric Laurent277a37e2024-07-29 18:37:52 +00005786 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5787 volume = 0.f;
Eric Laurenteab90452019-06-24 15:17:46 -07005788 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +00005789 volume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005790 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005791
Eric Laurenteab90452019-06-24 15:17:46 -07005792 handleVoipVolume_l(&volume);
5793
Eric Laurent81784c32012-11-19 14:55:58 -08005794 // cache the combined master volume and stream type volume for fast mixer; this
5795 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005796 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005797 proxy->framesReleased()).first;
5798 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005799 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005800 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005801 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5802 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent277a37e2024-07-29 18:37:52 +00005803
5804 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5805 /*muteState=*/{masterVolume == 0.f,
5806 mStreamTypes[track->streamType()].volume == 0.f,
5807 mStreamTypes[track->streamType()].mute,
5808 track->isPlaybackRestricted(),
5809 vlf == 0.f && vrf == 0.f,
5810 vh == 0.f});
5811
Vlad Popae2f5aef2022-07-25 16:00:20 +02005812 vlf *= volume;
5813 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005814
jiabin220eea12024-05-17 17:55:20 +00005815 if (track->getInternalMute()) {
5816 vlf = 0.f;
5817 vrf = 0.f;
5818 }
5819
jiabin76d94692022-12-15 21:51:21 +00005820 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005821 ++fastTracks;
5822 } else {
5823 // was it previously active?
5824 if (state->mTrackMask & (1 << j)) {
5825 fastTrack->mBufferProvider = NULL;
5826 fastTrack->mGeneration++;
5827 state->mTrackMask &= ~(1 << j);
5828 didModify = true;
5829 // If any fast tracks were removed, we must wait for acknowledgement
5830 // because we're about to decrement the last sp<> on those tracks.
5831 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5832 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005833 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5834 // AudioTrack may start (which may not be with a start() but with a write()
5835 // after underrun) and immediately paused or released. In that case the
5836 // FastTrack state hasn't had time to update.
5837 // TODO Remove the ALOGW when this theory is confirmed.
5838 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005839 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005840 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005841 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005842 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005843 }
5844 tracksToRemove->add(track);
5845 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005846 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005847 }
jiabin245cdd92018-12-07 17:55:15 -08005848 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5849 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5850 didModify = true;
5851 }
Eric Laurent81784c32012-11-19 14:55:58 -08005852 continue;
5853 }
5854
5855 { // local variable scope to avoid goto warning
5856
5857 audio_track_cblk_t* cblk = track->cblk();
5858
5859 // The first time a track is added we wait
5860 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005861 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005862
5863 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005864 // use the trackId as the AudioMixer name.
5865 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005866 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005867 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005868 track->channelMask(),
5869 track->format(),
5870 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005871 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005872 ALOGW("%s(): AudioMixer cannot create track(%d)"
5873 " mask %#x, format %#x, sessionId %d",
5874 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005875 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005876 tracksToRemove->add(track);
5877 track->invalidate(); // consider it dead.
5878 continue;
5879 }
5880 }
5881
Eric Laurent81784c32012-11-19 14:55:58 -08005882 // make sure that we have enough frames to mix one full buffer.
5883 // enforce this condition only once to enable draining the buffer in case the client
5884 // app does not call stop() and relies on underrun to stop:
5885 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5886 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005887 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005888 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5889 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005890
5891 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005892 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005893 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5894 // add frames already consumed but not yet released by the resampler
5895 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005896 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005897
Eric Laurent81784c32012-11-19 14:55:58 -08005898 uint32_t minFrames = 1;
5899 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5900 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005901 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005902 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005903
5904 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005905 if (ATRACE_ENABLED()) {
5906 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005907 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005908 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005909 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005910 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005911 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005912 !track->isPaused() && !track->isTerminated())
5913 {
Andy Hungc0691382018-09-12 18:01:57 -07005914 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005915
5916 mixedTracks++;
5917
Shunkai Yaof4847652024-01-12 00:25:20 +00005918 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005919 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005920 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005921 if (track->mainBuffer() != mSinkBuffer &&
5922 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005923 if (mEffectBufferEnabled) {
5924 mEffectBufferValid = true; // Later can set directly.
5925 }
Eric Laurent81784c32012-11-19 14:55:58 -08005926 chain = getEffectChain_l(track->sessionId());
5927 // Delegate volume control to effect in track effect chain if needed
5928 if (chain != 0) {
5929 tracksWithEffect++;
5930 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005931 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005932 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005933 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005934 }
5935 }
5936
5937
5938 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005939 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005940 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005941 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5942 if (track->state() == IAfTrackBase::RESUMING) {
5943 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005944 // If a new track is paused immediately after start, do not ramp on resume.
5945 if (cblk->mServer != 0) {
5946 param = AudioMixer::RAMP_VOLUME;
5947 }
Eric Laurent81784c32012-11-19 14:55:58 -08005948 }
Andy Hungc0691382018-09-12 18:01:57 -07005949 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005950 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005951 // FIXME should not make a decision based on mServer
5952 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005953 // If the track is stopped before the first frame was mixed,
5954 // do not apply ramp
5955 param = AudioMixer::RAMP_VOLUME;
5956 }
5957
5958 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005959 uint32_t vl, vr; // in U8.24 integer format
5960 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005961 // read original volumes with volume control
Eric Laurent277a37e2024-07-29 18:37:52 +00005962 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005963 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005964 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005965 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005966 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent277a37e2024-07-29 18:37:52 +00005967
5968 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5969 v = 0;
Eric Laurenteab90452019-06-24 15:17:46 -07005970 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005971
Eric Laurenteab90452019-06-24 15:17:46 -07005972 handleVoipVolume_l(&v);
5973
5974 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005975 vl = vr = 0;
5976 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005977 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005978 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005979 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005980 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5981 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005982 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005983 if (vlf > GAIN_FLOAT_UNITY) {
5984 ALOGV("Track left volume out of range: %.3g", vlf);
5985 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005986 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005987 if (vrf > GAIN_FLOAT_UNITY) {
5988 ALOGV("Track right volume out of range: %.3g", vrf);
5989 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005990 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005991
5992 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5993 /*muteState=*/{masterVolume == 0.f,
5994 mStreamTypes[track->streamType()].volume == 0.f,
5995 mStreamTypes[track->streamType()].mute,
5996 track->isPlaybackRestricted(),
5997 vlf == 0.f && vrf == 0.f,
5998 vh == 0.f});
5999
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006000 // now apply the master volume and stream type volume and shaper volume
6001 vlf *= v * vh;
6002 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006003 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006004 // then derive vl and vr as U8.24 versions for the effect chain
6005 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6006 vl = (uint32_t) (scaleto8_24 * vlf);
6007 vr = (uint32_t) (scaleto8_24 * vrf);
6008 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006009 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006010 // send level comes from shared memory and so may be corrupt
6011 if (sendLevel > MAX_GAIN_INT) {
6012 ALOGV("Track send level out of range: %04X", sendLevel);
6013 sendLevel = MAX_GAIN_INT;
6014 }
Andy Hung6be49402014-05-30 10:42:03 -07006015 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6016 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006017 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006018
jiabin220eea12024-05-17 17:55:20 +00006019 if (track->getInternalMute()) {
6020 vrf = 0.f;
6021 vlf = 0.f;
6022 }
6023
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006024 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006025
Eric Laurent81784c32012-11-19 14:55:58 -08006026 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006027 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006028 // Do not ramp volume if volume is controlled by effect
6029 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006030 // Update remaining floating point volume levels
6031 vlf = (float)vl / (1 << 24);
6032 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006033 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006034 } else {
6035 // force no volume ramp when volume controller was just disabled or removed
6036 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006037 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006038 param = AudioMixer::VOLUME;
6039 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006040 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006041 }
6042
Eric Laurent81784c32012-11-19 14:55:58 -08006043 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006044 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006045 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006046
Andy Hungc0691382018-09-12 18:01:57 -07006047 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6048 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6049 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006050 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006051 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006052 AudioMixer::TRACK,
6053 AudioMixer::FORMAT, (void *)track->format());
6054 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006055 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006056 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006057 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006058
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006059 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006060 mAudioMixer->setParameter(
6061 trackId,
6062 AudioMixer::TRACK,
6063 AudioMixer::MIXER_CHANNEL_MASK,
6064 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6065 } else {
6066 mAudioMixer->setParameter(
6067 trackId,
6068 AudioMixer::TRACK,
6069 AudioMixer::MIXER_CHANNEL_MASK,
6070 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6071 }
6072
Glenn Kastene3aa6592012-12-04 12:22:46 -08006073 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006074 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006075 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006076 if (reqSampleRate == 0) {
6077 reqSampleRate = mSampleRate;
6078 } else if (reqSampleRate > maxSampleRate) {
6079 reqSampleRate = maxSampleRate;
6080 }
Eric Laurent81784c32012-11-19 14:55:58 -08006081 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006082 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006083 AudioMixer::RESAMPLE,
6084 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006085 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006086
Andy Hung8edb8dc2015-03-26 19:13:55 -07006087 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006088 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006089 AudioMixer::TIMESTRETCH,
6090 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006091 // cast away constness for this generic API.
6092 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006093
Andy Hung69aed5f2014-02-25 17:24:40 -08006094 /*
6095 * Select the appropriate output buffer for the track.
6096 *
Andy Hung98ef9782014-03-04 14:46:50 -08006097 * Tracks with effects go into their own effects chain buffer
6098 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006099 *
6100 * Other tracks can use mMixerBuffer for higher precision
6101 * channel accumulation. If this buffer is enabled
6102 * (mMixerBufferEnabled true), then selected tracks will accumulate
6103 * into it.
6104 *
6105 */
6106 if (mMixerBufferEnabled
6107 && (track->mainBuffer() == mSinkBuffer
6108 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006109 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006110 mAudioMixer->setParameter(
6111 trackId,
6112 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006113 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006114 mAudioMixer->setParameter(
6115 trackId,
6116 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006117 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006118 } else {
6119 mAudioMixer->setParameter(
6120 trackId,
6121 AudioMixer::TRACK,
6122 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6123 mAudioMixer->setParameter(
6124 trackId,
6125 AudioMixer::TRACK,
6126 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6127 // TODO: override track->mainBuffer()?
6128 mMixerBufferValid = true;
6129 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006130 } else {
6131 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006132 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006133 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006134 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006135 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006136 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006137 AudioMixer::TRACK,
6138 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6139 }
Eric Laurent81784c32012-11-19 14:55:58 -08006140 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006141 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006142 AudioMixer::TRACK,
6143 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006144 mAudioMixer->setParameter(
6145 trackId,
6146 AudioMixer::TRACK,
6147 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006148 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006149 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006150 trackId,
6151 AudioMixer::TRACK,
6152 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006153 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006154 mAudioMixer->setParameter(
6155 trackId,
6156 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006157 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006158
6159 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006160 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006161
6162 // If one track is ready, set the mixer ready if:
6163 // - the mixer was not ready during previous round OR
6164 // - no other track is not ready
6165 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6166 mixerStatus != MIXER_TRACKS_ENABLED) {
6167 mixerStatus = MIXER_TRACKS_READY;
6168 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006169
6170 // Enable the next few lines to instrument a test for underrun log handling.
6171 // TODO: Remove when we have a better way of testing the underrun log.
6172#if 0
6173 static int i;
6174 if ((++i & 0xf) == 0) {
6175 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6176 }
6177#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006178 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006179 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006180 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006181 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6182 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006183 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006184 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006185 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006186
Eric Laurent81784c32012-11-19 14:55:58 -08006187 // clear effect chain input buffer if an active track underruns to avoid sending
6188 // previous audio buffer again to effects
6189 chain = getEffectChain_l(track->sessionId());
6190 if (chain != 0) {
6191 chain->clearInputBuffer();
6192 }
6193
Andy Hungc0691382018-09-12 18:01:57 -07006194 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006195 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6196 track->isStopped() || track->isPaused()) {
6197 // We have consumed all the buffers of this track.
6198 // Remove it from the list of active tracks.
6199 // TODO: use actual buffer filling status instead of latency when available from
6200 // audio HAL
6201 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006202 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006203 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6204 if (track->isStopped()) {
6205 track->reset();
6206 }
6207 tracksToRemove->add(track);
6208 }
6209 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006210 // No buffers for this track. Give it a few chances to
6211 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006212 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006213 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6214 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006215 tracksToRemove->add(track);
6216 // indicate to client process that the track was disabled because of underrun;
6217 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006218 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006219 // If one track is not ready, mark the mixer also not ready if:
6220 // - the mixer was ready during previous round OR
6221 // - no other track is ready
6222 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6223 mixerStatus != MIXER_TRACKS_READY) {
6224 mixerStatus = MIXER_TRACKS_ENABLED;
6225 }
6226 }
Andy Hungc0691382018-09-12 18:01:57 -07006227 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006228 }
6229
6230 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006231
6232 }
6233
jiabin245cdd92018-12-07 17:55:15 -08006234 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6235 // When there is no fast track playing haptic and FastMixer exists,
6236 // enabling the first FastTrack, which provides mixed data from normal
6237 // tracks, to play haptic data.
6238 FastTrack *fastTrack = &state->mFastTracks[0];
6239 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6240 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6241 didModify = true;
6242 }
6243 }
6244
Eric Laurent81784c32012-11-19 14:55:58 -08006245 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006246 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006247 if (didModify) {
6248 state->mFastTracksGen++;
6249 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6250 if (kUseFastMixer == FastMixer_Dynamic &&
6251 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6252 state->mCommand = FastMixerState::COLD_IDLE;
6253 state->mColdFutexAddr = &mFastMixerFutex;
6254 state->mColdGen++;
6255 mFastMixerFutex = 0;
6256 if (kUseFastMixer == FastMixer_Dynamic) {
6257 mNormalSink = mOutputSink;
6258 }
6259 // If we go into cold idle, need to wait for acknowledgement
6260 // so that fast mixer stops doing I/O.
6261 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6262 pauseAudioWatchdog = true;
6263 }
Eric Laurent81784c32012-11-19 14:55:58 -08006264 }
6265 if (sq != NULL) {
6266 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006267 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6268 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6269 // when bringing the output sink into standby.)
6270 //
6271 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6272 //
6273 // This occurs with BT suspend when we idle the FastMixer with
6274 // active tracks, which may be added or removed.
6275 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006276 }
6277#ifdef AUDIO_WATCHDOG
6278 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6279 mAudioWatchdog->pause();
6280 }
6281#endif
6282
6283 // Now perform the deferred reset on fast tracks that have stopped
6284 while (resetMask != 0) {
6285 size_t i = __builtin_ctz(resetMask);
6286 ALOG_ASSERT(i < count);
6287 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006288 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006289 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6290 track->reset();
6291 }
6292
Andy Hung80d03d22018-04-10 10:32:11 -07006293 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6294 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6295 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6296 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6297 // See also the implementation of destroyTrack_l().
6298 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006299 const int trackId = track->id();
6300 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6301 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006302 }
6303 }
6304
Eric Laurent81784c32012-11-19 14:55:58 -08006305 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006306 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006307
Eric Laurentb3f315a2021-07-13 15:09:05 +02006308 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6309 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006310 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006311 }
6312
6313 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006314 // as long as there are effects we should clear the effects buffer, to avoid
6315 // passing a non-clean buffer to the effect chain
6316 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006317 if (mType == SPATIALIZER) {
6318 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6319 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006320 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006321 // sink or mix buffer must be cleared if all tracks are connected to an
6322 // effect chain as in this case the mixer will not write to the sink or mix buffer
6323 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006324 // always clear sink buffer for spatializer output as the output of the spatializer
6325 // effect will be accumulated into it
6326 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6327 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006328 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006329 if (mMixerBufferValid) {
6330 memset(mMixerBuffer, 0, mMixerBufferSize);
6331 // TODO: In testing, mSinkBuffer below need not be cleared because
6332 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6333 // after mixing.
6334 //
6335 // To enforce this guarantee:
6336 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6337 // (mixedTracks == 0 && fastTracks > 0))
6338 // must imply MIXER_TRACKS_READY.
6339 // Later, we may clear buffers regardless, and skip much of this logic.
6340 }
Andy Hung98ef9782014-03-04 14:46:50 -08006341 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006342 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006343 }
6344
6345 // if any fast tracks, then status is ready
6346 mMixerStatusIgnoringFastTracks = mixerStatus;
6347 if (fastTracks > 0) {
6348 mixerStatus = MIXER_TRACKS_READY;
6349 }
6350 return mixerStatus;
6351}
6352
Andy Hungc5007f82023-08-29 14:26:09 -07006353// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006354uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006355{
6356 uint32_t trackCount = 0;
6357 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006358 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006359 trackCount++;
6360 }
6361 }
6362 return trackCount;
6363}
6364
Andy Hungee58e4a2023-07-07 13:47:37 -07006365bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006366{
Brian Lindahl65e90012022-07-27 18:01:07 +02006367 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6368 // could falsely detect that the frame position has stalled due to underrun because we haven't
6369 // given the Audio HAL enough time to update.
6370 const nsecs_t nowNs = systemTime();
6371 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6372 return mLatchedValue;
6373 }
6374 mPreviousNs = nowNs;
6375 mLatchedValue = false;
6376 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006377 uint64_t position = 0;
6378 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006379 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006380 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006381 if (position != mPreviousPosition) {
6382 mPreviousPosition = position;
6383 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006384 }
6385 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006386 return mLatchedValue;
6387}
6388
Andy Hungee58e4a2023-07-07 13:47:37 -07006389void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006390{
6391 mLatchedValue = true;
6392 mPreviousPosition = 0;
6393 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006394}
6395
Andy Hungc5007f82023-08-29 14:26:09 -07006396// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006397bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006398 audio_channel_mask_t channelMask, audio_format_t format,
6399 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006400{
Andy Hung1bc088a2018-02-09 15:57:31 -08006401 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6402 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006403 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006404 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006405 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006406 ALOGW("%s: invalid format: %#x", __func__, format);
6407 return false;
6408 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006409 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006410 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6411 return false;
6412 }
6413 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006414}
6415
Andy Hungc5007f82023-08-29 14:26:09 -07006416// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006417bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006418 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006419{
Eric Laurent81784c32012-11-19 14:55:58 -08006420 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006421 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006422
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006423 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006424
Eric Laurent10351942014-05-08 18:49:52 -07006425 AudioParameter param = AudioParameter(keyValuePair);
6426 int value;
6427 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6428 reconfig = true;
6429 }
6430 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006431 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006432 status = BAD_VALUE;
6433 } else {
6434 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006435 reconfig = true;
6436 }
Eric Laurent10351942014-05-08 18:49:52 -07006437 }
6438 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006439 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006440 status = BAD_VALUE;
6441 } else {
6442 // no need to save value, since it's constant
6443 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006444 }
Eric Laurent10351942014-05-08 18:49:52 -07006445 }
6446 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6447 // do not accept frame count changes if tracks are open as the track buffer
6448 // size depends on frame count and correct behavior would not be guaranteed
6449 // if frame count is changed after track creation
6450 if (!mTracks.isEmpty()) {
6451 status = INVALID_OPERATION;
6452 } else {
6453 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006454 }
Eric Laurent10351942014-05-08 18:49:52 -07006455 }
6456 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006457 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006458 }
Eric Laurent81784c32012-11-19 14:55:58 -08006459
Eric Laurent10351942014-05-08 18:49:52 -07006460 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006461 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006462 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006463 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6464 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006465 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006466 mThreadMetrics.logEndInterval();
6467 mThreadSnapshot.onEnd();
6468 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006469 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006470 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006471 }
Eric Laurent10351942014-05-08 18:49:52 -07006472 if (status == NO_ERROR && reconfig) {
6473 readOutputParameters_l();
6474 delete mAudioMixer;
6475 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006476 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006477 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006478 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006479 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006480 track->channelMask(),
6481 track->format(),
6482 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006483 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006484 "%s(): AudioMixer cannot create track(%d)"
6485 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006486 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006487 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006488 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006489 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006490 }
Eric Laurent81784c32012-11-19 14:55:58 -08006491 }
6492
Dean Wheatley68918102021-03-19 22:09:19 +11006493 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006494}
6495
6496
Andy Hungee58e4a2023-07-07 13:47:37 -07006497void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006498{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006499 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006500 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006501 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006502 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006503 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6504 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6505 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006506 if (hasFastMixer()) {
6507 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6508
6509 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6510 // while we are dumping it. It may be inconsistent, but it won't mutate!
6511 // This is a large object so we place it on the heap.
6512 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006513 const std::unique_ptr<FastMixerDumpState> copy =
6514 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006515 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006516
6517#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006518 // Similar for state queue
6519 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6520 observerCopy.dump(fd);
6521 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6522 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006523#endif
6524
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006525#ifdef AUDIO_WATCHDOG
6526 if (mAudioWatchdog != 0) {
6527 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6528 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6529 wdCopy.dump(fd);
6530 }
6531#endif
6532
6533 } else {
6534 dprintf(fd, " No FastMixer\n");
6535 }
Eric Laurent90cea102023-05-15 15:08:27 +02006536
6537 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6538 mBluetoothLatencyModesEnabled ? "" : "not ");
6539 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6540 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6541 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006542}
6543
Andy Hungee58e4a2023-07-07 13:47:37 -07006544uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006545{
6546 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6547}
6548
Andy Hungee58e4a2023-07-07 13:47:37 -07006549uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006550{
6551 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6552}
6553
Andy Hungee58e4a2023-07-07 13:47:37 -07006554void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006555{
6556 PlaybackThread::cacheParameters_l();
6557
6558 // FIXME: Relaxed timing because of a certain device that can't meet latency
6559 // Should be reduced to 2x after the vendor fixes the driver issue
6560 // increase threshold again due to low power audio mode. The way this warning
6561 // threshold is calculated and its usefulness should be reconsidered anyway.
6562 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6563}
6564
Andy Hungee58e4a2023-07-07 13:47:37 -07006565void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006566 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006567}
6568
Andy Hungee58e4a2023-07-07 13:47:37 -07006569void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006570 // Only handle latency mode if:
6571 // - mBluetoothLatencyModesEnabled is true
6572 // - the HAL supports latency modes
6573 // - the selected device is Bluetooth LE or A2DP
6574 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6575 return;
6576 }
6577 if (mOutDeviceTypeAddrs.size() != 1
6578 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6579 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6580 return;
6581 }
6582
6583 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6584 if (mSupportedLatencyModes.size() == 1) {
6585 // If the HAL only support one latency mode currently, confirm the choice
6586 latencyMode = mSupportedLatencyModes[0];
6587 } else if (mSupportedLatencyModes.size() > 1) {
6588 // Request low latency if:
6589 // - At least one active track is either:
6590 // - a fast track with gaming usage or
6591 // - a track with acessibility usage
6592 for (const auto& track : mActiveTracks) {
6593 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6594 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6595 latencyMode = AUDIO_LATENCY_MODE_LOW;
6596 break;
6597 }
6598 }
6599 }
6600
6601 if (latencyMode != mSetLatencyMode) {
6602 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6603 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6604 __func__, mId, toString(latencyMode).c_str(), status);
6605 if (status == NO_ERROR) {
6606 mSetLatencyMode = latencyMode;
6607 }
6608 }
6609}
6610
Andy Hungee58e4a2023-07-07 13:47:37 -07006611void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006612
6613 if (mOutput == nullptr || mOutput->stream == nullptr) {
6614 return;
6615 }
6616 std::vector<audio_latency_mode_t> latencyModes;
6617 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6618 if (status != NO_ERROR) {
6619 latencyModes.clear();
6620 }
6621 if (latencyModes != mSupportedLatencyModes) {
6622 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6623 __func__, mId, status, toString(latencyModes).c_str());
6624 mSupportedLatencyModes.swap(latencyModes);
6625 sendHalLatencyModesChangedEvent_l();
6626 }
6627}
6628
Andy Hungee58e4a2023-07-07 13:47:37 -07006629status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006630 std::vector<audio_latency_mode_t>* modes) {
6631 if (modes == nullptr) {
6632 return BAD_VALUE;
6633 }
Andy Hung972bec12023-08-31 16:13:39 -07006634 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006635 *modes = mSupportedLatencyModes;
6636 return NO_ERROR;
6637}
6638
Andy Hungee58e4a2023-07-07 13:47:37 -07006639void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006640 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006641 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006642 if (modes != mSupportedLatencyModes) {
6643 ALOGD("%s: thread(%d) supported latency modes: %s",
6644 __func__, mId, toString(modes).c_str());
6645 mSupportedLatencyModes.swap(modes);
6646 sendHalLatencyModesChangedEvent_l();
6647 }
6648}
6649
Andy Hungee58e4a2023-07-07 13:47:37 -07006650status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006651 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6652 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6653 return INVALID_OPERATION;
6654 }
6655 mBluetoothLatencyModesEnabled.store(enabled);
6656 return NO_ERROR;
6657}
6658
Eric Laurent81784c32012-11-19 14:55:58 -08006659// ----------------------------------------------------------------------------
6660
Andy Hungee58e4a2023-07-07 13:47:37 -07006661/* static */
6662sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006663 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006664 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6665 const audio_offload_info_t& offloadInfo) {
6666 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006667 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006668}
6669
Andy Hung583043b2023-07-17 17:05:00 -07006670DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006671 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6672 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006673 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006674 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006675{
Andy Hung583043b2023-07-17 17:05:00 -07006676 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006677}
6678
Andy Hungee58e4a2023-07-07 13:47:37 -07006679DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006680{
6681}
6682
Andy Hungee58e4a2023-07-07 13:47:37 -07006683void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006684{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006685 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006686 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6687 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6688}
6689
Andy Hungee58e4a2023-07-07 13:47:37 -07006690void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006691{
Andy Hung972bec12023-08-31 16:13:39 -07006692 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006693 if (mMasterBalance != balance) {
6694 mMasterBalance.store(balance);
6695 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6696 broadcast_l();
6697 }
6698}
6699
Andy Hungee58e4a2023-07-07 13:47:37 -07006700void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006701{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006702 float left, right;
6703
Andy Hung333ab962019-05-28 20:23:35 -07006704 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006705 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006706
Andy Hung398ffa22022-12-13 19:19:53 -08006707 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6708 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6709
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006710 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6711 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006712
6713 const int64_t volumeShaperFrames =
6714 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6715 const auto [shaperVolume, shaperActive] =
6716 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006717 mVolumeShaperActive = shaperActive;
6718
Vlad Popae2f5aef2022-07-25 16:00:20 +02006719 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6720 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6721 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6722
6723 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6724
Eric Laurent277a37e2024-07-29 18:37:52 +00006725 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6726 left = right = 0;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006727 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +00006728 float typeVolume = mStreamTypes[track->streamType()].volume;
6729 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006730
Eric Laurent277a37e2024-07-29 18:37:52 +00006731 if (left > GAIN_FLOAT_UNITY) {
6732 left = GAIN_FLOAT_UNITY;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006733 }
Eric Laurent277a37e2024-07-29 18:37:52 +00006734 if (right > GAIN_FLOAT_UNITY) {
6735 right = GAIN_FLOAT_UNITY;
6736 }
6737 left *= v;
6738 right *= v;
6739 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6740 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6741 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6742 right *= mMasterBalanceRight;
6743 }
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006744 }
Vlad Popae8d99472022-06-30 16:02:48 +02006745
Eric Laurent277a37e2024-07-29 18:37:52 +00006746 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6747 /*muteState=*/{mMasterMute,
6748 mStreamTypes[track->streamType()].volume == 0.f,
6749 mStreamTypes[track->streamType()].mute,
6750 track->isPlaybackRestricted(),
6751 clientVolumeMute,
6752 shaperVolume == 0.f});
6753
Eric Laurentbfb1b832013-01-07 09:53:42 -08006754 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006755 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006756 if (left != mLeftVolFloat || right != mRightVolFloat) {
6757 mLeftVolFloat = left;
6758 mRightVolFloat = right;
6759
Eric Laurentbfb1b832013-01-07 09:53:42 -08006760 // Delegate volume control to effect in track effect chain if needed
6761 // only one effect chain can be present on DirectOutputThread, so if
6762 // there is one, the track is connected to it
6763 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006764 // if effect chain exists, volume is handled by it.
6765 // Convert volumes from float to 8.24
6766 uint32_t vl = (uint32_t)(left * (1 << 24));
6767 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006768 // Direct/Offload effect chains set output volume in setVolume().
6769 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006770 } else {
6771 // otherwise we directly set the volume.
6772 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006773 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006774 }
6775 }
6776}
6777
Andy Hungee58e4a2023-07-07 13:47:37 -07006778void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006779{
Andy Hung8d31fd22023-06-26 19:20:57 -07006780 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6781 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006782
Eric Laurent0f0631e2015-07-06 18:01:25 -07006783 if (previousTrack != 0 && latestTrack != 0) {
6784 if (mType == DIRECT) {
6785 if (previousTrack.get() != latestTrack.get()) {
6786 mFlushPending = true;
6787 }
6788 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006789 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6790 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006791 mFlushPending = true;
6792 }
6793 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006794 } else if (previousTrack == 0) {
6795 // there could be an old track added back during track transition for direct
6796 // output, so always issues flush to flush data of the previous track if it
6797 // was already destroyed with HAL paused, then flush can resume the playback
6798 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006799 }
6800 PlaybackThread::onAddNewTrack_l();
6801}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006802
Andy Hungee58e4a2023-07-07 13:47:37 -07006803PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006804 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006805)
6806{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006807 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006808 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006809 bool doHwPause = false;
6810 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006811
6812 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006813 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006814 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006815 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006816 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006817 continue;
6818 }
6819
Andy Hung8d31fd22023-06-26 19:20:57 -07006820 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006821#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006822 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006823#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006824 // Only consider last track started for volume and mixer state control.
6825 // In theory an older track could underrun and restart after the new one starts
6826 // but as we only care about the transition phase between two tracks on a
6827 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006828 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006829 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006830
Kuowei Li23666472021-01-20 10:23:25 +08006831 if (track->isPausePending()) {
6832 track->pauseAck();
6833 // It is possible a track might have been flushed or stopped.
6834 // Other operations such as flush pending might occur on the next prepare.
6835 if (track->isPausing()) {
6836 track->setPaused();
6837 }
6838 // Always perform pause, as an immediate flush will change
6839 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006840 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006841 doHwPause = true;
6842 mHwPaused = true;
6843 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006844 } else if (track->isFlushPending()) {
6845 track->flushAck();
6846 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006847 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006848 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006849 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006850 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006851 if (last) {
6852 mLeftVolFloat = mRightVolFloat = -1.0;
6853 if (mHwPaused) {
6854 doHwResume = true;
6855 mHwPaused = false;
6856 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006857 }
6858 }
6859
Eric Laurent81784c32012-11-19 14:55:58 -08006860 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006861 // for all its buffers to be filled before processing it.
6862 // Allow draining the buffer in case the client
6863 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006864 // hence the test on (track->retryCount() > 1).
6865 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006866 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6867 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006868 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006869
6870 // target retry count that we will use is based on the time we wait for retries.
6871 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6872 // the retry threshold is when we accept any size for PCM data. This is slightly
6873 // smaller than the retry count so we can push small bits of data without a glitch.
6874 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006875 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006876 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006877 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006878 minFrames = mNormalFrameCount;
6879 } else {
6880 minFrames = 1;
6881 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006882
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006883 const size_t framesReady = track->framesReady();
6884 const int trackId = track->id();
6885 if (ATRACE_ENABLED()) {
6886 std::string traceName("nRdy");
6887 traceName += std::to_string(trackId);
6888 ATRACE_INT(traceName.c_str(), framesReady);
6889 }
6890 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006891 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006892 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006893 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006894
Andy Hung8d31fd22023-06-26 19:20:57 -07006895 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6896 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006897 if (last) {
6898 // make sure processVolume_l() will apply new volume even if 0
6899 mLeftVolFloat = mRightVolFloat = -1.0;
6900 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006901 if (!mHwSupportsPause) {
6902 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006903 }
6904 }
6905
6906 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006907 processVolume_l(track, last);
6908 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006909 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006910 if (previousTrack != 0) {
6911 if (track != previousTrack.get()) {
6912 // Flush any data still being written from last track
6913 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006914 // Invalidate previous track to force a seek when resuming.
6915 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006916 }
6917 }
6918 mPreviousTrack = track;
6919
Eric Laurentd595b7c2013-04-03 17:27:56 -07006920 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006921 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006922 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006923 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006924 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006925 doHwResume = true;
6926 mHwPaused = false;
6927 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006928 }
Eric Laurent81784c32012-11-19 14:55:58 -08006929 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006930 // clear effect chain input buffer if the last active track started underruns
6931 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006932 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006933 mEffectChains[0]->clearInputBuffer();
6934 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006935 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006936 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006937 if (last && mHwPaused) {
6938 doHwResume = true;
6939 mHwPaused = false;
6940 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006941 }
6942 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6943 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006944 // We have consumed all the buffers of this track.
6945 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006946 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006947 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006948 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006949 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006950 if (presComplete) {
6951 mOutput->presentationComplete();
6952 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006953 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006954 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006955 }
Eric Laurent81784c32012-11-19 14:55:58 -08006956 if (track->isStopped()) {
6957 track->reset();
6958 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006959 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006960 }
6961 } else {
6962 // No buffers for this track. Give it a few chances to
6963 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006964 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006965 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006966 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006967 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006968 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006969 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006970 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00006971 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
6972 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08006973 tracksToRemove->add(track);
6974 // indicate to client process that the track was disabled because of
6975 // underrun; it will then automatically call start() when data is available
6976 track->disable();
6977 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6978 // unlike mixerthread, HAL can be paused for direct output
6979 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6980 "minFrames = %u, mFormat = %#x",
6981 framesReady, minFrames, mFormat);
6982 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6983 doHwPause = true;
6984 mHwPaused = true;
6985 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006986 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006987 } else if (last) {
6988 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006989 }
6990 }
6991 }
6992 }
6993
Eric Laurentd1f69b02014-12-15 14:33:13 -08006994 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006995 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006996 for (size_t i = 0; i < mTracks.size(); i++) {
6997 if (mTracks[i]->isFlushPending()) {
6998 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006999 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007000 }
7001 }
7002 }
7003
7004 // make sure the pause/flush/resume sequence is executed in the right order.
7005 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7006 // before flush and then resume HW. This can happen in case of pause/flush/resume
7007 // if resume is received before pause is executed.
7008 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007009 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007010 status_t result = mOutput->stream->pause();
7011 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007012 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007013 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007014 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007015 flushHw_l();
7016 }
7017 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007018 status_t result = mOutput->stream->resume();
7019 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007020 }
Eric Laurent81784c32012-11-19 14:55:58 -08007021 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007022 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007023
7024 return mixerStatus;
7025}
7026
Andy Hungee58e4a2023-07-07 13:47:37 -07007027void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
Eric Laurent81784c32012-11-19 14:55:58 -08007029 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007030 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007031 // output audio to hardware
7032 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007033 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007034 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007035 status_t status = mActiveTrack->getNextBuffer(&buffer);
7036 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007037 // no need to pad with 0 for compressed audio
7038 if (audio_has_proportional_frames(mFormat)) {
7039 memset(curBuf, 0, frameCount * mFrameSize);
7040 }
Eric Laurent81784c32012-11-19 14:55:58 -08007041 break;
7042 }
7043 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7044 frameCount -= buffer.frameCount;
7045 curBuf += buffer.frameCount * mFrameSize;
7046 mActiveTrack->releaseBuffer(&buffer);
7047 }
Andy Hung2098f272014-02-27 14:00:06 -08007048 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007049 mSleepTimeUs = 0;
7050 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007051 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007052}
7053
Andy Hungee58e4a2023-07-07 13:47:37 -07007054void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007055{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007056 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007057 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007058 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007059 return;
7060 }
Andy Hung85ba3332021-04-27 17:40:26 -07007061 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7062 mSleepTimeUs = mActiveSleepTimeUs;
7063 } else {
7064 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007065 }
Andy Hung85ba3332021-04-27 17:40:26 -07007066 // Note: In S or later, we do not write zeroes for
7067 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007068}
7069
Andy Hungee58e4a2023-07-07 13:47:37 -07007070void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007071{
7072 {
Andy Hung972bec12023-08-31 16:13:39 -07007073 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007074 for (size_t i = 0; i < mTracks.size(); i++) {
7075 if (mTracks[i]->isFlushPending()) {
7076 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007077 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007078 }
7079 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007080 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007081 flushHw_l();
7082 }
7083 }
7084 PlaybackThread::threadLoop_exit();
7085}
7086
7087// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007088bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007089{
7090 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007091 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007092 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007093
Eric Laurent022a5132024-04-12 17:02:51 +00007094 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007095 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007096 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007097 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007098 const auto& mainTrack = mTracks[mTracks.size() - 1];
7099
7100 trackPaused = mainTrack->isPaused();
7101 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7102 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007103 }
7104
Eric Laurent022a5132024-04-12 17:02:51 +00007105 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007106}
7107
Andy Hungc5007f82023-08-29 14:26:09 -07007108// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007109bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007110 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007111{
7112 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007113 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007114
Eric Laurent10351942014-05-08 18:49:52 -07007115 AudioParameter param = AudioParameter(keyValuePair);
7116 int value;
7117 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007118 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007119 }
Eric Laurent10351942014-05-08 18:49:52 -07007120 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7121 // do not accept frame count changes if tracks are open as the track buffer
7122 // size depends on frame count and correct behavior would not be garantied
7123 // if frame count is changed after track creation
7124 if (!mTracks.isEmpty()) {
7125 status = INVALID_OPERATION;
7126 } else {
7127 reconfig = true;
7128 }
7129 }
7130 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007131 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007132 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007133 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007134 if (!mStandby) {
7135 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007136 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007137 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007138 }
Eric Laurent10351942014-05-08 18:49:52 -07007139 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007140 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007141 }
7142 if (status == NO_ERROR && reconfig) {
7143 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007144 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007145 }
7146 }
7147
Dean Wheatley68918102021-03-19 22:09:19 +11007148 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007149}
7150
Andy Hungee58e4a2023-07-07 13:47:37 -07007151uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007152{
7153 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007154 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007155 time = PlaybackThread::activeSleepTimeUs();
7156 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007157 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007158 }
7159 return time;
7160}
7161
Andy Hungee58e4a2023-07-07 13:47:37 -07007162uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007163{
7164 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007165 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007166 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7167 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007168 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007169 }
7170 return time;
7171}
7172
Andy Hungee58e4a2023-07-07 13:47:37 -07007173uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007174{
7175 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007176 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007177 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7178 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007179 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007180 }
7181 return time;
7182}
7183
Andy Hungee58e4a2023-07-07 13:47:37 -07007184void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007185{
7186 PlaybackThread::cacheParameters_l();
7187
7188 // use shorter standby delay as on normal output to release
7189 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007190 // no delay on outputs with HW A/V sync
7191 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007192 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007193 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007194 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007195 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007196 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007197 }
Eric Laurent81784c32012-11-19 14:55:58 -08007198}
7199
Andy Hungee58e4a2023-07-07 13:47:37 -07007200void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007201{
ziyangch8f194f12021-12-01 13:48:04 -08007202 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007203 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007204 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007205 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007206 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007207 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007208 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007209}
7210
Andy Hungee58e4a2023-07-07 13:47:37 -07007211int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007212 // If a VolumeShaper is active, we must wake up periodically to update volume.
7213 const int64_t NS_PER_MS = 1000000;
7214 return mVolumeShaperActive ?
7215 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7216}
7217
Eric Laurent81784c32012-11-19 14:55:58 -08007218// ----------------------------------------------------------------------------
7219
Andy Hungee58e4a2023-07-07 13:47:37 -07007220AsyncCallbackThread::AsyncCallbackThread(
7221 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007222 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007223 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007224 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007225 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007226 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007227{
7228}
7229
Andy Hungee58e4a2023-07-07 13:47:37 -07007230void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007231{
7232 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7233}
7234
Andy Hungee58e4a2023-07-07 13:47:37 -07007235bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007236{
7237 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007238 uint32_t writeAckSequence;
7239 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007240 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007241
7242 {
Andy Hungc5007f82023-08-29 14:26:09 -07007243 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007244 while (!((mWriteAckSequence & 1) ||
7245 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007246 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007247 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007248 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007249 }
7250
Eric Laurentbfb1b832013-01-07 09:53:42 -08007251 if (exitPending()) {
7252 break;
7253 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007254 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7255 mWriteAckSequence, mDrainSequence);
7256 writeAckSequence = mWriteAckSequence;
7257 mWriteAckSequence &= ~1;
7258 drainSequence = mDrainSequence;
7259 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007260 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007261 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007262 }
7263 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007264 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007265 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007266 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007267 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007268 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007269 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007270 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007271 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007272 if (asyncError != ASYNC_ERROR_NONE) {
7273 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007274 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007275 }
7276 }
7277 }
7278 return false;
7279}
7280
Andy Hungee58e4a2023-07-07 13:47:37 -07007281void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007282{
7283 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007284 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007285 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007286 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007287}
7288
Andy Hungee58e4a2023-07-07 13:47:37 -07007289void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007290{
Andy Hung972bec12023-08-31 16:13:39 -07007291 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007292 // bit 0 is cleared
7293 mWriteAckSequence = sequence << 1;
7294}
7295
Andy Hungee58e4a2023-07-07 13:47:37 -07007296void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007297{
Andy Hung972bec12023-08-31 16:13:39 -07007298 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007299 // ignore unexpected callbacks
7300 if (mWriteAckSequence & 2) {
7301 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007302 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007303 }
7304}
7305
Andy Hungee58e4a2023-07-07 13:47:37 -07007306void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007307{
Andy Hung972bec12023-08-31 16:13:39 -07007308 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007309 // bit 0 is cleared
7310 mDrainSequence = sequence << 1;
7311}
7312
Andy Hungee58e4a2023-07-07 13:47:37 -07007313void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007314{
Andy Hung972bec12023-08-31 16:13:39 -07007315 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007316 // ignore unexpected callbacks
7317 if (mDrainSequence & 2) {
7318 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007319 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007320 }
7321}
7322
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007323void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007324{
Andy Hung972bec12023-08-31 16:13:39 -07007325 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007326 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007327 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007328}
7329
Eric Laurentbfb1b832013-01-07 09:53:42 -08007330
7331// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007332
7333/* static */
7334sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007335 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007336 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7337 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007338 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007339}
7340
Andy Hung583043b2023-07-17 17:05:00 -07007341OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007342 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7343 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007344 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007345 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007346{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007347 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007348 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007349 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007350}
7351
Andy Hungee58e4a2023-07-07 13:47:37 -07007352void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007353{
7354 if (mFlushPending || mHwPaused) {
7355 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007356 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007357 flushHw_l();
7358 } else {
7359 mMixerStatus = MIXER_DRAIN_ALL;
7360 threadLoop_drain();
7361 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007362 if (mUseAsyncWrite) {
7363 ALOG_ASSERT(mCallbackThread != 0);
7364 mCallbackThread->exit();
7365 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007366 PlaybackThread::threadLoop_exit();
7367}
7368
Andy Hungee58e4a2023-07-07 13:47:37 -07007369PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007370 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007371)
7372{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007373 size_t count = mActiveTracks.size();
7374
7375 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007376 bool doHwPause = false;
7377 bool doHwResume = false;
7378
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007379 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007380
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007382 for (const sp<IAfTrack>& t : mActiveTracks) {
7383 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007384#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007386#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007387 // Only consider last track started for volume and mixer state control.
7388 // In theory an older track could underrun and restart after the new one starts
7389 // but as we only care about the transition phase between two tracks on a
7390 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007391 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007392 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007393
Haynes Mathew George7844f672014-01-15 12:32:55 -08007394 if (track->isInvalid()) {
7395 ALOGW("An invalidated track shouldn't be in active list");
7396 tracksToRemove->add(track);
7397 continue;
7398 }
7399
Andy Hung8d31fd22023-06-26 19:20:57 -07007400 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007401 ALOGW("An idle track shouldn't be in active list");
7402 continue;
7403 }
7404
Kuowei Li23666472021-01-20 10:23:25 +08007405 if (track->isPausePending()) {
7406 track->pauseAck();
7407 // It is possible a track might have been flushed or stopped.
7408 // Other operations such as flush pending might occur on the next prepare.
7409 if (track->isPausing()) {
7410 track->setPaused();
7411 }
7412 // Always perform pause if last, as an immediate flush will change
7413 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007414 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007415 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007416 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007417 mHwPaused = true;
7418 }
7419 // If we were part way through writing the mixbuffer to
7420 // the HAL we must save this until we resume
7421 // BUG - this will be wrong if a different track is made active,
7422 // in that case we want to discard the pending data in the
7423 // mixbuffer and tell the client to present it again when the
7424 // track is resumed
7425 mPausedWriteLength = mCurrentWriteLength;
7426 mPausedBytesRemaining = mBytesRemaining;
7427 mBytesRemaining = 0; // stop writing
7428 }
7429 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007430 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007431 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007432 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007433 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007434 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007435 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007436 track->flushAck();
7437 if (last) {
7438 mFlushPending = true;
7439 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007440 } else if (track->isResumePending()){
7441 track->resumeAck();
7442 if (last) {
7443 if (mPausedBytesRemaining) {
7444 // Need to continue write that was interrupted
7445 mCurrentWriteLength = mPausedWriteLength;
7446 mBytesRemaining = mPausedBytesRemaining;
7447 mPausedBytesRemaining = 0;
7448 }
7449 if (mHwPaused) {
7450 doHwResume = true;
7451 mHwPaused = false;
7452 // threadLoop_mix() will handle the case that we need to
7453 // resume an interrupted write
7454 }
7455 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007456 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007457
Eric Laurent3df841a2016-07-15 15:15:40 -07007458 mLeftVolFloat = mRightVolFloat = -1.0;
7459
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007460 // Do not handle new data in this iteration even if track->framesReady()
7461 mixerStatus = MIXER_TRACKS_ENABLED;
7462 }
7463 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007464 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007465 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007466 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7467 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007468 if (last) {
7469 // make sure processVolume_l() will apply new volume even if 0
7470 mLeftVolFloat = mRightVolFloat = -1.0;
7471 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007472 }
7473
7474 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007475 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007476 if (previousTrack != 0) {
7477 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007478 // Flush any data still being written from last track
7479 mBytesRemaining = 0;
7480 if (mPausedBytesRemaining) {
7481 // Last track was paused so we also need to flush saved
7482 // mixbuffer state and invalidate track so that it will
7483 // re-submit that unwritten data when it is next resumed
7484 mPausedBytesRemaining = 0;
7485 // Invalidate is a bit drastic - would be more efficient
7486 // to have a flag to tell client that some of the
7487 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007488 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007489 }
7490 // flush data already sent to the DSP if changing audio session as audio
7491 // comes from a different source. Also invalidate previous track to force a
7492 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007493 if (previousTrack->sessionId() != track->sessionId()) {
7494 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007495 }
7496 }
7497 }
7498 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007499 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007500 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007501 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007502 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007503 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007504 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007505 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007506 mixerStatus = MIXER_TRACKS_READY;
7507 }
7508 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007509 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007510 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007511 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007512 // Hardware buffer can hold a large amount of audio so we must
7513 // wait for all current track's data to drain before we say
7514 // that the track is stopped.
7515 if (mBytesRemaining == 0) {
7516 // Only start draining when all data in mixbuffer
7517 // has been written
7518 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007519 track->setState(IAfTrackBase::STOPPING_2);
7520 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007521 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7522 if (last && !mStandby) {
7523 // do not modify drain sequence if we are already draining. This happens
7524 // when resuming from pause after drain.
7525 if ((mDrainSequence & 1) == 0) {
7526 mSleepTimeUs = 0;
7527 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7528 mixerStatus = MIXER_DRAIN_TRACK;
7529 mDrainSequence += 2;
7530 }
7531 if (mHwPaused) {
7532 // It is possible to move from PAUSED to STOPPING_1 without
7533 // a resume so we must ensure hardware is running
7534 doHwResume = true;
7535 mHwPaused = false;
7536 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007537 }
7538 }
Eric Laurente93cc032016-05-05 10:15:10 -07007539 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007540 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007541 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007542 }
7543 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007544 // Drain has completed or we are in standby, signal presentation complete
7545 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007546 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007547 mOutput->presentationComplete();
7548 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007549 track->reset();
7550 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007551 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007552 if (!mUseAsyncWrite) {
7553 // If we don't get explicit drain notification we must
7554 // register discontinuity regardless of whether this is
7555 // the previous (!last) or the upcoming (last) track
7556 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007557 mTimestampVerifier.discontinuity(
7558 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007559 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007560 }
7561 } else {
7562 // No buffers for this track. Give it a few chances to
7563 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007564 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007565 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007566 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007567 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007568 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007569 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007570 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7571 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007572 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007573 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007574 // it will then automatically call start() when data is available
7575 track->disable();
7576 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007577 } else if (last){
7578 mixerStatus = MIXER_TRACKS_ENABLED;
7579 }
7580 }
7581 }
7582 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007583 if (track->isReady()) { // check ready to prevent premature start.
7584 processVolume_l(track, last);
7585 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007586 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007587
Eric Laurentea0fade2013-10-04 16:23:48 -07007588 // make sure the pause/flush/resume sequence is executed in the right order.
7589 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7590 // before flush and then resume HW. This can happen in case of pause/flush/resume
7591 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007592 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007593 status_t result = mOutput->stream->pause();
7594 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007595 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007596 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007597 if (mFlushPending) {
7598 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007599 }
Eric Laurentfd477972013-10-25 18:10:40 -07007600 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007601 status_t result = mOutput->stream->resume();
7602 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007603 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007604
Eric Laurentbfb1b832013-01-07 09:53:42 -08007605 // remove all the tracks that need to be...
7606 removeTracks_l(*tracksToRemove);
7607
7608 return mixerStatus;
7609}
7610
Eric Laurentbfb1b832013-01-07 09:53:42 -08007611// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007612bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007613{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007614 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7615 mWriteAckSequence, mDrainSequence);
7616 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007617 return true;
7618 }
7619 return false;
7620}
7621
Andy Hungee58e4a2023-07-07 13:47:37 -07007622bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007623{
Andy Hung972bec12023-08-31 16:13:39 -07007624 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007625 return waitingAsyncCallback_l();
7626}
7627
Andy Hungee58e4a2023-07-07 13:47:37 -07007628void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007629{
Eric Laurente659ef42014-09-29 13:06:46 -07007630 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007631 // Flush anything still waiting in the mixbuffer
7632 mCurrentWriteLength = 0;
7633 mBytesRemaining = 0;
7634 mPausedWriteLength = 0;
7635 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007636 // reset bytes written count to reflect that DSP buffers are empty after flush.
7637 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007638
Eric Laurentbfb1b832013-01-07 09:53:42 -08007639 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007640 // discard any pending drain or write ack by incrementing sequence
7641 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7642 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007643 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007644 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7645 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007646 }
7647}
7648
Andy Hungee58e4a2023-07-07 13:47:37 -07007649void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007650{
Andy Hung972bec12023-08-31 16:13:39 -07007651 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007652 if (PlaybackThread::invalidateTracks_l(streamType)) {
7653 mFlushPending = true;
7654 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007655}
7656
Andy Hungee58e4a2023-07-07 13:47:37 -07007657void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007658 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007659 if (PlaybackThread::invalidateTracks_l(portIds)) {
7660 mFlushPending = true;
7661 }
7662}
7663
Eric Laurentbfb1b832013-01-07 09:53:42 -08007664// ----------------------------------------------------------------------------
7665
Andy Hungee58e4a2023-07-07 13:47:37 -07007666/* static */
7667sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007668 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007669 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007670 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007671}
7672
Andy Hung583043b2023-07-17 17:05:00 -07007673DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007674 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007675 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007676 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007677 mWaitTimeMs(UINT_MAX)
7678{
7679 addOutputTrack(mainThread);
7680}
7681
Andy Hungee58e4a2023-07-07 13:47:37 -07007682DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007683{
7684 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7685 mOutputTracks[i]->destroy();
7686 }
7687}
7688
Andy Hungee58e4a2023-07-07 13:47:37 -07007689void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007690{
7691 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007692 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007693 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007694 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007695 if (mMixerBufferValid) {
7696 memset(mMixerBuffer, 0, mMixerBufferSize);
7697 } else {
7698 memset(mSinkBuffer, 0, mSinkBufferSize);
7699 }
Eric Laurent81784c32012-11-19 14:55:58 -08007700 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007701 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007702 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007703 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007704 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007705}
7706
Andy Hungee58e4a2023-07-07 13:47:37 -07007707void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007708{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007709 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007710 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007711 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007712 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007713 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007714 }
7715 } else if (mBytesWritten != 0) {
7716 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7717 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007718 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007719 } else {
7720 // flush remaining overflow buffers in output tracks
7721 writeFrames = 0;
7722 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007723 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007724 }
7725}
7726
Andy Hungee58e4a2023-07-07 13:47:37 -07007727ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007728{
7729 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007730 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7731
7732 // Consider the first OutputTrack for timestamp and frame counting.
7733
7734 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7735 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7736 // we always claim success.
7737 if (i == 0) {
7738 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7739 ALOGD_IF(correction != 0 && writeFrames != 0,
7740 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7741 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7742 mFramesWritten -= correction;
7743 }
7744
7745 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007746 }
Andy Hungcf10d742020-04-28 15:38:24 -07007747 if (mStandby) {
7748 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007749 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007750 mStandby = false;
7751 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007752 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007753}
7754
Andy Hungee58e4a2023-07-07 13:47:37 -07007755void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007756{
7757 // DuplicatingThread implements standby by stopping all tracks
7758 for (size_t i = 0; i < outputTracks.size(); i++) {
7759 outputTracks[i]->stop();
7760 }
7761}
7762
Andy Hung8a5abfd2023-12-07 19:35:12 -08007763void DuplicatingThread::threadLoop_exit()
7764{
7765 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7766 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7767 // Do so here in the threadLoop_exit().
7768
7769 SortedVector <sp<IAfOutputTrack>> localTracks;
7770 {
7771 audio_utils::lock_guard l(mutex());
7772 localTracks = std::move(mOutputTracks);
7773 mOutputTracks.clear();
7774 }
7775 localTracks.clear();
7776 outputTracks.clear();
7777 PlaybackThread::threadLoop_exit();
7778}
7779
Andy Hungee58e4a2023-07-07 13:47:37 -07007780void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007781{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007782 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007783
7784 std::stringstream ss;
7785 const size_t numTracks = mOutputTracks.size();
7786 ss << " " << numTracks << " OutputTracks";
7787 if (numTracks > 0) {
7788 ss << ":";
7789 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007790 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007791 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007792 if (thread.get() != nullptr) {
7793 ss << thread.get() << ", " << thread->id();
7794 } else {
7795 ss << "null";
7796 }
7797 ss << ")";
7798 }
7799 }
7800 ss << "\n";
7801 std::string result = ss.str();
7802 write(fd, result.c_str(), result.size());
7803}
7804
Andy Hungee58e4a2023-07-07 13:47:37 -07007805void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007806{
7807 outputTracks = mOutputTracks;
7808}
7809
Andy Hungee58e4a2023-07-07 13:47:37 -07007810void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007811{
7812 outputTracks.clear();
7813}
7814
Andy Hungee58e4a2023-07-07 13:47:37 -07007815void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007816{
Andy Hung972bec12023-08-31 16:13:39 -07007817 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007818 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7819 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7820 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7821 const size_t frameCount =
7822 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7823 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7824 // from different OutputTracks and their associated MixerThreads (e.g. one may
7825 // nearly empty and the other may be dropping data).
7826
Svet Ganov33761132021-05-13 22:51:08 +00007827 // TODO b/182392769: use attribution source util, move to server edge
7828 AttributionSourceState attributionSource = AttributionSourceState();
7829 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007830 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007831 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007832 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007833 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007834 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007835 this,
7836 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007837 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007838 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007839 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007840 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007841 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7842 if (status != NO_ERROR) {
7843 ALOGE("addOutputTrack() initCheck failed %d", status);
7844 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007845 }
Eric Laurent277a37e2024-07-29 18:37:52 +00007846 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007847 mOutputTracks.add(outputTrack);
7848 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7849 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007850}
7851
Andy Hungee58e4a2023-07-07 13:47:37 -07007852void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007853{
Andy Hung972bec12023-08-31 16:13:39 -07007854 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007855 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7856 if (mOutputTracks[i]->thread() == thread) {
7857 mOutputTracks[i]->destroy();
7858 mOutputTracks.removeAt(i);
7859 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007860 // NO_THREAD_SAFETY_ANALYSIS
7861 // Lambda workaround: as thread != this
7862 // we can safely call the remote thread getOutput.
7863 const bool equalOutput =
7864 [&](){ return thread->getOutput() == mOutput; }();
7865 if (equalOutput) {
7866 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007867 }
Eric Laurent81784c32012-11-19 14:55:58 -08007868 return;
7869 }
7870 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007871 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007872}
7873
Andy Hungc5007f82023-08-29 14:26:09 -07007874// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007875void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007876{
7877 mWaitTimeMs = UINT_MAX;
7878 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007879 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007880 if (strong != 0) {
7881 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7882 if (waitTimeMs < mWaitTimeMs) {
7883 mWaitTimeMs = waitTimeMs;
7884 }
7885 }
7886 }
7887}
7888
Andy Hungee58e4a2023-07-07 13:47:37 -07007889bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007890{
7891 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007892 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007893 if (thread == 0) {
7894 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7895 outputTracks[i].get());
7896 return false;
7897 }
Andy Hung87c693c2023-07-06 20:56:16 -07007898 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007899 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007900 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007901 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7902 thread.get());
7903 return false;
7904 }
7905 }
7906 return true;
7907}
7908
Andy Hungee58e4a2023-07-07 13:47:37 -07007909void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007910 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007911{
Kevin Rocard12381092018-04-11 09:19:59 -07007912 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7913 outputTrack->setMetadatas(metadata.tracks);
7914 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007915}
7916
Andy Hungee58e4a2023-07-07 13:47:37 -07007917uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007918{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007919 // return half the wait time in microseconds.
7920 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007921}
7922
Andy Hungee58e4a2023-07-07 13:47:37 -07007923void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007924{
7925 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7926 updateWaitTime_l();
7927
7928 MixerThread::cacheParameters_l();
7929}
7930
Eric Laurentb3f315a2021-07-13 15:09:05 +02007931// ----------------------------------------------------------------------------
7932
Andy Hungee58e4a2023-07-07 13:47:37 -07007933/* static */
7934sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007935 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007936 AudioStreamOut* output,
7937 audio_io_handle_t id,
7938 bool systemReady,
7939 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007940 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007941}
7942
Andy Hung583043b2023-07-17 17:05:00 -07007943SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007944 AudioStreamOut* output,
7945 audio_io_handle_t id,
7946 bool systemReady,
7947 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007948 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007949{
7950}
7951
Andy Hungee58e4a2023-07-07 13:47:37 -07007952void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007953 // if mSupportedLatencyModes is empty, the HAL stream does not support
7954 // latency mode control and we can exit.
7955 if (mSupportedLatencyModes.empty()) {
7956 return;
7957 }
Eric Laurent4c85e372024-02-23 16:50:06 +00007958 // Do not update the HAL latency mode if no track is active
7959 if (mActiveTracks.isEmpty()) {
7960 return;
7961 }
7962
Eric Laurent68a40a82022-05-03 18:15:04 +02007963 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7964 if (mSupportedLatencyModes.size() == 1) {
7965 // If the HAL only support one latency mode currently, confirm the choice
7966 latencyMode = mSupportedLatencyModes[0];
7967 } else if (mSupportedLatencyModes.size() > 1) {
7968 // Request low latency if:
7969 // - The low latency mode is requested by the spatializer controller
7970 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7971 // AND
7972 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007973 for (const auto& track : mActiveTracks) {
7974 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007975 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007976 break;
7977 }
7978 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007979 }
7980
7981 if (latencyMode != mSetLatencyMode) {
7982 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007983 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7984 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007985 if (status == NO_ERROR) {
7986 mSetLatencyMode = latencyMode;
7987 }
7988 }
7989}
7990
Andy Hungee58e4a2023-07-07 13:47:37 -07007991status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007992 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007993 return BAD_VALUE;
7994 }
Andy Hung972bec12023-08-31 16:13:39 -07007995 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007996 mRequestedLatencyMode = mode;
7997 return NO_ERROR;
7998}
7999
Andy Hungee58e4a2023-07-07 13:47:37 -07008000void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008001NO_THREAD_SAFETY_ANALYSIS
8002// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008003{
8004 bool hasVirtualizer = false;
8005 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008006 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008007 {
Andy Hung972bec12023-08-31 16:13:39 -07008008 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008009 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008010 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008011 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008012 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8013 }
8014
8015 finalDownMixer = mFinalDownMixer;
8016 mFinalDownMixer.clear();
8017 }
8018
8019 if (hasVirtualizer) {
8020 if (finalDownMixer != nullptr) {
8021 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008022 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008023 }
8024 finalDownMixer.clear();
8025 } else if (!hasDownMixer) {
8026 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008027 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008028 EFFECT_UIID_DOWNMIX, &descriptors);
8029 if (status != NO_ERROR) {
8030 return;
8031 }
8032 ALOG_ASSERT(!descriptors.empty(),
8033 "%s getDescriptors() returned no error but empty list", __func__);
8034
8035 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8036 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008037 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008038
8039 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8040 ALOGW("%s error creating downmixer %d", __func__, status);
8041 finalDownMixer.clear();
8042 } else {
8043 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008044 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008045 }
8046 }
8047
8048 {
Andy Hung972bec12023-08-31 16:13:39 -07008049 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008050 mFinalDownMixer = finalDownMixer;
8051 }
8052}
8053
Andy Hunge2514462023-12-06 14:59:24 -08008054void SpatializerThread::threadLoop_exit()
8055{
8056 // The Spatializer EffectHandle must be released on the PlaybackThread
8057 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8058 mFinalDownMixer.clear();
8059
8060 PlaybackThread::threadLoop_exit();
8061}
8062
Eric Laurent81784c32012-11-19 14:55:58 -08008063// ----------------------------------------------------------------------------
8064// Record
8065// ----------------------------------------------------------------------------
8066
Andy Hung583043b2023-07-17 17:05:00 -07008067sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008068 AudioStreamIn* input,
8069 audio_io_handle_t id,
8070 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008071 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008072}
8073
Andy Hung583043b2023-07-17 17:05:00 -07008074RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008075 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008076 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008077 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008078 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008079 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008080 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008081 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008082 mActiveTracks(&this->mLocalLog),
8083 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008084 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008085 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008086 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8087 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008088 // mFastCapture below
8089 , mFastCaptureFutex(0)
8090 // mInputSource
8091 // mPipeSink
8092 // mPipeSource
8093 , mPipeFramesP2(0)
8094 // mPipeMemory
8095 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008096 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008097 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008098{
Glenn Kastend7dca052015-03-05 16:05:54 -08008099 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008100 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008101
George Burgess IVa8f90c12020-05-14 11:27:19 -07008102 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008103 mIsMsdDevice = strcmp(
8104 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8105 }
8106
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008107 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008108
Andy Hungc8fddf32018-08-08 18:32:37 -07008109 // TODO: We may also match on address as well as device type for
8110 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008111 // TODO: This property should be ensure that only contains one single device type.
8112 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8113 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008114 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8115 : AUDIO_DEVICE_NONE));
8116
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008117 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008118 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008119 size_t numCounterOffers = 0;
8120 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008121#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008122 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008123#else
8124 (void)
8125#endif
8126 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008127 ALOG_ASSERT(index == 0);
8128
8129 // initialize fast capture depending on configuration
8130 bool initFastCapture;
8131 switch (kUseFastCapture) {
8132 case FastCapture_Never:
8133 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008134 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008135 break;
8136 case FastCapture_Always:
8137 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008138 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008139 break;
8140 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008141 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008142 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008143 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008144 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8145 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8146 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008147 break;
8148 // case FastCapture_Dynamic:
8149 }
8150
8151 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008152 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008153 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008154 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8155 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008156 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008157 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008158 const sp<MemoryDealer> roHeap(readOnlyHeap());
8159 sp<IMemory> pipeMemory;
8160 if ((roHeap == 0) ||
8161 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008162 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008163 ALOGE("not enough memory for pipe buffer size=%zu; "
8164 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8165 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8166 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008167 goto failed;
8168 }
8169 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8170 memset(pipeBuffer, 0, pipeSize);
8171 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008172 const NBAIO_Format offersFast[1] = {format};
8173 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008174 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008175 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008176 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008177 mPipeSink = pipe;
8178 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008179 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008180 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008181 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008182 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008183 mPipeSource = pipeReader;
8184 mPipeFramesP2 = pipeFramesP2;
8185 mPipeMemory = pipeMemory;
8186
8187 // create fast capture
8188 mFastCapture = new FastCapture();
8189 FastCaptureStateQueue *sq = mFastCapture->sq();
8190#ifdef STATE_QUEUE_DUMP
8191 // FIXME
8192#endif
8193 FastCaptureState *state = sq->begin();
8194 state->mCblk = NULL;
8195 state->mInputSource = mInputSource.get();
8196 state->mInputSourceGen++;
8197 state->mPipeSink = pipe;
8198 state->mPipeSinkGen++;
8199 state->mFrameCount = mFrameCount;
8200 state->mCommand = FastCaptureState::COLD_IDLE;
8201 // already done in constructor initialization list
8202 //mFastCaptureFutex = 0;
8203 state->mColdFutexAddr = &mFastCaptureFutex;
8204 state->mColdGen++;
8205 state->mDumpState = &mFastCaptureDumpState;
8206#ifdef TEE_SINK
8207 // FIXME
8208#endif
Andy Hung583043b2023-07-17 17:05:00 -07008209 mFastCaptureNBLogWriter =
8210 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008211 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8212 sq->end();
8213 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8214
8215 // start the fast capture
8216 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8217 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008218 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008219 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008220#ifdef AUDIO_WATCHDOG
8221 // FIXME
8222#endif
8223
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008224 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008225 }
Andy Hung8946a282018-04-19 20:04:56 -07008226#ifdef TEE_SINK
8227 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8228 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8229#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008230failed: ;
8231
8232 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008233}
8234
Andy Hungee58e4a2023-07-07 13:47:37 -07008235RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008236{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008237 if (mFastCapture != 0) {
8238 FastCaptureStateQueue *sq = mFastCapture->sq();
8239 FastCaptureState *state = sq->begin();
8240 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8241 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8242 if (old == -1) {
8243 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8244 }
8245 }
8246 state->mCommand = FastCaptureState::EXIT;
8247 sq->end();
8248 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8249 mFastCapture->join();
8250 mFastCapture.clear();
8251 }
Andy Hung583043b2023-07-17 17:05:00 -07008252 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8253 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008254 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008255}
8256
Andy Hungee58e4a2023-07-07 13:47:37 -07008257void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008258{
Glenn Kastend7dca052015-03-05 16:05:54 -08008259 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008260}
8261
Andy Hungee58e4a2023-07-07 13:47:37 -07008262void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008263{
8264 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008265 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008266 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008267 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008268 track->invalidate();
8269 }
8270 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008271 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008272}
8273
Andy Hungee58e4a2023-07-07 13:47:37 -07008274bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008275{
Eric Laurent81784c32012-11-19 14:55:58 -08008276 nsecs_t lastWarning = 0;
8277
8278 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008279
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008280reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008281 {
Andy Hung972bec12023-08-31 16:13:39 -07008282 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008283 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008284 }
8285
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008286 // used to request a deferred sleep, to be executed later while mutex is unlocked
8287 uint32_t sleepUs = 0;
8288
Andy Hung95c94a22023-10-20 16:41:18 -07008289 // timestamp correction enable is determined under lock, used in processing step.
8290 bool timestampCorrectionEnabled = false;
8291
Andy Hung446f4df2019-02-21 12:26:41 -08008292 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8293
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008294 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008295 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008296 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8297 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008298 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008299 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008300
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008301 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008302 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008303
Glenn Kasten735f45f2014-08-18 15:51:59 -07008304 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008305 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008306
Glenn Kasten735f45f2014-08-18 15:51:59 -07008307 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008308 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008309
Eric Laurent33403f02020-05-29 18:35:06 -07008310 bool silenceFastCapture = false;
8311
Andy Hungc5007f82023-08-29 14:26:09 -07008312 { // scope for mutex()
8313 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008314
Eric Laurent021cf962014-05-13 10:18:14 -07008315 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008316
Eric Laurent000a4192014-01-29 15:17:32 -08008317 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008318 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008319 if (exitPending()) {
8320 break;
8321 }
8322
Eric Laurent5c25d562016-07-13 17:17:45 -07008323 // sleep with mutex unlocked
8324 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008325 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008326 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008327 ATRACE_END();
8328 sleepUs = 0;
8329 continue;
8330 }
8331
Glenn Kasten2b806402013-11-20 16:37:38 -08008332 // if no active track(s), then standby and release wakelock
8333 size_t size = mActiveTracks.size();
8334 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008335 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008336 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008337 releaseWakeLock_l();
8338 ALOGV("RecordThread: loop stopping");
8339 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008340 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008341 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008342 goto reacquire_wakelock;
8343 }
8344
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008345 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008346 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008347 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008348 if (activeTrack) { // ensure track release is outside lock.
8349 oldActiveTracks.emplace_back(std::move(activeTrack));
8350 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008351 activeTrack = mActiveTracks[i];
8352 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008353 if (activeTrack->isFastTrack()) {
8354 ALOG_ASSERT(fastTrackToRemove == 0);
8355 fastTrackToRemove = activeTrack;
8356 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008357 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008358 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008359 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008360 continue;
8361 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008362
Andy Hung8d31fd22023-06-26 19:20:57 -07008363 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008364 switch (activeTrackState) {
8365
Andy Hung8d31fd22023-06-26 19:20:57 -07008366 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008367 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008368 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008369 if (activeTrack->isFastTrack()) {
8370 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8371 // Keep a ref on fast track to wait for FastCapture thread to get updated
8372 // state before potential track removal
8373 fastTrackToRemove = activeTrack;
8374 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008375 doBroadcast = true;
8376 size--;
8377 continue;
8378
Andy Hung8d31fd22023-06-26 19:20:57 -07008379 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008380 sleepUs = 10000;
8381 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008382 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008383 continue;
8384
Andy Hung8d31fd22023-06-26 19:20:57 -07008385 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008386 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008387 if (mStandby) {
8388 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008389 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008390 mStandby = false;
8391 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008392 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008393 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008394 break;
8395
Andy Hung8d31fd22023-06-26 19:20:57 -07008396 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008397 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008398 break;
8399
Andy Hung8d31fd22023-06-26 19:20:57 -07008400 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8401 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8402 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008403 default:
Andy Hungce685402018-10-05 17:23:27 -07008404 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8405 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008406 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008407
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008408 if (activeTrack->isFastTrack()) {
8409 ALOG_ASSERT(!mFastTrackAvail);
8410 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008411 // if the active fast track is silenced either:
8412 // 1) silence the whole capture from fast capture buffer if this is
8413 // the only active track
8414 // 2) invalidate this track: this will cause the client to reconnect and possibly
8415 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008416 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008417 if (activeTrack->isSilenced()) {
8418 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008419 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008420 } else {
8421 silenceFastCapture = true;
8422 }
8423 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008424 // Invalidate fast tracks if access to audio history is required as this is not
8425 // possible with fast tracks. Once the fast track has been invalidated, no new
8426 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8427 if (mMaxSharedAudioHistoryMs != 0) {
8428 invalidate = true;
8429 }
8430 if (invalidate) {
8431 activeTrack->invalidate();
8432 ALOG_ASSERT(fastTrackToRemove == 0);
8433 fastTrackToRemove = activeTrack;
8434 removeTrack_l(activeTrack);
8435 mActiveTracks.remove(activeTrack);
8436 size--;
8437 continue;
8438 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008439 fastTrack = activeTrack;
8440 }
Eric Laurent33403f02020-05-29 18:35:06 -07008441
8442 activeTracks.add(activeTrack);
8443 i++;
8444
Glenn Kasten9e982352013-08-14 14:39:50 -07008445 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008446
Andy Hungab65b182023-09-06 19:41:47 -07008447 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008448
Kevin Rocard069c2712018-03-29 19:09:14 -07008449 updateMetadata_l();
8450
Eric Laurent5c25d562016-07-13 17:17:45 -07008451 if (allStopped) {
8452 standbyIfNotAlreadyInStandby();
8453 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008454 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008455 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008456 }
8457
8458 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008459 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008460 if (sleepUs == 0) {
8461 sleepUs = kRecordThreadSleepUs;
8462 }
8463 continue;
8464 }
8465 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008466
Andy Hung95c94a22023-10-20 16:41:18 -07008467 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008468 lockEffectChains_l(effectChains);
8469 }
8470
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008472
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008473 size_t size = effectChains.size();
8474 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008475 // thread mutex is not locked, but effect chain is locked
8476 effectChains[i]->process_l();
8477 }
8478
Glenn Kasten735f45f2014-08-18 15:51:59 -07008479 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008480 if (mFastCapture != 0) {
8481 FastCaptureStateQueue *sq = mFastCapture->sq();
8482 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008483 bool didModify = false;
8484 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008485 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8486 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8487 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8488 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8489 if (old == -1) {
8490 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8491 }
8492 }
8493 state->mCommand = FastCaptureState::READ_WRITE;
8494#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008495 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008496 FastThreadDumpState::kSamplingNforLowRamDevice :
8497 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008498#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008499 didModify = true;
8500 }
8501 audio_track_cblk_t *cblkOld = state->mCblk;
8502 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8503 if (cblkNew != cblkOld) {
8504 state->mCblk = cblkNew;
8505 // block until acked if removing a fast track
8506 if (cblkOld != NULL) {
8507 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8508 }
8509 didModify = true;
8510 }
jiabin01c8f562018-07-19 17:47:28 -07008511 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8512 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8513 if (state->mFastPatchRecordBufferProvider != abp) {
8514 state->mFastPatchRecordBufferProvider = abp;
8515 state->mFastPatchRecordFormat = fastTrack == 0 ?
8516 AUDIO_FORMAT_INVALID : fastTrack->format();
8517 didModify = true;
8518 }
Eric Laurent33403f02020-05-29 18:35:06 -07008519 if (state->mSilenceCapture != silenceFastCapture) {
8520 state->mSilenceCapture = silenceFastCapture;
8521 didModify = true;
8522 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008523 sq->end(didModify);
8524 if (didModify) {
8525 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008526#if 0
8527 if (kUseFastCapture == FastCapture_Dynamic) {
8528 mNormalSource = mPipeSource;
8529 }
8530#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008531 }
8532 }
8533
Glenn Kasten735f45f2014-08-18 15:51:59 -07008534 // now run the fast track destructor with thread mutex unlocked
8535 fastTrackToRemove.clear();
8536
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008537 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8538 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8539 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8540 // If destination is non-contiguous, first read past the nominal end of buffer, then
8541 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008542
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008543 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008544 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008545 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008546
8547 // If an NBAIO source is present, use it to read the normal capture's data
8548 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008549 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008550
8551 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8552 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8553 // we immediately retry the read() to get data and prevent another overflow.
8554 for (int retries = 0; retries <= 2; ++retries) {
8555 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8556 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8557 framesToRead);
8558 if (framesRead != OVERRUN) break;
8559 }
8560
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008561 const ssize_t availableToRead = mPipeSource->availableToRead();
8562 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008563 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008564 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008565 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8566 "more frames to read than fifo size, %zd > %zu",
8567 availableToRead, mPipeFramesP2);
8568 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8569 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8570 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8571 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008572 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8573 }
8574 if (framesRead < 0) {
8575 status_t status = (status_t) framesRead;
8576 switch (status) {
8577 case OVERRUN:
8578 ALOGW("overrun on read from pipe");
8579 framesRead = 0;
8580 break;
8581 case NEGOTIATE:
8582 ALOGE("re-negotiation is needed");
8583 framesRead = -1; // Will cause an attempt to recover.
8584 break;
8585 default:
8586 ALOGE("unknown error %d on read from pipe", status);
8587 break;
8588 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008589 }
8590 // otherwise use the HAL / AudioStreamIn directly
8591 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008592 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008593 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008594 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008595 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008596 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008597 if (result < 0) {
8598 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008599 } else {
8600 framesRead = bytesRead / mFrameSize;
8601 }
8602 }
8603
Andy Hung446f4df2019-02-21 12:26:41 -08008604 const int64_t lastIoEndNs = systemTime(); // end IO timing
8605
Andy Hung3f0c9022016-01-15 17:49:46 -08008606 // Update server timestamp with server stats
8607 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008608 if (framesRead >= 0) {
8609 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8610 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8611 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008612
8613 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008614 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008615 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008616 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008617 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8618 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8619 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008620 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008621 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8622
8623 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008624 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008625 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008626 id(), (long long)time, (long long)position);
8627 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8628 position = correctedTimestamp.mFrames;
8629 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008630 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008631 id(), (long long)time, (long long)position);
8632 }
8633
Andy Hung3f0c9022016-01-15 17:49:46 -08008634 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8635 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8636 // Note: In general record buffers should tend to be empty in
8637 // a properly running pipeline.
8638 //
8639 // Also, it is not advantageous to call get_presentation_position during the read
8640 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008641 } else {
8642 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008643 }
8644 }
Andy Hunge6c37112019-02-26 17:38:10 -08008645
8646 // From the timestamp, input read latency is negative output write latency.
8647 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008648 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008649 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8650 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8651 mLatencyMs.add(latencyMs);
8652 }
8653
Andy Hung3f0c9022016-01-15 17:49:46 -08008654 // Use this to track timestamp information
8655 // ALOGD("%s", mTimestamp.toString().c_str());
8656
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008657 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008658 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008659 // Force input into standby so that it tries to recover at next read attempt
8660 inputStandBy();
8661 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008662 }
8663 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008664 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008665 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008666 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008667 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008668
Andy Hung8946a282018-04-19 20:04:56 -07008669#ifdef TEE_SINK
8670 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8671#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008672 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008673 {
8674 size_t part1 = mRsmpInFramesP2 - rear;
8675 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008676 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008677 (framesRead - part1) * mFrameSize);
8678 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008679 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008680 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008681
8682 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008683
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008684 // loop over each active track
8685 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008686 if (activeTrack) { // ensure track release is outside lock.
8687 oldActiveTracks.emplace_back(std::move(activeTrack));
8688 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008689 activeTrack = activeTracks[i];
8690
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008691 // skip fast tracks, as those are handled directly by FastCapture
8692 if (activeTrack->isFastTrack()) {
8693 continue;
8694 }
8695
Andy Hung73c02e42015-03-29 01:13:58 -07008696 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008697 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8698
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008699 enum {
8700 OVERRUN_UNKNOWN,
8701 OVERRUN_TRUE,
8702 OVERRUN_FALSE
8703 } overrun = OVERRUN_UNKNOWN;
8704
8705 // loop over getNextBuffer to handle circular sink
8706 for (;;) {
8707
Andy Hung8d31fd22023-06-26 19:20:57 -07008708 activeTrack->sinkBuffer().frameCount = ~0;
8709 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8710 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008711 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8712
Andy Hung73c02e42015-03-29 01:13:58 -07008713 // check available frames and handle overrun conditions
8714 // if the record track isn't draining fast enough.
8715 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008716 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008717 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008718 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008719 overrun = OVERRUN_TRUE;
8720 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008721 if (framesOut == 0 || framesIn == 0) {
8722 break;
8723 }
8724
Andy Hung6770c6f2015-04-07 13:43:36 -07008725 // Don't allow framesOut to be larger than what is possible with resampling
8726 // from framesIn.
8727 // This isn't strictly necessary but helps limit buffer resizing in
8728 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008729 if (audio_is_linear_pcm(activeTrack->format())) {
8730 framesOut = min(framesOut,
8731 destinationFramesPossible(
8732 framesIn, mSampleRate, activeTrack->sampleRate()));
8733 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008734
8735 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008736 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008737 // straight from RecordThread buffer to RecordTrack buffer.
8738 AudioBufferProvider::Buffer buffer;
8739 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008740 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008741 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008742 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008743 ALOGV_IF(buffer.frameCount != framesOut,
8744 "%s() read less than expected (%zu vs %zu)",
8745 __func__, buffer.frameCount, framesOut);
8746 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008747 memcpy(activeTrack->sinkBuffer().raw,
8748 buffer.raw, buffer.frameCount * mFrameSize);
8749 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008750 } else {
8751 framesOut = 0;
8752 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008753 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008754 }
8755 } else {
8756 // process frames from the RecordThread buffer provider to the RecordTrack
8757 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008758 framesOut = activeTrack->recordBufferConverter()->convert(
8759 activeTrack->sinkBuffer().raw,
8760 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008761 framesOut);
8762 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008763
8764 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8765 overrun = OVERRUN_FALSE;
8766 }
8767
Andy Hung93bb5732023-05-04 21:16:34 -07008768 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8769 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008770 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008771 if (framesToDrop == 0) {
8772 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008773 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008774 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008775 // Sanitize before releasing if the track has no access to the source data
8776 // An idle UID receives silence from non virtual devices until active
8777 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008778 memset(activeTrack->sinkBuffer().raw,
8779 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008780 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008781 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008782 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008783 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008784 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008785 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008786 }
8787 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008788
8789 switch (overrun) {
8790 case OVERRUN_TRUE:
8791 // client isn't retrieving buffers fast enough
8792 if (!activeTrack->setOverflow()) {
8793 nsecs_t now = systemTime();
8794 // FIXME should lastWarning per track?
8795 if ((now - lastWarning) > kWarningThrottleNs) {
8796 ALOGW("RecordThread: buffer overflow");
8797 lastWarning = now;
8798 }
8799 }
8800 break;
8801 case OVERRUN_FALSE:
8802 activeTrack->clearOverflow();
8803 break;
8804 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008805 break;
8806 }
8807
Andy Hung3f0c9022016-01-15 17:49:46 -08008808 // update frame information and push timestamp out
8809 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008810 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008811 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8812 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008813 }
8814
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008815unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008816 // enable changes in effect chain
8817 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008818 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008819 if (audio_has_proportional_frames(mFormat)
8820 && loopCount == lastLoopCountRead + 1) {
8821 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8822 const double jitterMs =
8823 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8824 {framesRead, readPeriodNs},
8825 {0, 0} /* lastTimestamp */, mSampleRate);
8826 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8827
Andy Hung972bec12023-08-31 16:13:39 -07008828 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008829 mIoJitterMs.add(jitterMs);
8830 mProcessTimeMs.add(processMs);
8831 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008832 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008833 // update timing info.
8834 mLastIoBeginNs = lastIoBeginNs;
8835 mLastIoEndNs = lastIoEndNs;
8836 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008837 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008838 mThreadloopExecutor.process(); // process any remaining deferred actions.
8839 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008840
Glenn Kasten93e471f2013-08-19 08:40:07 -07008841 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008842
8843 {
Andy Hung972bec12023-08-31 16:13:39 -07008844 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008845 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008846 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008847 track->invalidate();
8848 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008849 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008850 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008851 }
8852
8853 releaseWakeLock();
8854
8855 ALOGV("RecordThread %p exiting", this);
8856 return false;
8857}
8858
Andy Hungee58e4a2023-07-07 13:47:37 -07008859void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008860{
8861 if (!mStandby) {
8862 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008863 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008864 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008865 mStandby = true;
8866 }
8867}
8868
Andy Hungee58e4a2023-07-07 13:47:37 -07008869void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008870{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008871 // Idle the fast capture if it's currently running
8872 if (mFastCapture != 0) {
8873 FastCaptureStateQueue *sq = mFastCapture->sq();
8874 FastCaptureState *state = sq->begin();
8875 if (!(state->mCommand & FastCaptureState::IDLE)) {
8876 state->mCommand = FastCaptureState::COLD_IDLE;
8877 state->mColdFutexAddr = &mFastCaptureFutex;
8878 state->mColdGen++;
8879 mFastCaptureFutex = 0;
8880 sq->end();
8881 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8882 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8883#if 0
8884 if (kUseFastCapture == FastCapture_Dynamic) {
8885 // FIXME
8886 }
8887#endif
8888#ifdef AUDIO_WATCHDOG
8889 // FIXME
8890#endif
8891 } else {
8892 sq->end(false /*didModify*/);
8893 }
8894 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008895 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008896 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008897
8898 // If going into standby, flush the pipe source.
8899 if (mPipeSource.get() != nullptr) {
8900 const ssize_t flushed = mPipeSource->flush();
8901 if (flushed > 0) {
8902 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8903 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8904 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8905 }
8906 }
Eric Laurent81784c32012-11-19 14:55:58 -08008907}
8908
Andy Hungc5007f82023-08-29 14:26:09 -07008909// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008910sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008911 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008912 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008913 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008914 audio_format_t format,
8915 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008916 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008917 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008918 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008919 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008920 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008921 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008922 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008923 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008924 audio_port_handle_t portId,
8925 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008926{
Glenn Kasten74935e42013-12-19 08:56:45 -08008927 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008928 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008929 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008930 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008931 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008932 audio_input_flags_t requestedFlags = *flags;
8933 uint32_t sampleRate;
8934
8935 lStatus = initCheck();
8936 if (lStatus != NO_ERROR) {
8937 ALOGE("createRecordTrack_l() audio driver not initialized");
8938 goto Exit;
8939 }
8940
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008941 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8942 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8943 lStatus = BAD_VALUE;
8944 goto Exit;
8945 }
8946
Eric Laurentec376dc2021-04-08 20:41:22 +02008947 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008948 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008949 lStatus = PERMISSION_DENIED;
8950 goto Exit;
8951 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008952 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008953 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008954 lStatus = BAD_VALUE;
8955 goto Exit;
8956 }
8957 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008958 if (*pSampleRate == 0) {
8959 *pSampleRate = mSampleRate;
8960 }
8961 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008962
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008963 // special case for FAST flag considered OK if fast capture is present and access to
8964 // audio history is not required
8965 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008966 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8967 }
8968
Eric Laurentf14db3c2017-12-08 14:20:36 -08008969 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008970 if ((*flags & inputFlags) != *flags) {
8971 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8972 " input flags (%08x)",
8973 *flags, inputFlags);
8974 *flags = (audio_input_flags_t)(*flags & inputFlags);
8975 }
Eric Laurent81784c32012-11-19 14:55:58 -08008976
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008977 // client expresses a preference for FAST and no access to audio history,
8978 // but we get the final say
8979 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008980 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008981 // we formerly checked for a callback handler (non-0 tid),
8982 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008983 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008984 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008985 // Frame count is not specified (0), or is less than or equal the pipe depth.
8986 // It is OK to provide a higher capacity than requested.
8987 // We will force it to mPipeFramesP2 below.
8988 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008989 // PCM data
8990 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008991 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008992 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008993 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008994 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008995 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008996 hasFastCapture() &&
8997 // there are sufficient fast track slots available
8998 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008999 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009000 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009001 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009002 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009003 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009004 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009005 audio_input_flags_t old = *flags;
9006 chain->checkInputFlagCompatibility(flags);
9007 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009008 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9009 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009010 }
9011 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009012 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009013 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9014 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009015 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009016 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9017 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009018 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009019 this, frameCount, mFrameCount, mPipeFramesP2,
9020 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009021 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009022 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009023 }
9024 }
9025
Eric Laurentf14db3c2017-12-08 14:20:36 -08009026 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9027 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9028 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9029 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9030 lStatus = BAD_TYPE;
9031 goto Exit;
9032 }
9033
Glenn Kasten74105912014-07-03 12:28:53 -07009034 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009035 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009036 // fast track: frame count is exactly the pipe depth
9037 frameCount = mPipeFramesP2;
9038 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009039 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009040 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009041 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9042 // or 20 ms if there is a fast capture
9043 // TODO This could be a roundupRatio inline, and const
9044 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9045 * sampleRate + mSampleRate - 1) / mSampleRate;
9046 // minimum number of notification periods is at least kMinNotifications,
9047 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9048 static const size_t kMinNotifications = 3;
9049 static const uint32_t kMinMs = 30;
9050 // TODO This could be a roundupRatio inline
9051 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9052 // TODO This could be a roundupRatio inline
9053 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9054 maxNotificationFrames;
9055 const size_t minFrameCount = maxNotificationFrames *
9056 max(kMinNotifications, minNotificationsByMs);
9057 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009058 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9059 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009060 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009061 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009062 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009063 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009064
Andy Hungc5007f82023-08-29 14:26:09 -07009065 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009066 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009067 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009068 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009069 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009070 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009071 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009072 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009073 }
Eric Laurent81784c32012-11-19 14:55:58 -08009074
Andy Hung8d31fd22023-06-26 19:20:57 -07009075 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009076 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009077 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009078 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009079 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009080
Glenn Kasten03003332013-08-06 15:40:54 -07009081 lStatus = track->initCheck();
9082 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009083 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009084 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009085 goto Exit;
9086 }
9087 mTracks.add(track);
9088
Eric Laurent05067782016-06-01 18:27:28 -07009089 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009090 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9091 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9092 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009093 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009094 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009095
9096 if (maxSharedAudioHistoryMs != 0) {
9097 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9098 }
Eric Laurent81784c32012-11-19 14:55:58 -08009099 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009100
Eric Laurent81784c32012-11-19 14:55:58 -08009101 lStatus = NO_ERROR;
9102
9103Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009104 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009105 return track;
9106}
9107
Andy Hungee58e4a2023-07-07 13:47:37 -07009108status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009109 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009110 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009111{
9112 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9113 sp<ThreadBase> strongMe = this;
9114 status_t status = NO_ERROR;
9115
9116 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009117 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009118 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009119 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009120 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009121 event, triggerSession,
9122 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009123 }
9124
9125 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009126 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009127 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009128 if (recordTrack->isInvalid()) {
9129 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009130 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9131 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009132 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009133 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009134 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009135 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9136 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009137 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009138 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009139 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009140 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009141 }
9142 return status;
9143 }
9144
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009145 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9146 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9147 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009148 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009149 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009150 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009151 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009152 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009153 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009154 if (recordTrack->isInvalid()) {
9155 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009156 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9157 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009158 // STARTING_2 forces destroy to call stopInput.
9159 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009160 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9161 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009162 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009163 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009164 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009165 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009166 // Someone else has changed state, let them take over,
9167 // leave mState in the new state.
9168 recordTrack->clearSyncStartEvent();
9169 return INVALID_OPERATION;
9170 }
9171 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009172 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009173 ALOGW("%s(%d): startInput failed, status %d",
9174 __func__, recordTrack->id(), status);
9175 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9176 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009177 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009178 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009179 return status;
9180 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009181 sendIoConfigEvent_l(
9182 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009183 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009184
9185 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9186
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009187 // Catch up with current buffer indices if thread is already running.
9188 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9189 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9190 // see previously buffered data before it called start(), but with greater risk of overrun.
9191
Andy Hung8d31fd22023-06-26 19:20:57 -07009192 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009193 if (!recordTrack->isDirect()) {
9194 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009195 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009196 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009197 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009198 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009199 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009200 return status;
9201 }
Eric Laurent81784c32012-11-19 14:55:58 -08009202}
9203
Andy Hungee58e4a2023-07-07 13:47:37 -07009204void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009205{
Andy Hungee58e4a2023-07-07 13:47:37 -07009206 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009207
9208 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009209 sp<IAfTrackBase> ptr =
9210 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9211 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009212 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009213 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009214 }
Eric Laurent81784c32012-11-19 14:55:58 -08009215 }
9216}
9217
Andy Hungee58e4a2023-07-07 13:47:37 -07009218bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009219 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009220 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009221 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009222 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009223 return false;
9224 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009225 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009226 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009227
Andy Hungabfab202019-03-07 19:45:54 -08009228 // NOTE: Waiting here is important to keep stop synchronous.
9229 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009230 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009231 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009232 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009233 }
Andy Hungce685402018-10-05 17:23:27 -07009234
Andy Hung8d31fd22023-06-26 19:20:57 -07009235 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009236 ALOGV("Record stopped OK");
9237 return true;
9238 }
Andy Hungce685402018-10-05 17:23:27 -07009239
9240 // don't handle anything - we've been invalidated or restarted and in a different state
9241 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009242 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009243 return false;
9244}
9245
Andy Hungee58e4a2023-07-07 13:47:37 -07009246bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009247{
9248 return false;
9249}
9250
Andy Hungee58e4a2023-07-07 13:47:37 -07009251status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009252{
9253#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9254 if (!isValidSyncEvent(event)) {
9255 return BAD_VALUE;
9256 }
9257
Glenn Kastend848eb42016-03-08 13:42:11 -08009258 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009259 status_t ret = NAME_NOT_FOUND;
9260
Andy Hung972bec12023-08-31 16:13:39 -07009261 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009262
9263 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009264 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009265 if (eventSession == track->sessionId()) {
9266 (void) track->setSyncEvent(event);
9267 ret = NO_ERROR;
9268 }
9269 }
9270 return ret;
9271#else
9272 return BAD_VALUE;
9273#endif
9274}
9275
Andy Hungee58e4a2023-07-07 13:47:37 -07009276status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009277 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009278{
9279 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009280 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009281 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009282 return NO_INIT;
9283 }
jiabin9ff780e2018-03-19 18:19:52 -07009284 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9285 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009286}
9287
Andy Hungee58e4a2023-07-07 13:47:37 -07009288status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009289 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009290{
Paul McLean12340082019-03-19 09:35:05 -06009291 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009292 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009293 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009294 return NO_INIT;
9295 }
Paul McLean12340082019-03-19 09:35:05 -06009296 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009297}
9298
Andy Hungee58e4a2023-07-07 13:47:37 -07009299status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009300{
Paul McLean12340082019-03-19 09:35:05 -06009301 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009302 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009303 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009304 return NO_INIT;
9305 }
Paul McLean12340082019-03-19 09:35:05 -06009306 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009307}
9308
Andy Hungee58e4a2023-07-07 13:47:37 -07009309status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009310 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9311 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009312 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009313 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9314}
9315
Andy Hungee58e4a2023-07-07 13:47:37 -07009316status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009317 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9318 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009319
Eric Laurentec376dc2021-04-08 20:41:22 +02009320 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9321 return BAD_VALUE;
9322 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009323
9324 if (sharedAudioStartMs < 0
9325 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009326 return BAD_VALUE;
9327 }
9328
Eric Laurent2407ce32021-04-26 14:56:03 +02009329 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9330 // As we cannot detect more than one wraparound, only accept values up current write position
9331 // after one wraparound
9332 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9333 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009334 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009335 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9336 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009337 // Bring the start frame position within the input buffer to match the documented
9338 // "best effort" behavior of the API.
9339 if (sharedOffset < 0) {
9340 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009341 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009342 sharedAudioStartFrames =
9343 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009344 }
9345
Eric Laurentec376dc2021-04-08 20:41:22 +02009346 mSharedAudioPackageName = sharedAudioPackageName;
9347 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009348 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009349 } else {
9350 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009351 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009352 }
9353 return NO_ERROR;
9354}
9355
Andy Hungee58e4a2023-07-07 13:47:37 -07009356void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009357 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9358 mSharedAudioStartFrames = -1;
9359 mSharedAudioPackageName = "";
9360}
9361
Andy Hungee58e4a2023-07-07 13:47:37 -07009362ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009363{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009364 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009365 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009366 }
9367 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009368 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009369 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009370 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009371 }
9372 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009373 MetadataUpdate change;
9374 change.recordMetadataUpdate = metadata.tracks;
9375 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009376}
9377
Andy Hungc5007f82023-08-29 14:26:09 -07009378// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009379void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009380{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009381 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009382 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009383
Eric Laurent81784c32012-11-19 14:55:58 -08009384 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009385 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009386 removeTrack_l(track);
9387 }
9388}
9389
Andy Hungee58e4a2023-07-07 13:47:37 -07009390void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009391{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009392 String8 result;
9393 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009394 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009395
Eric Laurent81784c32012-11-19 14:55:58 -08009396 mTracks.remove(track);
9397 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009398 if (track->isFastTrack()) {
9399 ALOG_ASSERT(!mFastTrackAvail);
9400 mFastTrackAvail = true;
9401 }
Eric Laurent81784c32012-11-19 14:55:58 -08009402}
9403
Andy Hungee58e4a2023-07-07 13:47:37 -07009404void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009405{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009406 AudioStreamIn *input = mInput;
9407 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9408 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009409 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009410 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009411 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009412 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009413 }
Andy Hungbfa64962017-06-12 14:43:19 -07009414
9415 if (input != nullptr) {
9416 dprintf(fd, " Hal stream dump:\n");
9417 (void)input->stream->dump(fd);
9418 }
9419
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009420 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009421 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009422
Glenn Kasten2f90c512015-12-02 11:40:09 -08009423 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9424 // while we are dumping it. It may be inconsistent, but it won't mutate!
9425 // This is a large object so we place it on the heap.
9426 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009427 const std::unique_ptr<FastCaptureDumpState> copy =
9428 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009429 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009430}
9431
Andy Hungee58e4a2023-07-07 13:47:37 -07009432void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009433{
Eric Laurent81784c32012-11-19 14:55:58 -08009434 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009435 size_t numtracks = mTracks.size();
9436 size_t numactive = mActiveTracks.size();
9437 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009438 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009439 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009440 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009441 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009442 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009443 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009444 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009445 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009446 if (track != 0) {
9447 bool active = mActiveTracks.indexOf(track) >= 0;
9448 if (active) {
9449 numactiveseen++;
9450 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009451 result.append(prefix);
9452 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009453 }
Eric Laurent81784c32012-11-19 14:55:58 -08009454 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009455 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009456 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009457 }
9458
Marco Nelissenb2208842014-02-07 14:00:50 -08009459 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009460 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009461 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009462 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009463 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009464 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009465 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009466 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009467 result.append(prefix);
9468 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009469 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009470 }
Eric Laurent81784c32012-11-19 14:55:58 -08009471
9472 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009473 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009474}
9475
Andy Hungee58e4a2023-07-07 13:47:37 -07009476void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009477{
Andy Hung972bec12023-08-31 16:13:39 -07009478 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009479 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009480 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009481 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009482 track->setSilenced(silenced);
9483 }
9484 }
9485}
Andy Hung73c02e42015-03-29 01:13:58 -07009486
Andy Hung8d31fd22023-06-26 19:20:57 -07009487void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009488{
Andy Hung87c693c2023-07-06 20:56:16 -07009489 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009490 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009491 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009492 const int32_t rear = recordThread->mRsmpInRear;
9493 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009494 if (mRecordTrack->startFrames() >= 0) {
9495 int32_t startFrames = mRecordTrack->startFrames();
9496 // Accept a recent wraparound of mRsmpInRear
9497 if (startFrames <= rear) {
9498 deltaFrames = rear - startFrames;
9499 } else {
9500 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009501 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009502 // start frame cannot be further in the past than start of resampling buffer
9503 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9504 deltaFrames = recordThread->mRsmpInFrames;
9505 }
9506 }
9507 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009508}
9509
Andy Hung8d31fd22023-06-26 19:20:57 -07009510void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009511 size_t *framesAvailable, bool *hasOverrun)
9512{
Andy Hung87c693c2023-07-06 20:56:16 -07009513 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009514 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009515 const int32_t rear = recordThread->mRsmpInRear;
9516 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009517 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009518
9519 size_t framesIn;
9520 bool overrun = false;
9521 if (filled < 0) {
9522 // should not happen, but treat like a massive overrun and re-sync
9523 framesIn = 0;
9524 mRsmpInFront = rear;
9525 overrun = true;
9526 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9527 framesIn = (size_t) filled;
9528 } else {
9529 // client is not keeping up with server, but give it latest data
9530 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009531 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9532 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009533 overrun = true;
9534 }
9535 if (framesAvailable != NULL) {
9536 *framesAvailable = framesIn;
9537 }
9538 if (hasOverrun != NULL) {
9539 *hasOverrun = overrun;
9540 }
9541}
9542
Eric Laurent81784c32012-11-19 14:55:58 -08009543// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009544status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009545 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009546{
Andy Hung87c693c2023-07-06 20:56:16 -07009547 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009548 if (threadBase == 0) {
9549 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009550 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009551 return NOT_ENOUGH_DATA;
9552 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009553 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009554 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009555 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009556 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009557 // FIXME should not be P2 (don't want to increase latency)
9558 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009559 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009560 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009561
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009562 front &= recordThread->mRsmpInFramesP2 - 1;
9563 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009564 if (part1 > (size_t) filled) {
9565 part1 = filled;
9566 }
9567 size_t ask = buffer->frameCount;
9568 ALOG_ASSERT(ask > 0);
9569 if (part1 > ask) {
9570 part1 = ask;
9571 }
9572 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009573 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009574 buffer->raw = NULL;
9575 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009576 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009577 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009578 }
9579
Andy Hung57446612015-04-19 23:56:46 -07009580 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009581 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009582 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009583 return NO_ERROR;
9584}
9585
9586// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009587void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009588 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009589{
Hongwei Wang95e37682019-04-12 11:13:36 -07009590 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009591 if (stepCount == 0) {
9592 return;
9593 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009594 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009595 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009596 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009597 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009598 buffer->frameCount = 0;
9599}
9600
Andy Hungee58e4a2023-07-07 13:47:37 -07009601void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009602{
Andy Hung972bec12023-08-31 16:13:39 -07009603 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009604 checkBtNrec_l();
9605}
9606
Andy Hungee58e4a2023-07-07 13:47:37 -07009607void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009608{
9609 // disable AEC and NS if the device is a BT SCO headset supporting those
9610 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009611 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009612 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009613 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9614 for (size_t i = 0; i < mEffectChains.size(); i++) {
9615 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9616 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9617 }
9618 }
9619}
9620
Andy Hung97a893e2015-03-29 01:03:07 -07009621
Andy Hungee58e4a2023-07-07 13:47:37 -07009622bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009623 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009624{
9625 bool reconfig = false;
9626
Eric Laurent10351942014-05-08 18:49:52 -07009627 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009628
Eric Laurent10351942014-05-08 18:49:52 -07009629 audio_format_t reqFormat = mFormat;
9630 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009631 // 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 +08009632 [[maybe_unused]] audio_channel_mask_t channelMask =
9633 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009634
9635 AudioParameter param = AudioParameter(keyValuePair);
9636 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009637
9638 // scope for AutoPark extends to end of method
9639 AutoPark<FastCapture> park(mFastCapture);
9640
Eric Laurent10351942014-05-08 18:49:52 -07009641 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9642 // channel count change can be requested. Do we mandate the first client defines the
9643 // HAL sampling rate and channel count or do we allow changes on the fly?
9644 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9645 samplingRate = value;
9646 reconfig = true;
9647 }
9648 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009649 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009650 status = BAD_VALUE;
9651 } else {
9652 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009653 reconfig = true;
9654 }
Eric Laurent10351942014-05-08 18:49:52 -07009655 }
9656 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9657 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009658 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009659 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009660 status = BAD_VALUE;
9661 } else {
9662 channelMask = mask;
9663 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009664 }
Eric Laurent10351942014-05-08 18:49:52 -07009665 }
9666 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9667 // do not accept frame count changes if tracks are open as the track buffer
9668 // size depends on frame count and correct behavior would not be guaranteed
9669 // if frame count is changed after track creation
9670 if (mActiveTracks.size() > 0) {
9671 status = INVALID_OPERATION;
9672 } else {
9673 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009674 }
Eric Laurent10351942014-05-08 18:49:52 -07009675 }
9676 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009677 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009678 }
9679 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9680 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009681 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009682 }
Glenn Kastene198c362013-08-13 09:13:36 -07009683
Eric Laurent10351942014-05-08 18:49:52 -07009684 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009685 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009686 if (status == INVALID_OPERATION) {
9687 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009688 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009689 }
9690 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009691 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009692 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9693 if (mInput->stream->getAudioProperties(&config) == OK &&
9694 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9695 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009696 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009697 status = NO_ERROR;
9698 }
Eric Laurent81784c32012-11-19 14:55:58 -08009699 }
Eric Laurent10351942014-05-08 18:49:52 -07009700 if (status == NO_ERROR) {
9701 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009702 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009703 }
9704 }
Eric Laurent81784c32012-11-19 14:55:58 -08009705 }
Eric Laurent10351942014-05-08 18:49:52 -07009706
Eric Laurent81784c32012-11-19 14:55:58 -08009707 return reconfig;
9708}
9709
Andy Hungee58e4a2023-07-07 13:47:37 -07009710String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009711{
Andy Hung972bec12023-08-31 16:13:39 -07009712 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009713 if (initCheck() == NO_ERROR) {
9714 String8 out_s8;
9715 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9716 return out_s8;
9717 }
Eric Laurent81784c32012-11-19 14:55:58 -08009718 }
Andy Hung920f6572022-10-06 12:09:49 -07009719 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009720}
9721
Andy Hungab65b182023-09-06 19:41:47 -07009722void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009723 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009724 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009725 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009726 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009727 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009728 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009729 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9730 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009731 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009732 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009733 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009734 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009735 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009736 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009737 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009738 break;
9739 }
Andy Hungab65b182023-09-06 19:41:47 -07009740 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009741}
9742
Andy Hungee58e4a2023-07-07 13:47:37 -07009743void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009744{
Dean Wheatley6c009512023-10-23 09:34:14 +11009745 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9746 mSampleRate = audioConfig.sample_rate;
9747 mChannelMask = audioConfig.channel_mask;
9748 if (!audio_is_input_channel(mChannelMask)) {
9749 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9750 }
9751
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009752 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009753
9754 // Get actual HAL format.
9755 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9756 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9757 // Get format from the shim, which will be different than the HAL format
9758 // if recording compressed audio from IEC61937 wrapped sources.
9759 mFormat = audioConfig.format;
9760 if (!audio_is_valid_format(mFormat)) {
9761 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9762 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009763 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009764 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9765 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009766 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009767 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009768 ALOGI("HAL format %#x is not linear pcm", mFormat);
9769 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009770 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009771 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9772 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009773 result = mInput->stream->getBufferSize(&mBufferSize);
9774 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009775 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009776 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9777 "mBufferSize=%zu, mFrameCount=%zu",
9778 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009779
Eric Laurentec376dc2021-04-08 20:41:22 +02009780 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9781 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009782 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009783
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009784 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9785 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009786
9787 audio_input_flags_t flags = mInput->flags;
9788 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9789 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009790 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009791 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9792 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9793 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9794 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9795 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9796 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009797}
9798
Andy Hungee58e4a2023-07-07 13:47:37 -07009799uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009800{
Andy Hung972bec12023-08-31 16:13:39 -07009801 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009802 uint32_t result;
9803 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9804 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009805 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009806 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009807}
9808
Andy Hungee58e4a2023-07-07 13:47:37 -07009809KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009810{
Glenn Kastend848eb42016-03-08 13:42:11 -08009811 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009812 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009813 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009814 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009815 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009816 if (ids.indexOfKey(sessionId) < 0) {
9817 ids.add(sessionId, true);
9818 }
9819 }
9820 return ids;
9821}
9822
Andy Hungee58e4a2023-07-07 13:47:37 -07009823AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009824{
Andy Hung972bec12023-08-31 16:13:39 -07009825 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009826 AudioStreamIn *input = mInput;
9827 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009828 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009829 return input;
9830}
9831
Andy Hungc5007f82023-08-29 14:26:09 -07009832// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009833sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009834{
9835 if (mInput == NULL) {
9836 return NULL;
9837 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009838 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009839}
9840
Andy Hungee58e4a2023-07-07 13:47:37 -07009841status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009842{
Eric Laurent81784c32012-11-19 14:55:58 -08009843 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009844 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009845 chain->setInBuffer(NULL);
9846 chain->setOutBuffer(NULL);
9847
9848 checkSuspendOnAddEffectChain_l(chain);
9849
Eric Laurent1b928682014-10-02 19:41:47 -07009850 // make sure enabled pre processing effects state is communicated to the HAL as we
9851 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009852 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009853
Eric Laurent81784c32012-11-19 14:55:58 -08009854 mEffectChains.add(chain);
9855
9856 return NO_ERROR;
9857}
9858
Andy Hungee58e4a2023-07-07 13:47:37 -07009859size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009860{
9861 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009862
9863 for (size_t i = 0; i < mEffectChains.size(); i++) {
9864 if (chain == mEffectChains[i]) {
9865 mEffectChains.removeAt(i);
9866 break;
9867 }
Eric Laurent81784c32012-11-19 14:55:58 -08009868 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009869 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009870}
9871
Andy Hungee58e4a2023-07-07 13:47:37 -07009872status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009873 audio_patch_handle_t *handle)
9874{
9875 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009876
9877 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009878 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009879 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009880 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009881 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009882 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009883 }
9884
Eric Laurentd8365c52017-07-16 15:27:05 -07009885 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009886
9887 // store new source and send to effects
9888 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9889 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009890 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009891 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009892 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009893 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009894
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009895 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009896 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9897 status = hwDevice->createAudioPatch(patch->num_sources,
9898 patch->sources,
9899 patch->num_sinks,
9900 patch->sinks,
9901 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009902 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009903 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9904 patch->sinks[0].ext.mix.usecase.source,
9905 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009906 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009907 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009908
jiabinc52b1ff2019-10-31 17:20:42 -07009909 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009910 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009911 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009912 }
Eric Laurent296fb132015-05-01 11:38:42 -07009913
Andy Hungc2b11cb2020-04-22 09:04:01 -07009914 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009915 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009916 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009917 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009918 // also dispatch to active AudioRecords
9919 for (const auto &track : mActiveTracks) {
9920 track->logEndInterval();
9921 track->logBeginInterval(pathSourcesAsString);
9922 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009923 // Force meteadata update after a route change
9924 mActiveTracks.setHasChanged();
9925
Eric Laurent1c333e22014-05-20 10:48:17 -07009926 return status;
9927}
9928
Andy Hungee58e4a2023-07-07 13:47:37 -07009929status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009930{
9931 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009932
jiabinc52b1ff2019-10-31 17:20:42 -07009933 mPatch = audio_patch{};
9934 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009935
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009936 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009937 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9938 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009939 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009940 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009941 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009942 // Force meteadata update after a route change
9943 mActiveTracks.setHasChanged();
9944
Eric Laurent1c333e22014-05-20 10:48:17 -07009945 return status;
9946}
9947
Andy Hungee58e4a2023-07-07 13:47:37 -07009948void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009949{
Andy Hung972bec12023-08-31 16:13:39 -07009950 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009951 mOutDevices = outDevices;
9952 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9953 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009954 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009955 }
9956}
9957
Andy Hungee58e4a2023-07-07 13:47:37 -07009958int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009959{
9960 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009961 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009962 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009963 int32_t oldestFront = mRsmpInRear;
9964 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009965 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009966 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009967 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009968 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009969 if (filled > maxFilled) {
9970 oldestFront = front;
9971 maxFilled = filled;
9972 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009973 }
Andy Hung920f6572022-10-06 12:09:49 -07009974 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009975 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9976 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009977 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009978}
9979
Andy Hungee58e4a2023-07-07 13:47:37 -07009980void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009981{
9982 if (offset == 0) {
9983 return;
9984 }
9985 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009986 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009987 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009988 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009989 }
9990}
9991
Andy Hungee58e4a2023-07-07 13:47:37 -07009992void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009993{
9994 // This is the formula for calculating the temporary buffer size.
9995 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9996 // 1 full output buffer, regardless of the alignment of the available input.
9997 // The value is somewhat arbitrary, and could probably be even larger.
9998 // A larger value should allow more old data to be read after a track calls start(),
9999 // without increasing latency.
10000 //
10001 // Note this is independent of the maximum downsampling ratio permitted for capture.
10002 size_t minRsmpInFrames = mFrameCount * 7;
10003
10004 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10005 // capture history available to another client using the same session ID:
10006 // dimension the resampler input buffer accordingly.
10007
10008 // Get oldest client read position: getOldestFront_l() must be called before altering
10009 // mRsmpInRear, or mRsmpInFrames
10010 int32_t previousFront = getOldestFront_l();
10011 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10012 int32_t previousRear = mRsmpInRear;
10013 mRsmpInRear = 0;
10014
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010015 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010016 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010017 "resizeInputBuffer_l() called with invalid max shared history %d",
10018 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010019 if (maxSharedAudioHistoryMs != 0) {
10020 // resizeInputBuffer_l should never be called with a non zero shared history if the
10021 // buffer was not already allocated
10022 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10023 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10024 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10025 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010026 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010027 return;
10028 }
10029 mRsmpInFrames = rsmpInFrames;
10030 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010031 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010032 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10033 // initialized
10034 if (mRsmpInFrames < minRsmpInFrames) {
10035 mRsmpInFrames = minRsmpInFrames;
10036 }
10037 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10038
10039 // TODO optimize audio capture buffer sizes ...
10040 // Here we calculate the size of the sliding buffer used as a source
10041 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10042 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10043 // be better to have it derived from the pipe depth in the long term.
10044 // The current value is higher than necessary. However it should not add to latency.
10045
10046 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10047 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10048
10049 void *rsmpInBuffer;
10050 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10051 // if posix_memalign fails, will segv here.
10052 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10053
10054 // Copy audio history if any from old buffer before freeing it
10055 if (previousRear != 0) {
10056 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10057 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10058
10059 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10060 previousFront &= previousRsmpInFramesP2 - 1;
10061 size_t part1 = previousRsmpInFramesP2 - previousFront;
10062 if (part1 > (size_t) unread) {
10063 part1 = unread;
10064 }
10065 if (part1 != 0) {
10066 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10067 part1 * mFrameSize);
10068 mRsmpInRear = part1;
10069 part1 = unread - part1;
10070 if (part1 != 0) {
10071 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10072 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10073 mRsmpInRear += part1;
10074 }
10075 }
10076 // Update front for all clients according to new rear
10077 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10078 } else {
10079 mRsmpInRear = 0;
10080 }
10081 free(mRsmpInBuffer);
10082 mRsmpInBuffer = rsmpInBuffer;
10083}
10084
Andy Hungee58e4a2023-07-07 13:47:37 -070010085void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010086{
Andy Hung972bec12023-08-31 16:13:39 -070010087 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010088 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010089 if (record->getSource()) {
10090 mSource = record->getSource();
10091 }
Eric Laurent83b88082014-06-20 18:31:16 -070010092}
10093
Andy Hungee58e4a2023-07-07 13:47:37 -070010094void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010095{
Andy Hung972bec12023-08-31 16:13:39 -070010096 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010097 if (mSource == record->getSource()) {
10098 mSource = mInput;
10099 }
Eric Laurent83b88082014-06-20 18:31:16 -070010100 destroyTrack_l(record);
10101}
10102
Andy Hungee58e4a2023-07-07 13:47:37 -070010103void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010104{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010105 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010106 config->role = AUDIO_PORT_ROLE_SINK;
10107 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10108 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010109 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10110 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10111 config->flags.input = mInput->flags;
10112 }
Eric Laurent83b88082014-06-20 18:31:16 -070010113}
Eric Laurent1c333e22014-05-20 10:48:17 -070010114
Eric Laurent6acd1d42017-01-04 14:23:29 -080010115// ----------------------------------------------------------------------------
10116// Mmap
10117// ----------------------------------------------------------------------------
10118
Andy Hung7aa7d102023-07-07 15:58:48 -070010119// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10120// MmapPlaybackThread or MmapCaptureThread instance.
10121class MmapThreadHandle : public MmapStreamInterface {
10122public:
10123 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10124 ~MmapThreadHandle() override;
10125
10126 // MmapStreamInterface virtuals
10127 status_t createMmapBuffer(int32_t minSizeFrames,
10128 struct audio_mmap_buffer_info* info) final;
10129 status_t getMmapPosition(struct audio_mmap_position* position) final;
10130 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10131 status_t start(const AudioClient& client,
10132 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10133 status_t stop(audio_port_handle_t handle) final;
10134 status_t standby() final;
10135 status_t reportData(const void* buffer, size_t frameCount) final;
10136private:
10137 const sp<IAfMmapThread> mThread;
10138};
10139
10140/* static */
10141sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10142 const sp<IAfMmapThread>& mmapThread) {
10143 return sp<MmapThreadHandle>::make(mmapThread);
10144}
10145
10146MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010147 : mThread(thread)
10148{
Phil Burk9fabbf82017-08-03 12:02:00 -070010149 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150}
10151
Andy Hung7aa7d102023-07-07 15:58:48 -070010152// MmapStreamInterface could be directly implemented by MmapThread excepting this
10153// special handling on adapter dtor.
10154MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010155{
Phil Burk9fabbf82017-08-03 12:02:00 -070010156 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157}
10158
Andy Hung7aa7d102023-07-07 15:58:48 -070010159status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010160 struct audio_mmap_buffer_info *info)
10161{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010162 return mThread->createMmapBuffer(minSizeFrames, info);
10163}
10164
Andy Hung7aa7d102023-07-07 15:58:48 -070010165status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010166{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167 return mThread->getMmapPosition(position);
10168}
10169
Andy Hung7aa7d102023-07-07 15:58:48 -070010170status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010171 int64_t *timeNanos) {
10172 return mThread->getExternalPosition(position, timeNanos);
10173}
10174
Andy Hung7aa7d102023-07-07 15:58:48 -070010175status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010176 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010177{
jiabind1f1cb62020-03-24 11:57:57 -070010178 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179}
10180
Andy Hung7aa7d102023-07-07 15:58:48 -070010181status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010182{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010183 return mThread->stop(handle);
10184}
10185
Andy Hung7aa7d102023-07-07 15:58:48 -070010186status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010187{
Eric Laurent18b57012017-02-13 16:23:52 -080010188 return mThread->standby();
10189}
10190
Andy Hung7aa7d102023-07-07 15:58:48 -070010191status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10192{
jiabinfc791ee2023-02-15 19:43:40 +000010193 return mThread->reportData(buffer, frameCount);
10194}
10195
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196
Andy Hungee58e4a2023-07-07 13:47:37 -070010197MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010198 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010199 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010200 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010201 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010202 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010203 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010204 mActiveTracks(&this->mLocalLog),
10205 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10206 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207{
Eric Laurent18b57012017-02-13 16:23:52 -080010208 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010209 readHalParameters_l();
10210}
10211
Andy Hungee58e4a2023-07-07 13:47:37 -070010212void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213{
10214 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10215}
10216
Andy Hungee58e4a2023-07-07 13:47:37 -070010217void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010218{
Andy Hung8d31fd22023-06-26 19:20:57 -070010219 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010220 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010221 {
Andy Hung972bec12023-08-31 16:13:39 -070010222 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010223 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010224 activeTracks.add(t);
10225 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010226 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010227 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010228 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 stop(t->portId());
10230 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010231 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010232 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010233 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010234 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010235 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 }
10237}
10238
10239
Andy Hung8d672e02023-09-15 18:19:28 -070010240void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241 audio_stream_type_t streamType __unused,
10242 audio_session_t sessionId,
10243 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010244 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 audio_port_handle_t portId)
10246{
10247 mAttr = *attr;
10248 mSessionId = sessionId;
10249 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010250 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251 mPortId = portId;
10252}
10253
Andy Hungee58e4a2023-07-07 13:47:37 -070010254status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255 struct audio_mmap_buffer_info *info)
10256{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010257 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 if (mHalStream == 0) {
10259 return NO_INIT;
10260 }
Eric Laurent18b57012017-02-13 16:23:52 -080010261 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010262 return mHalStream->createMmapBuffer(minSizeFrames, info);
10263}
10264
Andy Hungee58e4a2023-07-07 13:47:37 -070010265status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010267 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010268 if (mHalStream == 0) {
10269 return NO_INIT;
10270 }
10271 return mHalStream->getMmapPosition(position);
10272}
10273
Andy Hungee58e4a2023-07-07 13:47:37 -070010274status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010275{
Eric Laurentdda206a2022-07-08 17:28:35 +020010276 // The HAL must receive track metadata before starting the stream
10277 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010278 status_t ret = mHalStream->start();
10279 if (ret != NO_ERROR) {
10280 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10281 return ret;
10282 }
Andy Hungcf10d742020-04-28 15:38:24 -070010283 if (mStandby) {
10284 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010285 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010286 mStandby = false;
10287 }
Eric Laurent331679c2018-04-16 17:03:16 -070010288 return NO_ERROR;
10289}
10290
Andy Hungee58e4a2023-07-07 13:47:37 -070010291status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010292 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 audio_port_handle_t *handle)
10294{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010295 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010296 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010297 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010298 if (mHalStream == 0) {
10299 return NO_INIT;
10300 }
10301
10302 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010303
Eric Laurentdda206a2022-07-08 17:28:35 +020010304 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010305 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010306 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010307 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010308 }
10309
10310 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10311
10312 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010313 AttributionSourceState adjAttributionSource;
10314 if (!com::android::media::audio::audioserver_permissions()) {
10315 adjAttributionSource = afutils::checkAttributionSourcePackage(
10316 client.attributionSource);
10317 } else {
10318 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10319 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10320 client.attributionSource,
10321 mAfThreadCallback->getPermissionProvider()
10322 );
10323 if (!validatedRes.has_value()) {
10324 ALOGE("MMAP client package validation fail: %s",
10325 validatedRes.error().toString8().c_str());
10326 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10327 }
10328 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10329 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010330
Andy Hung3f49ebb2023-09-19 14:48:41 -070010331 const auto localSessionId = mSessionId;
10332 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010333 if (isOutput()) {
10334 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10335 config.sample_rate = mSampleRate;
10336 config.channel_mask = mChannelMask;
10337 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010338 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010339 audio_output_flags_t flags =
10340 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010341 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010342 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010343 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010344 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010345 mutex().unlock();
10346 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10347 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010348 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010349 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010350 &config,
10351 flags,
10352 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010353 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010354 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010355 &isSpatialized,
Eric Laurent277a37e2024-07-29 18:37:52 +000010356 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010357 mutex().lock();
10358 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010359 ALOGD_IF(!secondaryOutputs.empty(),
10360 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010361 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010362 audio_config_base_t config;
10363 config.sample_rate = mSampleRate;
10364 config.channel_mask = mChannelMask;
10365 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010366 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010367 mutex().unlock();
10368 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010369 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010370 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010371 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010372 &config,
10373 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10374 &deviceId,
10375 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010376 mutex().lock();
10377 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010378 }
10379 // APM should not chose a different input or output stream for the same set of attributes
10380 // and audo configuration
10381 if (ret != NO_ERROR || io != mId) {
10382 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10383 __FUNCTION__, ret, io, mId);
10384 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385 }
10386
10387 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010388 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010389 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010390 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010391 } else {
jiabin09609032022-06-15 19:26:01 +000010392 {
10393 // Add the track record before starting input so that the silent status for the
10394 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010395 setClientSilencedState_l(portId, false /*silenced*/);
10396 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010397 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010398 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010399 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010400 }
10401
10402 // abort if start is rejected by audio policy manager
10403 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010404 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010405 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010406 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010407 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010408 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010409 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010410 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411 }
Andy Hungc5007f82023-08-29 14:26:09 -070010412 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010413 } else {
10414 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010415 }
jiabin09609032022-06-15 19:26:01 +000010416 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010417 return PERMISSION_DENIED;
10418 }
10419
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010420 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010421 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10422 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010423 mChannelMask, mSessionId, isOutput(),
10424 client.attributionSource,
Eric Laurent277a37e2024-07-29 18:37:52 +000010425 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010426 if (!isOutput()) {
10427 track->setSilenced_l(isClientSilenced_l(portId));
10428 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010429
Eric Laurent4eb58f12018-12-07 16:41:02 -080010430 if (isOutput()) {
10431 // force volume update when a new track is added
10432 mHalVolFloat = -1.0f;
10433 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010434 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010435 if (t->isSilenced_l()
10436 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010437 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010438 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010439 }
10440 }
10441
Eric Laurent6acd1d42017-01-04 14:23:29 -080010442 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010443 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010445 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010446 chain->incTrackCnt();
10447 chain->incActiveTrackCnt();
10448 }
10449
Andy Hungc2b11cb2020-04-22 09:04:01 -070010450 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010452
10453 if (mActiveTracks.size() == 1) {
10454 ret = exitStandby_l();
10455 }
10456
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457 broadcast_l();
10458
Eric Laurentdda206a2022-07-08 17:28:35 +020010459 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010460
Eric Laurentdda206a2022-07-08 17:28:35 +020010461 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462}
10463
Andy Hungee58e4a2023-07-07 13:47:37 -070010464status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010466 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010467 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468
10469 if (mHalStream == 0) {
10470 return NO_INIT;
10471 }
10472
Eric Laurenta54f1282017-07-01 19:39:32 -070010473 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010474 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010475 return NO_ERROR;
10476 }
10477
Andy Hung8d31fd22023-06-26 19:20:57 -070010478 sp<IAfMmapTrack> track;
10479 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010480 if (handle == t->portId()) {
10481 track = t;
10482 break;
10483 }
10484 }
10485 if (track == 0) {
10486 return BAD_VALUE;
10487 }
10488
10489 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010490 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491
Andy Hungc5007f82023-08-29 14:26:09 -070010492 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010494 AudioSystem::stopOutput(track->portId());
10495 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010496 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010497 AudioSystem::stopInput(track->portId());
10498 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499 }
Andy Hungc5007f82023-08-29 14:26:09 -070010500 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501
Andy Hung116bc262023-06-20 18:56:17 -070010502 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503 if (chain != 0) {
10504 chain->decActiveTrackCnt();
10505 chain->decTrackCnt();
10506 }
10507
Eric Laurentdda206a2022-07-08 17:28:35 +020010508 if (mActiveTracks.isEmpty()) {
10509 mHalStream->stop();
10510 }
10511
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 broadcast_l();
10513
Eric Laurent6acd1d42017-01-04 14:23:29 -080010514 return NO_ERROR;
10515}
10516
Andy Hungee58e4a2023-07-07 13:47:37 -070010517status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010518NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010519{
10520 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010521 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010522
10523 if (mHalStream == 0) {
10524 return NO_INIT;
10525 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010526 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010527 return INVALID_OPERATION;
10528 }
10529 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010530 if (!mStandby) {
10531 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010532 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010533 mStandby = true;
10534 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010535 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010536 return NO_ERROR;
10537}
10538
Andy Hungee58e4a2023-07-07 13:47:37 -070010539status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010540 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10541 return INVALID_OPERATION;
10542}
10543
Andy Hungee58e4a2023-07-07 13:47:37 -070010544void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545{
10546 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10547 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10548 mFormat = mHALFormat;
10549 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10550 result = mHalStream->getFrameSize(&mFrameSize);
10551 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010552 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10553 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010554 result = mHalStream->getBufferSize(&mBufferSize);
10555 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10556 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010557
Andy Hungcf10d742020-04-28 15:38:24 -070010558 // TODO: make a readHalParameters call?
10559 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010560 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010561 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010562 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10563 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10564 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10565 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10566 /*
10567 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10568 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10569 (int32_t)mHapticChannelMask)
10570 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10571 (int32_t)mHapticChannelCount)
10572 */
10573 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010574 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010575 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10576 (int32_t)mFrameCount) // sic - added HAL
10577 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578}
10579
Andy Hungee58e4a2023-07-07 13:47:37 -070010580bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581{
Andy Hungab65b182023-09-06 19:41:47 -070010582 {
10583 audio_utils::unique_lock _l(mutex());
10584 checkSilentMode_l();
10585 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010586
10587 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10588
10589 while (!exitPending())
10590 {
Andy Hung116bc262023-06-20 18:56:17 -070010591 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592
Andy Hung13850be2019-03-14 11:33:09 -070010593 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010594 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010595
Eric Laurent6acd1d42017-01-04 14:23:29 -080010596 if (mSignalPending) {
10597 // A signal was raised while we were unlocked
10598 mSignalPending = false;
10599 } else {
10600 if (mConfigEvents.isEmpty()) {
10601 // we're about to wait, flush the binder command buffer
10602 IPCThreadState::self()->flushCommands();
10603
10604 if (exitPending()) {
10605 break;
10606 }
10607
Eric Laurent6acd1d42017-01-04 14:23:29 -080010608 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010609 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010610 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010611 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010612
10613 checkSilentMode_l();
10614
10615 continue;
10616 }
10617 }
10618
10619 processConfigEvents_l();
10620
10621 processVolume_l();
10622
10623 checkInvalidTracks_l();
10624
Andy Hungab65b182023-09-06 19:41:47 -070010625 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010626
Kevin Rocard069c2712018-03-29 19:09:14 -070010627 updateMetadata_l();
10628
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010630 } // release Thread lock
10631
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010633 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010634 }
Andy Hung13850be2019-03-14 11:33:09 -070010635
10636 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637 unlockEffectChains(effectChains);
10638 // Effect chains will be actually deleted here if they were removed from
10639 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010640 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010642 mThreadloopExecutor.process(); // process any remaining deferred actions.
10643 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010644
10645 threadLoop_exit();
10646
10647 if (!mStandby) {
10648 threadLoop_standby();
10649 mStandby = true;
10650 }
10651
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652 ALOGV("Thread %p type %d exiting", this, mType);
10653 return false;
10654}
10655
Andy Hungc5007f82023-08-29 14:26:09 -070010656// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010657bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658 status_t& status)
10659{
10660 AudioParameter param = AudioParameter(keyValuePair);
10661 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010662 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010663 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010664 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010665 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010666 if (sendToHal) {
10667 status = mHalStream->setParameters(keyValuePair);
10668 } else {
10669 status = NO_ERROR;
10670 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671
10672 return false;
10673}
10674
Andy Hungee58e4a2023-07-07 13:47:37 -070010675String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676{
Andy Hung972bec12023-08-31 16:13:39 -070010677 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010678 String8 out_s8;
10679 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10680 return out_s8;
10681 }
Andy Hung920f6572022-10-06 12:09:49 -070010682 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010683}
10684
Andy Hungab65b182023-09-06 19:41:47 -070010685void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010686 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010687 sp<AudioIoDescriptor> desc;
10688 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010689 switch (event) {
10690 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010691 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010693 isInput = true;
10694 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010695 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010696 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010698 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10699 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010701 case AUDIO_INPUT_CLOSED:
10702 case AUDIO_OUTPUT_CLOSED:
10703 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010704 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010705 break;
10706 }
Andy Hungab65b182023-09-06 19:41:47 -070010707 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708}
10709
Andy Hungee58e4a2023-07-07 13:47:37 -070010710status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010712NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010713{
10714 status_t status = NO_ERROR;
10715
10716 // store new device and send to effects
10717 audio_devices_t type = AUDIO_DEVICE_NONE;
10718 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010719 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10720 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10721 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 if (isOutput()) {
10723 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010724 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10725 && !mAudioHwDev->supportsAudioPatches(),
10726 "Enumerated device type(%#x) must not be used "
10727 "as it does not support audio patches",
10728 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010729 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010730 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10731 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010732 }
10733 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010734 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010735 } else {
10736 type = patch->sources[0].ext.device.type;
10737 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010738 numDevices = mPatch.num_sources;
10739 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010740 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010741 }
10742
10743 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010744 if (isOutput()) {
10745 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10746 } else {
10747 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10748 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010749 }
10750
jiabinc52b1ff2019-10-31 17:20:42 -070010751 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010752 // store new source and send to effects
10753 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10754 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10755 for (size_t i = 0; i < mEffectChains.size(); i++) {
10756 mEffectChains[i]->setAudioSource_l(mAudioSource);
10757 }
10758 }
10759 }
10760
jiabin78b86f22024-02-22 00:39:29 +000010761 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10762 // okay to notify the client earlier before the new patch creation.
10763 if (mDeviceId != deviceId) {
10764 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10765 // The aaudioservice handle the routing changed event asynchronously. In that case,
10766 // it is safe to hold the lock here.
10767 callback->onRoutingChanged(deviceId);
10768 }
10769 }
10770
Eric Laurent6acd1d42017-01-04 14:23:29 -080010771 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010772 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10773 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010775 audio_port_config port;
10776 std::optional<audio_source_t> source;
10777 if (isOutput()) {
10778 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010780 port = patch->sources[0];
10781 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010782 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010783 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010784 *handle = AUDIO_PATCH_HANDLE_NONE;
10785 }
10786
jiabinc52b1ff2019-10-31 17:20:42 -070010787 if (numDevices == 0 || mDeviceId != deviceId) {
10788 if (isOutput()) {
10789 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10790 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010791 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010792 } else {
10793 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10794 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10795 }
jiabinc52b1ff2019-10-31 17:20:42 -070010796 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010797 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010799 // Force meteadata update after a route change
10800 mActiveTracks.setHasChanged();
10801
Eric Laurent6acd1d42017-01-04 14:23:29 -080010802 return status;
10803}
10804
Andy Hungee58e4a2023-07-07 13:47:37 -070010805status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010806{
10807 status_t status = NO_ERROR;
10808
jiabinc52b1ff2019-10-31 17:20:42 -070010809 mPatch = audio_patch{};
10810 mOutDeviceTypeAddrs.clear();
10811 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010812
10813 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10814 supportsAudioPatches : false;
10815
10816 if (supportsAudioPatches) {
10817 status = mHalDevice->releaseAudioPatch(handle);
10818 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010819 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010821 // Force meteadata update after a route change
10822 mActiveTracks.setHasChanged();
10823
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824 return status;
10825}
10826
Andy Hungee58e4a2023-07-07 13:47:37 -070010827void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010828NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010829{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010830 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010831 if (isOutput()) {
10832 config->role = AUDIO_PORT_ROLE_SOURCE;
10833 config->ext.mix.hw_module = mAudioHwDev->handle();
10834 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10835 } else {
10836 config->role = AUDIO_PORT_ROLE_SINK;
10837 config->ext.mix.hw_module = mAudioHwDev->handle();
10838 config->ext.mix.usecase.source = mAudioSource;
10839 }
10840}
10841
Andy Hungee58e4a2023-07-07 13:47:37 -070010842status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010843{
10844 audio_session_t session = chain->sessionId();
10845
10846 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10847 // Attach all tracks with same session ID to this chain.
10848 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010849 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010850 if (session == track->sessionId()) {
10851 chain->incTrackCnt();
10852 chain->incActiveTrackCnt();
10853 }
10854 }
10855
10856 chain->setThread(this);
10857 chain->setInBuffer(nullptr);
10858 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010859 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010860
10861 mEffectChains.add(chain);
10862 checkSuspendOnAddEffectChain_l(chain);
10863 return NO_ERROR;
10864}
10865
Andy Hungee58e4a2023-07-07 13:47:37 -070010866size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010867{
10868 audio_session_t session = chain->sessionId();
10869
10870 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10871
10872 for (size_t i = 0; i < mEffectChains.size(); i++) {
10873 if (chain == mEffectChains[i]) {
10874 mEffectChains.removeAt(i);
10875 // detach all active tracks from the chain
10876 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010877 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010878 if (session == track->sessionId()) {
10879 chain->decActiveTrackCnt();
10880 chain->decTrackCnt();
10881 }
10882 }
10883 break;
10884 }
10885 }
10886 return mEffectChains.size();
10887}
10888
Andy Hungee58e4a2023-07-07 13:47:37 -070010889void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010890{
10891 mHalStream->standby();
10892}
10893
Andy Hungee58e4a2023-07-07 13:47:37 -070010894void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010895{
Phil Burk7dce7282017-09-27 13:51:41 -070010896 // Do not call callback->onTearDown() because it is redundant for thread exit
10897 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010898}
10899
Andy Hungee58e4a2023-07-07 13:47:37 -070010900status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010901{
10902 return BAD_VALUE;
10903}
10904
Andy Hungee58e4a2023-07-07 13:47:37 -070010905bool MmapThread::isValidSyncEvent(
10906 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010907{
10908 return false;
10909}
10910
Andy Hungee58e4a2023-07-07 13:47:37 -070010911status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912 const effect_descriptor_t *desc, audio_session_t sessionId)
10913{
10914 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010915 if (audio_is_global_session(sessionId)) {
10916 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010917 desc->name, mThreadName);
10918 return BAD_VALUE;
10919 }
10920
10921 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10922 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10923 desc->name);
10924 return BAD_VALUE;
10925 }
10926 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010927 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10928 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010929 return BAD_VALUE;
10930 }
10931
10932 // Only allow effects without processing load or latency
10933 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10934 return BAD_VALUE;
10935 }
10936
Andy Hung116bc262023-06-20 18:56:17 -070010937 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010938 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10939 return BAD_VALUE;
10940 }
10941
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010943}
10944
Andy Hungee58e4a2023-07-07 13:47:37 -070010945void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010946{
Andy Hung8d31fd22023-06-26 19:20:57 -070010947 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010948 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010949 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10950 // The aaudioservice handle the routing changed event asynchronously. In that case,
10951 // it is safe to hold the lock here.
10952 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10953 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010954 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10955 mNoCallbackWarningCount++;
10956 }
10957 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010958 }
10959 }
10960}
10961
Andy Hungee58e4a2023-07-07 13:47:37 -070010962void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010963{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010964 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10965 mAttr.content_type, mAttr.usage, mAttr.source);
10966 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010967 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010968 dprintf(fd, " No active clients\n");
10969 }
10970}
10971
Andy Hungee58e4a2023-07-07 13:47:37 -070010972void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010973{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010976 dprintf(fd, " %zu Tracks\n", numtracks);
10977 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010978 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010979 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010980 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010981 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010982 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010983 result.append(prefix);
10984 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010985 }
10986 } else {
10987 dprintf(fd, "\n");
10988 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010989 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010990}
10991
Andy Hungee58e4a2023-07-07 13:47:37 -070010992/* static */
10993sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010994 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010995 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010996 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010997}
10998
10999MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011000 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011001 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011002 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011003 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011004 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011005{
11006 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11007 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011008 mMasterVolume = afThreadCallback->masterVolume_l();
11009 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent277a37e2024-07-29 18:37:52 +000011010
11011 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11012 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11013 mStreamTypes[stream].volume = 0.0f;
11014 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011015 }
Eric Laurent277a37e2024-07-29 18:37:52 +000011016 // Audio patch and call assistant volume are always max
11017 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11018 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11019 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11020 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
11021
Eric Laurent6acd1d42017-01-04 14:23:29 -080011022 if (mAudioHwDev) {
11023 if (mAudioHwDev->canSetMasterVolume()) {
11024 mMasterVolume = 1.0;
11025 }
11026
11027 if (mAudioHwDev->canSetMasterMute()) {
11028 mMasterMute = false;
11029 }
11030 }
11031}
11032
Andy Hungee58e4a2023-07-07 13:47:37 -070011033void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011034 audio_stream_type_t streamType,
11035 audio_session_t sessionId,
11036 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011037 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011038 audio_port_handle_t portId)
11039{
Andy Hung8d672e02023-09-15 18:19:28 -070011040 audio_utils::lock_guard l(mutex());
11041 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011042 mStreamType = streamType;
11043}
11044
Andy Hungee58e4a2023-07-07 13:47:37 -070011045AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011046{
Andy Hung972bec12023-08-31 16:13:39 -070011047 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011048 AudioStreamOut *output = mOutput;
11049 mOutput = NULL;
11050 return output;
11051}
11052
Andy Hungee58e4a2023-07-07 13:47:37 -070011053void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011054{
Andy Hung972bec12023-08-31 16:13:39 -070011055 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011056 // Don't apply master volume in SW if our HAL can do it for us.
11057 if (mAudioHwDev &&
11058 mAudioHwDev->canSetMasterVolume()) {
11059 mMasterVolume = 1.0;
11060 } else {
11061 mMasterVolume = value;
11062 }
11063}
11064
Andy Hungee58e4a2023-07-07 13:47:37 -070011065void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011066{
Andy Hung972bec12023-08-31 16:13:39 -070011067 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011068 // Don't apply master mute in SW if our HAL can do it for us.
11069 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11070 mMasterMute = false;
11071 } else {
11072 mMasterMute = muted;
11073 }
11074}
11075
Andy Hungee58e4a2023-07-07 13:47:37 -070011076void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077{
Andy Hung972bec12023-08-31 16:13:39 -070011078 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011079 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011080 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011081 broadcast_l();
11082 }
11083}
11084
Andy Hungee58e4a2023-07-07 13:47:37 -070011085float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011086{
Andy Hung972bec12023-08-31 16:13:39 -070011087 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011088 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011089}
11090
Andy Hungee58e4a2023-07-07 13:47:37 -070011091void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092{
Andy Hung972bec12023-08-31 16:13:39 -070011093 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011094 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011095 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011096 broadcast_l();
11097 }
11098}
11099
Andy Hungee58e4a2023-07-07 13:47:37 -070011100void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011101{
Andy Hung972bec12023-08-31 16:13:39 -070011102 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011103 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011104 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011105 track->invalidate();
11106 }
11107 broadcast_l();
11108 }
11109}
11110
Andy Hungee58e4a2023-07-07 13:47:37 -070011111void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011112{
Andy Hung972bec12023-08-31 16:13:39 -070011113 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011114 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011115 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011116 if (portIds.find(track->portId()) != portIds.end()) {
11117 track->invalidate();
11118 trackMatch = true;
11119 portIds.erase(track->portId());
11120 }
11121 if (portIds.empty()) {
11122 break;
11123 }
11124 }
11125 if (trackMatch) {
11126 broadcast_l();
11127 }
11128}
11129
Andy Hungee58e4a2023-07-07 13:47:37 -070011130void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011131NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011132{
Eric Laurent277a37e2024-07-29 18:37:52 +000011133 float volume;
11134
11135 if (mMasterMute || streamMuted_l()) {
11136 volume = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011137 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +000011138 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011139 }
Eric Laurent277a37e2024-07-29 18:37:52 +000011140
Eric Laurent6acd1d42017-01-04 14:23:29 -080011141 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011142 // Convert volumes from float to 8.24
11143 uint32_t vol = (uint32_t)(volume * (1 << 24));
11144
11145 // Delegate volume control to effect in track effect chain if needed
11146 // only one effect chain can be present on DirectOutputThread, so if
11147 // there is one, the track is connected to it
11148 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011149 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011150 volume = (float)vol / (1 << 24);
11151 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011152 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011153 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11154 mHalVolFloat = volume; // HW volume control worked, so update value.
11155 mNoCallbackWarningCount = 0;
11156 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011157 sp<MmapStreamCallback> callback = mCallback.promote();
11158 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011159 mHalVolFloat = volume; // SW volume control worked, so update value.
11160 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011161 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011162 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011163 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011164 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011165 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11166 ALOGW("Could not set MMAP stream volume: no volume callback!");
11167 mNoCallbackWarningCount++;
11168 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011169 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011170 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011171 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011172 track->setMetadataHasChanged();
Eric Laurent277a37e2024-07-29 18:37:52 +000011173 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11174 /*muteState=*/{mMasterMute,
11175 streamVolume_l() == 0.f,
11176 streamMuted_l(),
11177 // TODO(b/241533526): adjust logic to include mute from AppOps
11178 false /*muteFromPlaybackRestricted*/,
11179 false /*muteFromClientVolume*/,
11180 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011181 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011182 }
11183}
11184
Andy Hungee58e4a2023-07-07 13:47:37 -070011185ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011186{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011187 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011188 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011189 }
11190 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011191 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011192 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011193 playback_track_metadata_v7_t trackMetadata;
11194 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011195 .usage = track->attributes().usage,
11196 .content_type = track->attributes().content_type,
11197 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011198 };
11199 trackMetadata.channel_mask = track->channelMask(),
11200 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11201 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011202 }
11203 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011204
11205 MetadataUpdate change;
11206 change.playbackMetadataUpdate = metadata.tracks;
11207 return change;
11208};
Kevin Rocard069c2712018-03-29 19:09:14 -070011209
Andy Hungee58e4a2023-07-07 13:47:37 -070011210void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011211{
11212 if (!mMasterMute) {
11213 char value[PROPERTY_VALUE_MAX];
11214 if (property_get("ro.audio.silent", value, "0") > 0) {
11215 char *endptr;
11216 unsigned long ul = strtoul(value, &endptr, 0);
11217 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011218 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011219 // The setprop command will not allow a property to be changed after
11220 // the first time it is set, so we don't have to worry about un-muting.
11221 setMasterMute_l(true);
11222 }
11223 }
11224 }
11225}
11226
Andy Hungee58e4a2023-07-07 13:47:37 -070011227void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011228{
11229 MmapThread::toAudioPortConfig(config);
11230 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11231 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11232 config->flags.output = mOutput->flags;
11233 }
11234}
11235
Andy Hungee58e4a2023-07-07 13:47:37 -070011236status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011237 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011238{
11239 if (mOutput == nullptr) {
11240 return NO_INIT;
11241 }
11242 struct timespec timestamp;
11243 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11244 if (status == NO_ERROR) {
11245 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11246 }
11247 return status;
11248}
11249
Andy Hungee58e4a2023-07-07 13:47:37 -070011250status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011251 // Send to MelProcessor for sound dose measurement.
11252 auto processor = mMelProcessor.load();
11253 if (processor) {
11254 processor->process(buffer, frameCount * mFrameSize);
11255 }
11256
jiabinfc791ee2023-02-15 19:43:40 +000011257 return NO_ERROR;
11258}
11259
Andy Hungc5007f82023-08-29 14:26:09 -070011260// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011261void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011262 const sp<audio_utils::MelProcessor>& processor)
11263{
11264 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011265 mMelProcessor.store(processor);
11266 if (processor) {
11267 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011268 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011269
11270 // no need to update output format for MMapPlaybackThread since it is
11271 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011272}
11273
Andy Hungc5007f82023-08-29 14:26:09 -070011274// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011275void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011276{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011277 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11278 auto melProcessor = mMelProcessor.load();
11279 if (melProcessor != nullptr) {
11280 melProcessor->pause();
11281 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011282}
11283
Andy Hungee58e4a2023-07-07 13:47:37 -070011284void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011285{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011286 MmapThread::dumpInternals_l(fd, args);
Eric Laurent277a37e2024-07-29 18:37:52 +000011287
11288 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11289 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011290 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11291}
11292
Andy Hungee58e4a2023-07-07 13:47:37 -070011293/* static */
11294sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011295 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011296 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011297 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011298}
11299
11300MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011301 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011302 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011303 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011304 mInput(input)
11305{
11306 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11307 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11308}
11309
Andy Hungee58e4a2023-07-07 13:47:37 -070011310status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011311{
Phil Burkf054fc32018-12-06 09:45:59 -080011312 {
11313 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011314 if (mInput != nullptr && mInput->stream != nullptr) {
11315 mInput->stream->setGain(1.0f);
11316 }
11317 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011318 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011319}
11320
Andy Hungee58e4a2023-07-07 13:47:37 -070011321AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011322{
Andy Hung972bec12023-08-31 16:13:39 -070011323 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011324 AudioStreamIn *input = mInput;
11325 mInput = NULL;
11326 return input;
11327}
Kevin Rocard069c2712018-03-29 19:09:14 -070011328
Andy Hungee58e4a2023-07-07 13:47:37 -070011329void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011330{
11331 bool changed = false;
11332 bool silenced = false;
11333
11334 sp<MmapStreamCallback> callback = mCallback.promote();
11335 if (callback == 0) {
11336 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11337 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11338 mNoCallbackWarningCount++;
11339 }
11340 }
11341
11342 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11343 // track is silenced and unmute otherwise
11344 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11345 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11346 changed = true;
11347 silenced = mActiveTracks[i]->isSilenced_l();
11348 }
11349 }
11350
11351 if (changed) {
11352 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11353 }
11354}
11355
Andy Hungee58e4a2023-07-07 13:47:37 -070011356ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011357{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011358 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011359 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011360 }
11361 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011362 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011363 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011364 record_track_metadata_v7_t trackMetadata;
11365 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011366 .source = track->attributes().source,
11367 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011368 };
11369 trackMetadata.channel_mask = track->channelMask(),
11370 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11371 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011372 }
11373 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011374 MetadataUpdate change;
11375 change.recordMetadataUpdate = metadata.tracks;
11376 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011377}
11378
Andy Hungee58e4a2023-07-07 13:47:37 -070011379void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011380{
Andy Hung972bec12023-08-31 16:13:39 -070011381 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011382 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011383 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011384 mActiveTracks[i]->setSilenced_l(silenced);
11385 broadcast_l();
11386 }
11387 }
jiabin09609032022-06-15 19:26:01 +000011388 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011389}
11390
Andy Hungee58e4a2023-07-07 13:47:37 -070011391void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011392{
11393 MmapThread::toAudioPortConfig(config);
11394 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11395 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11396 config->flags.input = mInput->flags;
11397 }
11398}
11399
Andy Hungee58e4a2023-07-07 13:47:37 -070011400status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011401 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011402{
11403 if (mInput == nullptr) {
11404 return NO_INIT;
11405 }
11406 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11407}
11408
jiabinc658e452022-10-21 20:52:21 +000011409// ----------------------------------------------------------------------------
11410
Andy Hungee58e4a2023-07-07 13:47:37 -070011411/* static */
11412sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011413 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011414 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011415 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011416}
11417
Andy Hung583043b2023-07-17 17:05:00 -070011418BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011419 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011420 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011421
Andy Hungee58e4a2023-07-07 13:47:37 -070011422PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011423 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011424 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11425 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011426 float volumeLeft = 1.0f;
11427 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011428 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11429 bitPerfectTrack != nullptr) {
11430 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011431 mAudioMixer->setParameter(
11432 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11433 mAudioMixer->setParameter(
11434 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11435 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011436 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011437 mIsBitPerfect = true;
11438 } else {
11439 mIsBitPerfect = false;
11440 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11441 // active.
11442 for (const auto& track : mActiveTracks) {
11443 const int trackId = track->id();
11444 mAudioMixer->setParameter(
11445 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11446 }
11447 }
jiabin76d94692022-12-15 21:51:21 +000011448 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11449 mVolumeLeft = volumeLeft;
11450 mVolumeRight = volumeRight;
11451 setVolumeForOutput_l(volumeLeft, volumeRight);
11452 }
jiabinc658e452022-10-21 20:52:21 +000011453 return result;
11454}
11455
Andy Hungee58e4a2023-07-07 13:47:37 -070011456void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011457 MixerThread::threadLoop_mix();
11458 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11459}
11460
jiabin220eea12024-05-17 17:55:20 +000011461void BitPerfectThread::setTracksInternalMute(
11462 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11463 for (auto& track : mTracks) {
11464 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11465 track->setInternalMute(it->second);
11466 tracksInternalMute->erase(it);
11467 }
11468 }
11469}
11470
11471sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11472 if (com::android::media::audioserver::
11473 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11474 sp<IAfTrack> bitPerfectTrack = nullptr;
11475 bool allOtherTracksMuted = true;
11476 // Return the bit perfect track if all other tracks are muted
11477 for (const auto& track : mActiveTracks) {
11478 if (track->isBitPerfect()) {
11479 bitPerfectTrack = track;
11480 } else if (track->getFinalVolume() != 0.f) {
11481 allOtherTracksMuted = false;
11482 if (bitPerfectTrack != nullptr) {
11483 break;
11484 }
11485 }
11486 }
11487 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11488 } else {
11489 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11490 return mActiveTracks[0];
11491 }
11492 }
11493 return nullptr;
11494}
11495
Glenn Kasten63238ef2015-03-02 15:50:29 -080011496} // namespace android