blob: 400613a125c5def6e7778e7c877b5b5824761ed9 [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:
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001581 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are supported on spatializer mixer, but only
1582 // the spatialized track have global effects applied for now.
Eric Laurentb62d0362021-10-26 17:40:18 +02001583 // 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) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001586 ALOGD("%s: global effect %s on spatializer thread %s", __func__, desc->name,
1587 mThreadName);
Eric Laurentb62d0362021-10-26 17:40:18 +02001588 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1589 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001590 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001591 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1592 break;
1593 }
1594 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1595 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1596 __func__, desc->name);
1597 return BAD_VALUE;
1598 }
1599 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1600 // only post processing on output stage session
1601 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1602 ALOGW("%s: non post processing effect %s not allowed on device session",
1603 __func__, desc->name);
1604 return BAD_VALUE;
1605 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001606 }
1607 break;
jiabinc658e452022-10-21 20:52:21 +00001608 case BIT_PERFECT:
1609 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1610 // Allow HW accelerated effects of tunnel type
1611 break;
1612 }
1613 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1614 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1615 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1616 // 3) there is any bit-perfect track with the given session id.
1617 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1618 sessionId == AUDIO_SESSION_DEVICE) {
1619 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1620 __func__, desc->name, mThreadName);
1621 return BAD_VALUE;
1622 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1623 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1624 __func__, desc->name, sessionId);
1625 return BAD_VALUE;
1626 }
1627 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001628 default:
1629 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1630 }
1631
1632 return NO_ERROR;
1633}
1634
Andy Hungc5007f82023-08-29 14:26:09 -07001635// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001636sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001637 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001638 const sp<IEffectClient>& effectClient,
1639 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001640 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001641 effect_descriptor_t *desc,
1642 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001643 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001644 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001645 bool probe,
1646 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001647{
Andy Hung116bc262023-06-20 18:56:17 -07001648 sp<IAfEffectModule> effect;
1649 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001650 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001651 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001652 bool chainCreated = false;
1653 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001654 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001655
1656 lStatus = initCheck();
1657 if (lStatus != NO_ERROR) {
1658 ALOGW("createEffect_l() Audio driver not initialized.");
1659 goto Exit;
1660 }
1661
Eric Laurent81784c32012-11-19 14:55:58 -08001662 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1663
Andy Hungc5007f82023-08-29 14:26:09 -07001664 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001665 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001666
Eric Laurent4c415062016-06-17 16:14:16 -07001667 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001668 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001669 goto Exit;
1670 }
1671
Eric Laurent81784c32012-11-19 14:55:58 -08001672 // check for existing effect chain with the requested audio session
1673 chain = getEffectChain_l(sessionId);
1674 if (chain == 0) {
1675 // create a new chain for this session
1676 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001677 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001678 addEffectChain_l(chain);
1679 chain->setStrategy(getStrategyForSession_l(sessionId));
1680 chainCreated = true;
1681 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001682 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001683 }
1684
1685 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1686
1687 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001688 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001689 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001690 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001691 if (lStatus != NO_ERROR) {
1692 goto Exit;
1693 }
1694 effectCreated = true;
1695
jiabinc52b1ff2019-10-31 17:20:42 -07001696 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001697 effect->setDevices(outDeviceTypeAddrs());
1698 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001699 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001700 effect->setAudioSource(mAudioSource);
1701 }
jiabin1319f5a2021-03-30 22:21:24 +00001702 if (effect->isHapticGenerator()) {
1703 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1704 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001705 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001706 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001707 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001708 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001709 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001710 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001711 }
1712 }
Eric Laurent81784c32012-11-19 14:55:58 -08001713 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001714 handle = IAfEffectHandle::create(
1715 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001716 lStatus = handle->initCheck();
1717 if (lStatus == OK) {
1718 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001719 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001720 }
Eric Laurent81784c32012-11-19 14:55:58 -08001721 if (enabled != NULL) {
1722 *enabled = (int)effect->isEnabled();
1723 }
1724 }
1725
1726Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001727 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001728 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001729 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001730 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001731 }
Eric Laurent81784c32012-11-19 14:55:58 -08001732 if (chainCreated) {
1733 removeEffectChain_l(chain);
1734 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001735 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001736 }
1737
Glenn Kasten9156ef32013-08-06 15:39:08 -07001738 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001739 return handle;
1740}
1741
Andy Hungee58e4a2023-07-07 13:47:37 -07001742void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001743 bool unpinIfLast)
1744{
1745 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001746 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 {
Andy Hung972bec12023-08-31 16:13:39 -07001748 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001749 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001750 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001751 return;
1752 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001753 effect = effectBase->asEffectModule();
1754 if (effect == nullptr) {
1755 return;
1756 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001757 // restore suspended effects if the disconnected handle was enabled and the last one.
1758 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1759 if (remove) {
1760 removeEffect_l(effect, true);
1761 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001762 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001763 }
1764 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001765 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001766 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001767 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001768 }
1769 }
1770}
1771
Andy Hungee58e4a2023-07-07 13:47:37 -07001772void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001773 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001774 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001775 broadcast_l();
1776 }
1777 if (!effect->isOffloadable()) {
1778 if (mType == ThreadBase::OFFLOAD) {
1779 PlaybackThread *t = (PlaybackThread *)this;
1780 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1781 }
1782 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001783 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001784 }
1785 }
1786}
1787
Andy Hungee58e4a2023-07-07 13:47:37 -07001788void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001789 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001790 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001791 broadcast_l();
1792 }
1793}
1794
Andy Hungee58e4a2023-07-07 13:47:37 -07001795sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001796 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001797{
Andy Hung972bec12023-08-31 16:13:39 -07001798 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001799 return getEffect_l(sessionId, effectId);
1800}
1801
Andy Hungee58e4a2023-07-07 13:47:37 -07001802sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001803 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001804{
Andy Hung116bc262023-06-20 18:56:17 -07001805 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001806 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1807}
1808
Andy Hungee58e4a2023-07-07 13:47:37 -07001809std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001810{
Andy Hung116bc262023-06-20 18:56:17 -07001811 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001812 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001813}
1814
Andy Hung972bec12023-08-31 16:13:39 -07001815// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1816// ThreadBase::mutex() held
1817status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001818{
1819 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001820 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001821 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001822 bool chainCreated = false;
1823
Eric Laurent5baf2af2013-09-12 17:37:00 -07001824 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001825 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1826 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001827
Eric Laurent81784c32012-11-19 14:55:58 -08001828 if (chain == 0) {
1829 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001830 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001831 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001832 addEffectChain_l(chain);
1833 chain->setStrategy(getStrategyForSession_l(sessionId));
1834 chainCreated = true;
1835 }
Andy Hung972bec12023-08-31 16:13:39 -07001836 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001837
1838 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001839 ALOGW("%s: %p effect %s already present in chain %p",
1840 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001841 return BAD_VALUE;
1842 }
1843
Shunkai Yaod125e402024-01-20 03:19:06 +00001844 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001845
Shunkai Yao29d10572024-03-19 04:31:47 +00001846 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001847 if (status != NO_ERROR) {
1848 if (chainCreated) {
1849 removeEffectChain_l(chain);
1850 }
1851 return status;
1852 }
1853
jiabin8f278ee2019-11-11 12:16:27 -08001854 effect->setDevices(outDeviceTypeAddrs());
1855 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001856 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001857 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001858
Eric Laurent81784c32012-11-19 14:55:58 -08001859 return NO_ERROR;
1860}
1861
Andy Hungee58e4a2023-07-07 13:47:37 -07001862void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001863
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001864 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001865 effect_descriptor_t desc = effect->desc();
1866 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1867 detachAuxEffect_l(effect->id());
1868 }
1869
Andy Hung116bc262023-06-20 18:56:17 -07001870 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001871 if (chain != 0) {
1872 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001873 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001874 removeEffectChain_l(chain);
1875 }
1876 } else {
1877 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1878 }
1879}
1880
Shunkai Yaof4847652024-01-12 00:25:20 +00001881void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1882 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
1884 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001885 for (const auto& effectChain : effectChains) {
1886 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001887 }
1888}
1889
Shunkai Yaof4847652024-01-12 00:25:20 +00001890void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1891 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001892{
Shunkai Yaof4847652024-01-12 00:25:20 +00001893 for (const auto& effectChain : effectChains) {
1894 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001895 }
1896}
1897
Andy Hungee58e4a2023-07-07 13:47:37 -07001898sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001899{
Andy Hung972bec12023-08-31 16:13:39 -07001900 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001901 return getEffectChain_l(sessionId);
1902}
1903
Andy Hungee58e4a2023-07-07 13:47:37 -07001904sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001905 const
Eric Laurent81784c32012-11-19 14:55:58 -08001906{
1907 size_t size = mEffectChains.size();
1908 for (size_t i = 0; i < size; i++) {
1909 if (mEffectChains[i]->sessionId() == sessionId) {
1910 return mEffectChains[i];
1911 }
1912 }
1913 return 0;
1914}
1915
Andy Hungee58e4a2023-07-07 13:47:37 -07001916void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001917{
Andy Hung972bec12023-08-31 16:13:39 -07001918 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001919 size_t size = mEffectChains.size();
1920 for (size_t i = 0; i < size; i++) {
1921 mEffectChains[i]->setMode_l(mode);
1922 }
1923}
1924
Andy Hungee58e4a2023-07-07 13:47:37 -07001925void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001926{
1927 config->type = AUDIO_PORT_TYPE_MIX;
1928 config->ext.mix.handle = mId;
1929 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001930 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001931 config->channel_mask = mChannelMask;
1932 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1933 AUDIO_PORT_CONFIG_FORMAT;
1934}
1935
Andy Hungee58e4a2023-07-07 13:47:37 -07001936void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001937{
Andy Hung972bec12023-08-31 16:13:39 -07001938 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001939 if (mSystemReady) {
1940 return;
1941 }
1942 mSystemReady = true;
1943
1944 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1945 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1946 }
1947 mPendingConfigEvents.clear();
1948}
1949
Andy Hungdae27702016-10-31 14:01:16 -07001950template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001951ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001952 ssize_t index = mActiveTracks.indexOf(track);
1953 if (index >= 0) {
1954 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1955 return index;
1956 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001957 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001958 mActiveTracksGeneration++;
1959 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001960 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001961 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001962 return mActiveTracks.add(track);
1963}
1964
1965template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001966ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001967 ssize_t index = mActiveTracks.remove(track);
1968 if (index < 0) {
1969 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1970 return index;
1971 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001972 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001973 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001974 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001975 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001976 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001977#ifdef TEE_SINK
1978 track->dumpTee(-1 /* fd */, "_REMOVE");
1979#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001980 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001981 return index;
1982}
1983
1984template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001985void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001986 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001987 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001988 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001989 }
1990 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001991 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001992 mActiveTracks.clear();
1993 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001994}
1995
1996template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001997void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001998 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001999 // Updates ActiveTracks client uids to the thread wakelock.
2000 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2001 thread->updateWakeLockUids_l(getWakeLockUids());
2002 mLastActiveTracksGeneration = mActiveTracksGeneration;
2003 }
Andy Hungdae27702016-10-31 14:01:16 -07002004}
Eric Laurent83b88082014-06-20 18:31:16 -07002005
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002006template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002007bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002008 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002009 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002010
2011 for (const sp<T> &track : mActiveTracks) {
2012 // Do not short-circuit as all hasChanged states must be reset
2013 // as all the metadata are going to be sent
2014 hasChanged |= track->readAndClearHasChanged();
2015 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002016 return hasChanged;
2017}
2018
2019template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002020void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002021 const char *funcName, const sp<T> &track) const {
2022 if (mLocalLog != nullptr) {
2023 String8 result;
2024 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002025 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002026 }
2027}
2028
Andy Hungee58e4a2023-07-07 13:47:37 -07002029void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002030{
2031 // Thread could be blocked waiting for async
2032 // so signal it to handle state changes immediately
2033 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2034 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2035 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002036 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002037}
2038
Andy Hungd0979812019-02-21 15:51:44 -08002039// Call only from threadLoop() or when it is idle.
2040// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002041void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002042NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002043{
2044 // Do not log if we have no stats.
2045 // We choose the timestamp verifier because it is the most likely item to be present.
2046 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2047 if (nstats == 0) {
2048 return;
2049 }
2050
2051 // Don't log more frequently than once per 12 hours.
2052 // We use BOOTTIME to include suspend time.
2053 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2054 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2055 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2056 return;
2057 }
2058
2059 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2060 mLastRecordedTimeNs = timeNs;
2061
Ray Essickf27e9872019-12-07 06:28:46 -08002062 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002063
2064#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2065
2066 // thread configuration
2067 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2068 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2069 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2070 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2071 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2072 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2073 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002074 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2075 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002076
2077 // thread statistics
2078 if (mIoJitterMs.getN() > 0) {
2079 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2080 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2081 }
2082 if (mProcessTimeMs.getN() > 0) {
2083 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2084 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2085 }
2086 const auto tsjitter = mTimestampVerifier.getJitterMs();
2087 if (tsjitter.getN() > 0) {
2088 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2089 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2090 }
2091 if (mLatencyMs.getN() > 0) {
2092 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2093 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2094 }
Robert Wu06db0a32021-08-10 19:05:34 +00002095 if (mMonopipePipeDepthStats.getN() > 0) {
2096 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2097 mMonopipePipeDepthStats.getMean());
2098 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2099 mMonopipePipeDepthStats.getStdDev());
2100 }
Andy Hungd0979812019-02-21 15:51:44 -08002101
2102 item->selfrecord();
2103}
2104
Andy Hungee58e4a2023-07-07 13:47:37 -07002105product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002106{
Andy Hung583043b2023-07-17 17:05:00 -07002107 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002108 return PRODUCT_STRATEGY_NONE;
2109 }
2110 return AudioSystem::getStrategyForStream(stream);
2111}
2112
Andy Hungc5007f82023-08-29 14:26:09 -07002113// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002114void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002115 const sp<audio_utils::MelProcessor>& /*processor*/)
2116{
2117 // Do nothing
2118 ALOGW("%s: ThreadBase does not support CSD", __func__);
2119}
2120
Andy Hungc5007f82023-08-29 14:26:09 -07002121// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002122void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002123{
2124 // Do nothing
2125 ALOGW("%s: ThreadBase does not support CSD", __func__);
2126}
2127
Eric Laurent81784c32012-11-19 14:55:58 -08002128// ----------------------------------------------------------------------------
2129// Playback
2130// ----------------------------------------------------------------------------
2131
Andy Hung583043b2023-07-17 17:05:00 -07002132PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002133 AudioStreamOut* output,
2134 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002135 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002136 bool systemReady,
2137 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002138 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002139 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002140 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002141 mMixerBuffer(NULL),
2142 mMixerBufferSize(0),
2143 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2144 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002145 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002146 mEffectBuffer(NULL),
2147 mEffectBufferSize(0),
2148 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2149 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002150 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002151 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002152 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002153 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002154 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002155 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002156 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002157 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002158 mMixerStatus(MIXER_IDLE),
2159 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002160 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002161 mBytesRemaining(0),
2162 mCurrentWriteLength(0),
2163 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002164 mWriteAckSequence(0),
2165 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002166 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002167 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002168 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002169 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002170 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002171 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002172 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002173{
Glenn Kastend7dca052015-03-05 16:05:54 -08002174 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002175 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002176
Andy Hungc5007f82023-08-29 14:26:09 -07002177 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002178 // it would be safer to explicitly pass initial masterVolume/masterMute as
2179 // parameter.
2180 //
2181 // If the HAL we are using has support for master volume or master mute,
2182 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2183 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002184 mMasterVolume = afThreadCallback->masterVolume_l();
2185 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002186 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002187 if (mOutput->audioHwDev->canSetMasterVolume()) {
2188 mMasterVolume = 1.0;
2189 }
2190
2191 if (mOutput->audioHwDev->canSetMasterMute()) {
2192 mMasterMute = false;
2193 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002194 mIsMsdDevice = strcmp(
2195 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002196 }
2197
Eric Laurentf1f22e72021-07-13 14:04:14 +02002198 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2199 mMixerChannelMask = mixerConfig->channel_mask;
2200 }
2201
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002202 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002203
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002204 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002205 && mMixerChannelMask != mChannelMask) {
2206 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2207 mChannelMask, mMixerChannelMask);
2208 }
2209
Andy Hungc8fddf32018-08-08 18:32:37 -07002210 // TODO: We may also match on address as well as device type for
2211 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002212 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002213 // TODO: This property should be ensure that only contains one single device type.
2214 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2215 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002216 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2217 : AUDIO_DEVICE_NONE));
2218 }
Eric Laurent277a37e2024-07-29 18:37:52 +00002219
2220 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2221 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2222 mStreamTypes[stream].volume = 0.0f;
2223 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002224 }
Eric Laurent277a37e2024-07-29 18:37:52 +00002225 // Audio patch and call assistant volume are always max
2226 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2227 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2228 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2229 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002230}
2231
Andy Hungee58e4a2023-07-07 13:47:37 -07002232PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002233{
Andy Hung583043b2023-07-17 17:05:00 -07002234 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002235 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002236 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002237 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002238 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002239}
2240
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002241// Thread virtuals
2242
Andy Hungee58e4a2023-07-07 13:47:37 -07002243void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002244{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002245 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002246 ALOGE("The stream is not open yet"); // This should not happen.
2247 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002248 // Callbacks take strong or weak pointers as a parameter.
2249 // Since PlaybackThread passes itself as a callback handler, it can only
2250 // be done outside of the constructor. Creating weak and especially strong
2251 // pointers to a refcounted object in its own constructor is strongly
2252 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2253 // Even if a function takes a weak pointer, it is possible that it will
2254 // need to convert it to a strong pointer down the line.
2255 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2256 mOutput->stream->setCallback(this) == OK) {
2257 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002258 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002259 }
2260
jiabinf6eb4c32020-02-25 14:06:25 -08002261 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002262 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002263 }
2264 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002265 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002266 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002267}
2268
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002269// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002270void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002271{
2272 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002273 status_t result = mOutput->stream->exit();
2274 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002275}
2276
Andy Hungee58e4a2023-07-07 13:47:37 -07002277void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002278{
Eric Laurent81784c32012-11-19 14:55:58 -08002279 String8 result;
Eric Laurent277a37e2024-07-29 18:37:52 +00002280
2281 result.appendFormat(" Stream volumes in dB: ");
2282 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2283 const stream_type_t *st = &mStreamTypes[i];
2284 if (i > 0) {
2285 result.appendFormat(", ");
2286 }
2287 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2288 if (st->mute) {
2289 result.append("M");
Eric Laurent81784c32012-11-19 14:55:58 -08002290 }
2291 }
2292 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002293 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002294 result.clear();
2295
Eric Laurent81784c32012-11-19 14:55:58 -08002296 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2297 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002298 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002299 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002300
2301 size_t numtracks = mTracks.size();
2302 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002303 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002304 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002305 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002306 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002307 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002308 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002309 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002310 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002311 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002312 if (track != 0) {
2313 bool active = mActiveTracks.indexOf(track) >= 0;
2314 if (active) {
2315 numactiveseen++;
2316 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002317 result.append(prefix);
2318 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002319 }
2320 }
2321 } else {
2322 result.append("\n");
2323 }
2324 if (numactiveseen != numactive) {
2325 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002326 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002327 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002328 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002329 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002330 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002331 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002332 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002333 result.append(prefix);
2334 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002335 }
2336 }
2337 }
2338
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002339 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002340}
2341
Andy Hungee58e4a2023-07-07 13:47:37 -07002342void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002343{
Andy Hung04cb8f72020-03-20 13:44:33 -07002344 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002345 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002346 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2347 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002348 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2349 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2350 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2351 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002352 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002353 dprintf(fd, " Total writes: %d\n", mNumWrites);
2354 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2355 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002356 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002357 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002358 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002359 AudioStreamOut *output = mOutput;
2360 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002361 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002362 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002363 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2364 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2365 if (mPipeSink.get() != nullptr) {
2366 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2367 }
2368 if (output != nullptr) {
2369 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002370 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002371 }
Eric Laurent81784c32012-11-19 14:55:58 -08002372}
2373
Andy Hungc5007f82023-08-29 14:26:09 -07002374// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002375sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002376 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002378 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002379 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002380 audio_format_t format,
2381 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002382 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002383 size_t *pNotificationFrameCount,
2384 uint32_t notificationsPerBuffer,
2385 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002386 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002387 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002388 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002389 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002390 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002391 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002392 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002393 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002394 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002395 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002396 bool isBitPerfect,
Eric Laurent277a37e2024-07-29 18:37:52 +00002397 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002398{
Glenn Kasten74935e42013-12-19 08:56:45 -08002399 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002400 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002401 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002402 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002403 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002404 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002405 uint32_t sampleRate;
2406
2407 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2408 lStatus = BAD_VALUE;
2409 goto Exit;
2410 }
Eric Laurent21da6472017-11-09 16:29:26 -08002411
2412 if (*pSampleRate == 0) {
2413 *pSampleRate = mSampleRate;
2414 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002415 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002416
2417 // special case for FAST flag considered OK if fast mixer is present
2418 if (hasFastMixer()) {
2419 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2420 }
2421
2422 // Check if requested flags are compatible with output stream flags
2423 if ((*flags & outputFlags) != *flags) {
2424 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2425 *flags, outputFlags);
2426 *flags = (audio_output_flags_t)(*flags & outputFlags);
2427 }
Eric Laurent81784c32012-11-19 14:55:58 -08002428
jiabinc658e452022-10-21 20:52:21 +00002429 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002430 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002431 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002432 if (chain.get() != nullptr) {
2433 // Bit-perfect is required according to the configuration and preferred mixer
2434 // attributes, but it is not in the output flag from the client's request. Explicitly
2435 // adding bit-perfect flag to check the compatibility
2436 audio_output_flags_t flagsToCheck =
2437 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2438 chain->checkOutputFlagCompatibility(&flagsToCheck);
2439 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2440 ALOGE("%s cannot create track as there is data-processing effect attached to "
2441 "given session id(%d)", __func__, sessionId);
2442 lStatus = BAD_VALUE;
2443 goto Exit;
2444 }
2445 *flags = flagsToCheck;
2446 }
2447 }
2448
Eric Laurent81784c32012-11-19 14:55:58 -08002449 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002450 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002451 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002452 // PCM data
2453 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002454 // TODO: extract as a data library function that checks that a computationally
2455 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002456 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002457 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2458 (channelMask == AUDIO_CHANNEL_OUT_MONO
2459 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002460 // hardware sample rate
2461 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002462 // normal mixer has an associated fast mixer
2463 hasFastMixer() &&
2464 // there are sufficient fast track slots available
2465 (mFastTrackAvailMask != 0)
2466 // FIXME test that MixerThread for this fast track has a capable output HAL
2467 // FIXME add a permission test also?
2468 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002469 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2470 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002471 // read the fast track multiplier property the first time it is needed
2472 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2473 if (ok != 0) {
2474 ALOGE("%s pthread_once failed: %d", __func__, ok);
2475 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002476 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002477 }
Eric Laurent4c415062016-06-17 16:14:16 -07002478
2479 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002480 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002481 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002482 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002483 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002484 AUDIO_SESSION_OUTPUT_STAGE,
2485 AUDIO_SESSION_OUTPUT_MIX,
2486 sessionId,
2487 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002488 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002489 if (chain.get() != nullptr) {
2490 audio_output_flags_t old = *flags;
2491 chain->checkOutputFlagCompatibility(flags);
2492 if (old != *flags) {
2493 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2494 (int)session, (int)old, (int)*flags);
2495 }
Eric Laurent4c415062016-06-17 16:14:16 -07002496 }
2497 }
2498 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002499 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002500 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2501 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002502 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002503 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002504 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002505 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002506 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002507 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002508 audio_is_linear_pcm(format), channelMask, sampleRate,
2509 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002510 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002511 }
2512 }
Eric Laurent21da6472017-11-09 16:29:26 -08002513
2514 if (!audio_has_proportional_frames(format)) {
2515 if (sharedBuffer != 0) {
2516 // Same comment as below about ignoring frameCount parameter for set()
2517 frameCount = sharedBuffer->size();
2518 } else if (frameCount == 0) {
2519 frameCount = mNormalFrameCount;
2520 }
2521 if (notificationFrameCount != frameCount) {
2522 notificationFrameCount = frameCount;
2523 }
2524 } else if (sharedBuffer != 0) {
2525 // FIXME: Ensure client side memory buffers need
2526 // not have additional alignment beyond sample
2527 // (e.g. 16 bit stereo accessed as 32 bit frame).
2528 size_t alignment = audio_bytes_per_sample(format);
2529 if (alignment & 1) {
2530 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2531 alignment = 1;
2532 }
2533 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2534 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2535 if (channelCount > 1) {
2536 // More than 2 channels does not require stronger alignment than stereo
2537 alignment <<= 1;
2538 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002539 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002540 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002541 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002542 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002543 goto Exit;
2544 }
Eric Laurent21da6472017-11-09 16:29:26 -08002545
2546 // When initializing a shared buffer AudioTrack via constructors,
2547 // there's no frameCount parameter.
2548 // But when initializing a shared buffer AudioTrack via set(),
2549 // there _is_ a frameCount parameter. We silently ignore it.
2550 frameCount = sharedBuffer->size() / frameSize;
2551 } else {
2552 size_t minFrameCount = 0;
2553 // For fast tracks we try to respect the application's request for notifications per buffer.
2554 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2555 if (notificationsPerBuffer > 0) {
2556 // Avoid possible arithmetic overflow during multiplication.
2557 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2558 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2559 notificationsPerBuffer, mFrameCount);
2560 } else {
2561 minFrameCount = mFrameCount * notificationsPerBuffer;
2562 }
2563 }
2564 } else {
2565 // For normal PCM streaming tracks, update minimum frame count.
2566 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2567 // cover audio hardware latency.
2568 // This is probably too conservative, but legacy application code may depend on it.
2569 // If you change this calculation, also review the start threshold which is related.
2570 uint32_t latencyMs = latency_l();
2571 if (latencyMs == 0) {
2572 ALOGE("Error when retrieving output stream latency");
2573 lStatus = UNKNOWN_ERROR;
2574 goto Exit;
2575 }
2576
2577 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2578 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2579
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
Eric Laurent21da6472017-11-09 16:29:26 -08002581 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002582 frameCount = minFrameCount;
2583 }
Eric Laurent81784c32012-11-19 14:55:58 -08002584 }
Eric Laurent21da6472017-11-09 16:29:26 -08002585
2586 // Make sure that application is notified with sufficient margin before underrun.
2587 // The client can divide the AudioTrack buffer into sub-buffers,
2588 // and expresses its desire to server as the notification frame count.
2589 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2590 size_t maxNotificationFrames;
2591 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2592 // notify every HAL buffer, regardless of the size of the track buffer
2593 maxNotificationFrames = mFrameCount;
2594 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002595 // Triple buffer the notification period for a triple buffered mixer period;
2596 // otherwise, double buffering for the notification period is fine.
2597 //
2598 // TODO: This should be moved to AudioTrack to modify the notification period
2599 // on AudioTrack::setBufferSizeInFrames() changes.
2600 const int nBuffering =
2601 (uint64_t{frameCount} * mSampleRate)
2602 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2603
Eric Laurent21da6472017-11-09 16:29:26 -08002604 maxNotificationFrames = frameCount / nBuffering;
2605 // If client requested a fast track but this was denied, then use the smaller maximum.
2606 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2607 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2608 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2609 maxNotificationFrames = maxNotificationFramesFastDenied;
2610 }
2611 }
2612 }
2613 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2614 if (notificationFrameCount == 0) {
2615 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2616 maxNotificationFrames, frameCount);
2617 } else {
2618 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2619 notificationFrameCount, maxNotificationFrames, frameCount);
2620 }
2621 notificationFrameCount = maxNotificationFrames;
2622 }
2623 }
2624
Glenn Kasten74935e42013-12-19 08:56:45 -08002625 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002626 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002627
Glenn Kastenc3df8382014-03-13 15:05:25 -07002628 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002629 case BIT_PERFECT:
2630 if (isBitPerfect) {
2631 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2632 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2633 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2634 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2635 mChannelMask);
2636 lStatus = BAD_VALUE;
2637 goto Exit;
2638 }
2639 }
2640 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002641
2642 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002643 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002644 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002645 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2646 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002647 sampleRate, format, channelMask, mOutput, mFormat);
2648 lStatus = BAD_VALUE;
2649 goto Exit;
2650 }
2651 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002652 break;
2653
2654 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002655 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002656 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2657 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 sampleRate, format, channelMask, mOutput, mFormat);
2659 lStatus = BAD_VALUE;
2660 goto Exit;
2661 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002662 break;
2663
2664 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002665 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002666 ALOGE("createTrack_l() Bad parameter: format %#x \""
2667 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002668 format, mOutput, mFormat);
2669 lStatus = BAD_VALUE;
2670 goto Exit;
2671 }
Andy Hungcd044842014-08-07 11:04:34 -07002672 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002673 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2674 lStatus = BAD_VALUE;
2675 goto Exit;
2676 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002677 break;
2678
Eric Laurent81784c32012-11-19 14:55:58 -08002679 }
2680
2681 lStatus = initCheck();
2682 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002683 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002684 goto Exit;
2685 }
2686
Andy Hungc5007f82023-08-29 14:26:09 -07002687 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002688 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002689
2690 // all tracks in same audio session must share the same routing strategy otherwise
2691 // conflicts will happen when tracks are moved from one output to another by audio policy
2692 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002693 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002694 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002695 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002696 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002697 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002698 if (sessionId == t->sessionId() && strategy != actual) {
2699 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2700 strategy, actual);
2701 lStatus = BAD_VALUE;
2702 goto Exit;
2703 }
2704 }
2705 }
2706
Deeraj Soman2b515232024-05-14 12:58:24 +05302707 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2708 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002709 // dynamic audio policy.
2710 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302711 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002712 audio_output_flags_t trackFlags = *flags;
2713 if (mType == DIRECT) {
2714 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302715 } else if (mType == OFFLOAD) {
2716 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2717 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002718 }
jiabin94ed47c2023-07-27 23:34:20 +00002719 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002720
Andy Hung8d31fd22023-06-26 19:20:57 -07002721 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002722 channelMask, frameCount,
2723 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002724 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002725 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Eric Laurent277a37e2024-07-29 18:37:52 +00002726 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002727
Glenn Kasten03003332013-08-06 15:40:54 -07002728 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2729 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002730 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002731 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002732 goto Exit;
2733 }
2734 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002735 {
Andy Hung972bec12023-08-31 16:13:39 -07002736 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002737 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002738 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002739 }
2740 }
Eric Laurent81784c32012-11-19 14:55:58 -08002741
Andy Hung116bc262023-06-20 18:56:17 -07002742 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002743 if (chain != 0) {
2744 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2745 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002746 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002747 chain->incTrackCnt();
2748 }
2749
Eric Laurent05067782016-06-01 18:27:28 -07002750 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002751 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2752 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2753 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002754 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002755 }
2756 }
2757
2758 lStatus = NO_ERROR;
2759
2760Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002761 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002762 return track;
2763}
2764
Andy Hung1bc088a2018-02-09 15:57:31 -08002765template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002766ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002767{
Andy Hungc0691382018-09-12 18:01:57 -07002768 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002769 const ssize_t index = mTracks.remove(track);
2770 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002771 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002772 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002773 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002774 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002775 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002776 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002777 }
2778 return index;
2779}
2780
Andy Hungee58e4a2023-07-07 13:47:37 -07002781uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002782{
2783 return latency;
2784}
2785
Andy Hungee58e4a2023-07-07 13:47:37 -07002786uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002787{
Andy Hung972bec12023-08-31 16:13:39 -07002788 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002789 return latency_l();
2790}
Andy Hungee58e4a2023-07-07 13:47:37 -07002791uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002792NO_THREAD_SAFETY_ANALYSIS
2793// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002794{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002795 uint32_t latency;
2796 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2797 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002798 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002799 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002800}
2801
Andy Hungee58e4a2023-07-07 13:47:37 -07002802void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
Andy Hung972bec12023-08-31 16:13:39 -07002804 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002805 // Don't apply master volume in SW if our HAL can do it for us.
2806 if (mOutput && mOutput->audioHwDev &&
2807 mOutput->audioHwDev->canSetMasterVolume()) {
2808 mMasterVolume = 1.0;
2809 } else {
2810 mMasterVolume = value;
2811 }
2812}
2813
Andy Hungee58e4a2023-07-07 13:47:37 -07002814void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002815{
2816 mMasterBalance.store(balance);
2817}
2818
Andy Hungee58e4a2023-07-07 13:47:37 -07002819void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002820{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002821 if (isDuplicating()) {
2822 return;
2823 }
Andy Hung972bec12023-08-31 16:13:39 -07002824 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002825 // Don't apply master mute in SW if our HAL can do it for us.
2826 if (mOutput && mOutput->audioHwDev &&
2827 mOutput->audioHwDev->canSetMasterMute()) {
2828 mMasterMute = false;
2829 } else {
2830 mMasterMute = muted;
2831 }
2832}
2833
Andy Hungee58e4a2023-07-07 13:47:37 -07002834void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002835{
Andy Hung972bec12023-08-31 16:13:39 -07002836 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002837 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002838 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002839}
2840
Andy Hungee58e4a2023-07-07 13:47:37 -07002841void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002842{
Andy Hung972bec12023-08-31 16:13:39 -07002843 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002844 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002845 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002846}
2847
Andy Hungee58e4a2023-07-07 13:47:37 -07002848float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002849{
Andy Hung972bec12023-08-31 16:13:39 -07002850 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002851 return mStreamTypes[stream].volume;
2852}
2853
Andy Hungee58e4a2023-07-07 13:47:37 -07002854void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002855{
2856 mOutput->stream->setVolume(left, right);
2857}
2858
Andy Hungc5007f82023-08-29 14:26:09 -07002859// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002860status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002861{
2862 status_t status = ALREADY_EXISTS;
2863
Eric Laurent81784c32012-11-19 14:55:58 -08002864 if (mActiveTracks.indexOf(track) < 0) {
2865 // the track is newly added, make sure it fills up all its
2866 // buffers before playing. This is to ensure the client will
2867 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002868 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002869 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002870 // Because the track is not on the ActiveTracks,
2871 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002872 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002873 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002874 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002875 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002876 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002878 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002879 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002880 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 }
2882 return INVALID_OPERATION;
2883 }
2884 // abort if start is rejected by audio policy manager
2885 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002886 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2887 // current playback thread is reopened, which may happen when clients set preferred
2888 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2889 // immediately.
2890 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002891 }
2892#ifdef ADD_BATTERY_DATA
2893 // to track the speaker usage
2894 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2895#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002896 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 }
2898
Eric Laurent51716182016-02-29 18:00:56 -08002899 // set retry count for buffer fill
2900 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002901 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002902 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002903 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002904 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002905 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002906 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002907 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002908 track->retryCount() = kMaxTrackStartupRetries;
2909 track->fillingStatus() =
2910 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002911 }
2912
Andy Hung116bc262023-06-20 18:56:17 -07002913 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002914 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2915 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002916 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002917 // Unlock due to VibratorService will lock for this call and will
2918 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002919 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002920 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002921 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002922 std::optional<media::AudioVibratorInfo> vibratorInfo;
2923 {
2924 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2925 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002926 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002927 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002928 }
Andy Hungc5007f82023-08-29 14:26:09 -07002929 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002930 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002931 if (vibratorInfo) {
2932 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2933 }
2934
jiabin57303cc2018-12-18 15:45:57 -08002935 // Haptic playback should be enabled by vibrator service.
2936 if (track->getHapticPlaybackEnabled()) {
2937 // Disable haptic playback of all active track to ensure only
2938 // one track playing haptic if current track should play haptic.
2939 for (const auto &t : mActiveTracks) {
2940 t->setHapticPlaybackEnabled(false);
2941 }
jiabin245cdd92018-12-07 17:55:15 -08002942 }
jiabine70bc7f2020-06-30 22:07:55 -07002943
2944 // Set haptic intensity for effect
2945 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002946 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002947 }
jiabin245cdd92018-12-07 17:55:15 -08002948 }
2949
Andy Hung8d31fd22023-06-26 19:20:57 -07002950 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002951 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002952
2953 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2954 // all key changes are complete. It is possible that the threadLoop will begin
2955 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002956 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002957
Eric Laurentd0107bc2013-06-11 14:38:48 -07002958 if (chain != 0) {
2959 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2960 track->sessionId());
2961 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002962 }
2963
Andy Hungc2b11cb2020-04-22 09:04:01 -07002964 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002965 status = NO_ERROR;
2966 }
2967
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002968 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002969 return status;
2970}
2971
Andy Hungee58e4a2023-07-07 13:47:37 -07002972bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002973{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002974 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002975 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002976 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002977 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002978 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002979 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002980 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002981 if (track->isPausePending()) {
2982 track->pauseAck();
2983 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002984 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002985 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002986
2987 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002988}
2989
Andy Hungee58e4a2023-07-07 13:47:37 -07002990void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002991{
2992 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002993
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002994 String8 result;
2995 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002996 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002997
Eric Laurent81784c32012-11-19 14:55:58 -08002998 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002999 {
Andy Hung972bec12023-08-31 16:13:39 -07003000 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003001 mAudioTrackCallbacks.erase(track);
3002 }
Eric Laurent81784c32012-11-19 14:55:58 -08003003 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003004 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003005 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003006 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3007 mFastTrackAvailMask |= 1 << index;
3008 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003009 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003010 }
Andy Hung116bc262023-06-20 18:56:17 -07003011 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003012 if (chain != 0) {
3013 chain->decTrackCnt();
3014 }
3015}
3016
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003017std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3018{
3019 std::set<int32_t> result;
3020 for (const auto& t : mTracks) {
3021 if (t->isExternalTrack()) {
3022 result.insert(t->portId());
3023 }
3024 }
3025 return result;
3026}
3027
3028std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3029{
3030 audio_utils::lock_guard _l(mutex());
3031 return getTrackPortIds_l();
3032}
3033
Andy Hungee58e4a2023-07-07 13:47:37 -07003034String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003035{
Andy Hung972bec12023-08-31 16:13:39 -07003036 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003037 String8 out_s8;
3038 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3039 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003040 }
Andy Hung920f6572022-10-06 12:09:49 -07003041 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003042}
3043
Andy Hungee58e4a2023-07-07 13:47:37 -07003044status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003045 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003046 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003047 return NO_INIT;
3048 }
3049 return mOutput->stream->selectPresentation(presentationId, programId);
3050}
3051
Andy Hungab65b182023-09-06 19:41:47 -07003052void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003053 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003054 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003055 sp<AudioIoDescriptor> desc;
3056 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003057 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003058 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003059 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003060 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003061 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3062 mSampleRate, mFormat, mChannelMask,
3063 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3064 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003065 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003066 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003067 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003068 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003069 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003070 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003071 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003072 break;
3073 }
Andy Hungab65b182023-09-06 19:41:47 -07003074 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003075}
3076
Andy Hungee58e4a2023-07-07 13:47:37 -07003077void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003078{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003079 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003080}
3081
Andy Hungee58e4a2023-07-07 13:47:37 -07003082void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003083{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003084 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003085}
3086
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003087void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003088{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003089 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003090}
3091
Andy Hungee58e4a2023-07-07 13:47:37 -07003092void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003093 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003094{
Andy Hungee58e4a2023-07-07 13:47:37 -07003095 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003096 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003097 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003098 if (playbackThread == nullptr) {
3099 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3100 return;
3101 }
3102
jiabinf6eb4c32020-02-25 14:06:25 -08003103 audio_utils::metadata::Data metadata =
3104 audio_utils::metadata::dataFromByteString(metadataBs);
3105 if (metadata.empty()) {
3106 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3107 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3108 (int)metadataBs.size());
3109 return;
3110 }
3111
3112 audio_utils::metadata::ByteString metaDataStr =
3113 audio_utils::metadata::byteStringFromData(metadata);
3114 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003115 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003116 for (const auto& callbackPair : mAudioTrackCallbacks) {
3117 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003118 }
3119 }).detach();
3120}
3121
Andy Hungee58e4a2023-07-07 13:47:37 -07003122void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003123{
Andy Hung972bec12023-08-31 16:13:39 -07003124 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003125 // reject out of sequence requests
3126 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3127 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003128 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003129 }
3130}
3131
Andy Hungee58e4a2023-07-07 13:47:37 -07003132void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003133{
Andy Hung972bec12023-08-31 16:13:39 -07003134 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003135 // reject out of sequence requests
3136 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003137 // Register discontinuity when HW drain is completed because that can cause
3138 // the timestamp frame position to reset to 0 for direct and offload threads.
3139 // (Out of sequence requests are ignored, since the discontinuity would be handled
3140 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003141 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003142 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003143 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003144 }
3145}
3146
Andy Hungee58e4a2023-07-07 13:47:37 -07003147void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003148NO_THREAD_SAFETY_ANALYSIS
3149// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003150{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003151 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003152 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3153 mSampleRate = audioConfig.sample_rate;
3154 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003155 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003156 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003157 }
Andy Hung81994d62023-07-20 21:44:14 -07003158 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003159 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3160 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003161 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003162
3163 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3164 mMixerChannelMask = mChannelMask;
3165 }
3166
Andy Hunge5412692014-05-16 11:25:07 -07003167 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003168 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003169
Eric Laurentf1f22e72021-07-13 14:04:14 +02003170 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3171
Phil Burkca5e6142015-07-14 09:42:29 -07003172 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003173 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003174 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003175 // Get format from the shim, which will be different than the HAL format
3176 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003177 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003178 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003179 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003180 }
Andy Hung81994d62023-07-20 21:44:14 -07003181 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003182 LOG_FATAL("HAL format %#x not supported for mixed output",
3183 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003184 }
Phil Burk062e67a2015-02-11 13:40:50 -08003185 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003186 result = mOutput->stream->getBufferSize(&mBufferSize);
3187 LOG_ALWAYS_FATAL_IF(result != OK,
3188 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003189 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003190 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003191 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003192 mFrameCount);
3193 }
3194
Eric Laurentd1f69b02014-12-15 14:33:13 -08003195 mHwSupportsPause = false;
3196 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003197 bool supportsPause = false, supportsResume = false;
3198 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3199 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003200 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003201 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003202 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003203 } else if (supportsResume) {
3204 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003205 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003206 }
3207 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003208 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3209 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3210 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003211
Andy Hungfbfc3952015-01-15 13:33:51 -08003212 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3213 // For best precision, we use float instead of the associated output
3214 // device format (typically PCM 16 bit).
3215
3216 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3217 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3218 mBufferSize = mFrameSize * mFrameCount;
3219
3220 // TODO: We currently use the associated output device channel mask and sample rate.
3221 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3222 // (if a valid mask) to avoid premature downmix.
3223 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3224 // instead of the output device sample rate to avoid loss of high frequency information.
3225 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3226 }
3227
Andy Hung09a50072014-02-27 14:30:47 -08003228 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003229 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003230 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003231 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3232 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003233 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3234 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003235
Eric Laurent81784c32012-11-19 14:55:58 -08003236 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3237 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3238 maxNormalFrameCount = maxNormalFrameCount & ~15;
3239 if (maxNormalFrameCount < minNormalFrameCount) {
3240 maxNormalFrameCount = minNormalFrameCount;
3241 }
3242 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3243 if (multiplier <= 1.0) {
3244 multiplier = 1.0;
3245 } else if (multiplier <= 2.0) {
3246 if (2 * mFrameCount <= maxNormalFrameCount) {
3247 multiplier = 2.0;
3248 } else {
3249 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3250 }
3251 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003252 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003253 }
3254 }
3255 mNormalFrameCount = multiplier * mFrameCount;
3256 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003257 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003258 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3259 }
Andy Hungab65b182023-09-06 19:41:47 -07003260 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3261 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003262
Andy Hung08fb1742015-05-31 23:22:10 -07003263 // Check if we want to throttle the processing to no more than 2x normal rate
3264 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003265 mThreadThrottleTimeMs = 0;
3266 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003267 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3268
Andy Hung010a1a12014-03-13 13:57:33 -07003269 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3270 // Originally this was int16_t[] array, need to remove legacy implications.
3271 free(mSinkBuffer);
3272 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003273
Andy Hung5b10a202014-03-13 13:59:29 -07003274 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3275 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3276 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003277 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003278
Andy Hung69aed5f2014-02-25 17:24:40 -08003279 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3280 // drives the output.
3281 free(mMixerBuffer);
3282 mMixerBuffer = NULL;
3283 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003284 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003285 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003286 * audio_bytes_per_sample(mMixerBufferFormat);
3287 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3288 }
Andy Hung98ef9782014-03-04 14:46:50 -08003289 free(mEffectBuffer);
3290 mEffectBuffer = NULL;
3291 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003292 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003293 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003294 * audio_bytes_per_sample(mEffectBufferFormat);
3295 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3296 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003297
Eric Laurentb62d0362021-10-26 17:40:18 +02003298 if (mType == SPATIALIZER) {
3299 free(mPostSpatializerBuffer);
3300 mPostSpatializerBuffer = nullptr;
3301 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3302 * audio_bytes_per_sample(mEffectBufferFormat);
3303 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3304 }
3305
Mikhail Naganov55773032020-10-01 15:08:13 -07003306 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3307 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003308 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3309 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003310 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003311
Eric Laurent81784c32012-11-19 14:55:58 -08003312 // force reconfiguration of effect chains and engines to take new buffer size and audio
3313 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003314 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003315 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3316 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003317 // create a copy of mEffectChains as calling moveEffectChain_ll()
3318 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003319 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003320 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003321 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003322 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003323 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003324
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003325 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003326 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003327 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003328 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003329 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3330 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3331 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3332 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3333 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3334 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3335 (int32_t)mHapticChannelMask)
3336 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3337 (int32_t)mHapticChannelCount)
3338 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003339 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003340 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3341 (int32_t)mFrameCount) // sic - added HAL
3342 ;
3343 uint32_t latencyMs;
3344 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3345 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3346 }
3347 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003348}
3349
Andy Hungee58e4a2023-07-07 13:47:37 -07003350ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003351{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003352 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003353 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003354 }
3355 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003356 static const bool stereo_spatialization_property =
3357 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3358 const bool stereo_spatialization_enabled =
3359 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3360 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003361 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3362 for (const sp<IAfTrack>& track : mActiveTracks) {
3363 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3364 allSessionsMetadata[track->sessionId()];
3365 auto backInserter = std::back_inserter(sessionMetadata);
3366 // No track is invalid as this is called after prepareTrack_l in the same
3367 // critical section
3368 track->copyMetadataTo(backInserter);
3369 }
3370 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3371 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3372 metadata.tracks.insert(metadata.tracks.end(),
3373 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3374 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3375 chain->sendMetadata_l(sessionTrackMetadata, {});
3376 }
3377 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3378 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3379 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3380 }
3381 }
3382 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3383 chain->sendMetadata_l(metadata.tracks, {});
3384 }
3385 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3386 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3387 }
3388 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3389 chain->sendMetadata_l(metadata.tracks, {});
3390 }
3391 } else {
3392 auto backInserter = std::back_inserter(metadata.tracks);
3393 for (const sp<IAfTrack>& track : mActiveTracks) {
3394 // No track is invalid as this is called after prepareTrack_l in the same
3395 // critical section
3396 track->copyMetadataTo(backInserter);
3397 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003398 }
Kevin Rocard12381092018-04-11 09:19:59 -07003399 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003400 MetadataUpdate change;
3401 change.playbackMetadataUpdate = metadata.tracks;
3402 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003403}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003404
Andy Hungee58e4a2023-07-07 13:47:37 -07003405void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003406 const StreamOutHalInterface::SourceMetadata& metadata)
3407{
3408 mOutput->stream->updateSourceMetadata(metadata);
3409};
3410
Andy Hungee58e4a2023-07-07 13:47:37 -07003411status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003412 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003413{
3414 if (halFrames == NULL || dspFrames == NULL) {
3415 return BAD_VALUE;
3416 }
Andy Hung972bec12023-08-31 16:13:39 -07003417 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003418 if (initCheck() != NO_ERROR) {
3419 return INVALID_OPERATION;
3420 }
Andy Hung818e7a32016-02-16 18:08:07 -08003421 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003422 *halFrames = framesWritten;
3423
3424 if (isSuspended()) {
3425 // return an estimation of rendered frames when the output is suspended
3426 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003427 *dspFrames = (uint32_t)
3428 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003429 return NO_ERROR;
3430 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003431 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003432 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003433 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003434 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003435 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003436 }
3437}
3438
Andy Hungee58e4a2023-07-07 13:47:37 -07003439product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003440{
3441 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3442 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3443 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003444 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003445 }
3446 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003447 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003448 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003449 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003450 }
3451 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003452 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003453}
3454
3455
Andy Hungee58e4a2023-07-07 13:47:37 -07003456AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003457{
Andy Hung972bec12023-08-31 16:13:39 -07003458 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003459 return mOutput;
3460}
3461
Andy Hungee58e4a2023-07-07 13:47:37 -07003462AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003463{
Andy Hung972bec12023-08-31 16:13:39 -07003464 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003465 AudioStreamOut *output = mOutput;
3466 mOutput = NULL;
3467 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3468 // must push a NULL and wait for ack
3469 mOutputSink.clear();
3470 mPipeSink.clear();
3471 mNormalSink.clear();
3472 return output;
3473}
3474
Andy Hungc5007f82023-08-29 14:26:09 -07003475// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003476sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003477{
3478 if (mOutput == NULL) {
3479 return NULL;
3480 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003481 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003482}
3483
Andy Hungee58e4a2023-07-07 13:47:37 -07003484uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003485{
3486 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3487}
3488
Andy Hungee58e4a2023-07-07 13:47:37 -07003489status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003490{
3491 if (!isValidSyncEvent(event)) {
3492 return BAD_VALUE;
3493 }
3494
Andy Hung972bec12023-08-31 16:13:39 -07003495 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003496
3497 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003498 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003499 if (event->triggerSession() == track->sessionId()) {
3500 (void) track->setSyncEvent(event);
3501 return NO_ERROR;
3502 }
3503 }
3504
3505 return NAME_NOT_FOUND;
3506}
3507
Andy Hungee58e4a2023-07-07 13:47:37 -07003508bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003509{
3510 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3511}
3512
Andy Hungee58e4a2023-07-07 13:47:37 -07003513void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003514 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003515{
Andy Hungfe726a62018-09-27 15:17:25 -07003516 // Miscellaneous track cleanup when removed from the active list,
3517 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003519 for (const auto& track : tracksToRemove) {
3520 if (track->isExternalTrack()) {
3521 // to track the speaker usage
3522 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003523 }
3524 }
Andy Hungfe726a62018-09-27 15:17:25 -07003525#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003526}
3527
Andy Hungee58e4a2023-07-07 13:47:37 -07003528void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003529{
3530 if (!mMasterMute) {
3531 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003532 if (mOutDeviceTypeAddrs.empty()) {
3533 ALOGD("ro.audio.silent is ignored since no output device is set");
3534 return;
3535 }
Andy Hungab65b182023-09-06 19:41:47 -07003536 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003537 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3538 return;
3539 }
Eric Laurent81784c32012-11-19 14:55:58 -08003540 if (property_get("ro.audio.silent", value, "0") > 0) {
3541 char *endptr;
3542 unsigned long ul = strtoul(value, &endptr, 0);
3543 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003544 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003545 // The setprop command will not allow a property to be changed after
3546 // the first time it is set, so we don't have to worry about un-muting.
3547 setMasterMute_l(true);
3548 }
3549 }
3550 }
3551}
3552
3553// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003554ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003555{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003556 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003557 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003558 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003559 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003560
3561 // If an NBAIO sink is present, use it to write the normal mixer's submix
3562 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003563
Andy Hung010a1a12014-03-13 13:57:33 -07003564 const size_t count = mBytesRemaining / mFrameSize;
3565
Simon Wilson2d590962012-11-29 15:18:50 -08003566 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003567 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003568 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003569 if (screenState != mScreenState) {
3570 mScreenState = screenState;
3571 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3572 if (pipe != NULL) {
3573 pipe->setAvgFrames((mScreenState & 1) ?
3574 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3575 }
3576 }
Andy Hung010a1a12014-03-13 13:57:33 -07003577 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003578 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003579
Eric Laurent81784c32012-11-19 14:55:58 -08003580 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003581 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003582
Andy Hung8946a282018-04-19 20:04:56 -07003583#ifdef TEE_SINK
3584 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3585#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003586 } else {
3587 bytesWritten = framesWritten;
3588 }
3589 // otherwise use the HAL / AudioStreamOut directly
3590 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003592
Eric Laurentbfb1b832013-01-07 09:53:42 -08003593 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003594 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3595 mWriteAckSequence += 2;
3596 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003597 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003598 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003599 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003600 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003601 // FIXME We should have an implementation of timestamps for direct output threads.
3602 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003603 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003604 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003605
Eric Laurentbfb1b832013-01-07 09:53:42 -08003606 if (mUseAsyncWrite &&
3607 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3608 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003609 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003611 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 }
Eric Laurent81784c32012-11-19 14:55:58 -08003613 }
3614
Eric Laurent81784c32012-11-19 14:55:58 -08003615 mNumWrites++;
3616 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003617 if (mStandby) {
3618 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003619 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003620 mStandby = false;
3621 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622 return bytesWritten;
3623}
3624
Andy Hungc5007f82023-08-29 14:26:09 -07003625// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003626void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003627 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003628{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003629 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003630 if (outputSink != nullptr) {
3631 outputSink->startMelComputation(processor);
3632 }
Vlad Popab042ee62022-10-20 18:05:00 +02003633}
3634
Andy Hungc5007f82023-08-29 14:26:09 -07003635// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003636void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003637{
3638 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003639 if (outputSink != nullptr) {
3640 outputSink->stopMelComputation();
3641 }
Vlad Popab042ee62022-10-20 18:05:00 +02003642}
3643
Andy Hungee58e4a2023-07-07 13:47:37 -07003644void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003645{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003646 bool supportsDrain = false;
3647 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003648 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3649 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003650 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3651 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003652 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003653 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003654 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003655 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003656 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003657 }
3658}
3659
Andy Hungee58e4a2023-07-07 13:47:37 -07003660void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003661{
Eric Laurent275e8e92014-11-30 15:14:47 -08003662 {
Andy Hung972bec12023-08-31 16:13:39 -07003663 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003664 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003665 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003666 track->invalidate();
3667 }
Andy Hungdae27702016-10-31 14:01:16 -07003668 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3669 // After we exit there are no more track changes sent to BatteryNotifier
3670 // because that requires an active threadLoop.
3671 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3672 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003673 }
Eric Laurent81784c32012-11-19 14:55:58 -08003674}
3675
3676/*
3677The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003678 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003679 - mActiveSleepTimeUs from activeSleepTimeUs()
3680 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003681 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3682 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003683 - maxPeriod from frame count and sample rate (MIXER only)
3684
3685The parameters that affect these derived values are:
3686 - frame count
3687 - frame size
3688 - sample rate
3689 - device type: A2DP or not
3690 - device latency
3691 - format: PCM or not
3692 - active sleep time
3693 - idle sleep time
3694*/
3695
Andy Hungee58e4a2023-07-07 13:47:37 -07003696void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003697{
Andy Hung25c2dac2014-02-27 14:56:00 -08003698 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003699 mActiveSleepTimeUs = activeSleepTimeUs();
3700 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003701
Andy Hung8fe87eb2023-07-20 21:31:38 -07003702 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003703
Eric Laurent42537be2016-01-08 17:16:42 -08003704 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3705 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003706 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003707 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3708 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3709 }
3710 }
Eric Laurent81784c32012-11-19 14:55:58 -08003711}
3712
Andy Hungee58e4a2023-07-07 13:47:37 -07003713bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003714{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003715 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003716 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003717 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003718 size_t size = mTracks.size();
3719 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003720 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003721 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003722 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003723 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003724 }
3725 }
Eric Laurent13084622016-05-17 10:51:49 -07003726 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003727}
3728
Andy Hungee58e4a2023-07-07 13:47:37 -07003729void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003730{
Andy Hung972bec12023-08-31 16:13:39 -07003731 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003732 invalidateTracks_l(streamType);
3733}
3734
Andy Hungee58e4a2023-07-07 13:47:37 -07003735void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003736 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003737 invalidateTracks_l(portIds);
3738}
3739
Andy Hungee58e4a2023-07-07 13:47:37 -07003740bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003741 bool trackMatch = false;
3742 const size_t size = mTracks.size();
3743 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003744 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003745 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3746 t->invalidate();
3747 portIds.erase(t->portId());
3748 trackMatch = true;
3749 }
3750 if (portIds.empty()) {
3751 break;
3752 }
3753 }
3754 return trackMatch;
3755}
3756
jiabinf042b9b2021-05-07 23:46:28 +00003757// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003758IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003759 audio_port_handle_t trackPortId) {
3760 for (size_t i = 0; i < mTracks.size(); i++) {
3761 if (mTracks[i]->portId() == trackPortId) {
3762 return mTracks[i].get();
3763 }
3764 }
3765 return nullptr;
3766}
3767
Andy Hungee58e4a2023-07-07 13:47:37 -07003768status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003769{
Glenn Kastend848eb42016-03-08 13:42:11 -08003770 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003771 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003772 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003773
Andy Hungd3639922022-04-28 18:00:49 -07003774 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003775 if (!audio_is_global_session(session)) {
3776 // player sessions on a spatializer output will use a dedicated input buffer and
3777 // will either output multi channel to mEffectBuffer if the track is spatilaized
3778 // or stereo to mPostSpatializerBuffer if not spatialized.
3779 uint32_t channelMask;
3780 bool isSessionSpatialized =
3781 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3782 if (isSessionSpatialized) {
3783 channelMask = mMixerChannelMask;
3784 } else {
3785 channelMask = mChannelMask;
3786 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003787 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003788 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003789 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003790 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003791 &halInBuffer);
3792 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003793
Andy Hung583043b2023-07-17 17:05:00 -07003794 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003795 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3796 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3797 &halOutBuffer);
3798 if (result != OK) return result;
3799
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003800 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003801
Mikhail Naganov022b9952017-01-04 16:36:51 -08003802 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3803 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003804 } else {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003805 status_t result = INVALID_OPERATION;
3806 // Buffer configuration for global sessions on a SPATIALIZER thread:
3807 // - AUDIO_SESSION_OUTPUT_MIX session uses the mEffectBuffer as input and output buffer
3808 // - AUDIO_SESSION_OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3809 // mPostSpatializerBuffer as output buffer
3810 // - AUDIO_SESSION_DEVICE session uses the mPostSpatializerBuffer as input and output
3811 // buffer
3812 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_OUTPUT_STAGE) {
3813 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3814 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3815 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003816
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003817 if (session == AUDIO_SESSION_OUTPUT_MIX) {
3818 halOutBuffer = halInBuffer;
3819 }
3820 }
3821
3822 if (session == AUDIO_SESSION_OUTPUT_STAGE || session == AUDIO_SESSION_DEVICE) {
3823 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3824 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3825 if (result != OK) return result;
3826
3827 if (session == AUDIO_SESSION_DEVICE) {
3828 halInBuffer = halOutBuffer;
3829 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003830 }
3831 }
3832 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003833 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003834 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3835 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3836 &halInBuffer);
3837 if (result != OK) return result;
3838 halOutBuffer = halInBuffer;
3839 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3840 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003841 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003842 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003843 // Only one effect chain can be present in direct output thread and it uses
3844 // the sink buffer as input
3845 if (mType != DIRECT) {
3846 size_t numSamples = mNormalFrameCount
3847 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3848 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003849 const status_t allocateStatus =
3850 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003851 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003852 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003853 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003854
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003855 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003856 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3857 buffer, session);
3858 }
3859 }
3860 }
3861
3862 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003863 // Attach all tracks with same session ID to this chain.
3864 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003865 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003866 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003867 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3868 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003869 track->setMainBuffer(buffer);
3870 chain->incTrackCnt();
3871 }
3872 }
3873
3874 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003875 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003876 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003877 ALOGV("addEffectChain_l() activating track %p on session %d",
3878 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003879 chain->incActiveTrackCnt();
3880 }
3881 }
3882 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003883
Eric Laurentaaa44472014-09-12 17:41:50 -07003884 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003885 chain->setInBuffer(halInBuffer);
3886 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003887 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3888 // chains list in order to be processed last as it contains output device effects.
3889 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3890 // processing effects specific to an output stream before effects applied to all streams
3891 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003892 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3893 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003894 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003895 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003896 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003897 // Effect chain for other sessions are inserted at beginning of effect
3898 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003899 // sessions is not important.
3900 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003901 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3902 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003903 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003904 size_t size = mEffectChains.size();
3905 size_t i = 0;
3906 for (i = 0; i < size; i++) {
3907 if (mEffectChains[i]->sessionId() < session) {
3908 break;
3909 }
3910 }
3911 mEffectChains.insertAt(chain, i);
3912 checkSuspendOnAddEffectChain_l(chain);
3913
3914 return NO_ERROR;
3915}
3916
Andy Hungee58e4a2023-07-07 13:47:37 -07003917size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003918{
Glenn Kastend848eb42016-03-08 13:42:11 -08003919 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003920
3921 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3922
3923 for (size_t i = 0; i < mEffectChains.size(); i++) {
3924 if (chain == mEffectChains[i]) {
3925 mEffectChains.removeAt(i);
3926 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003927 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003928 if (session == track->sessionId()) {
3929 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3930 chain.get(), session);
3931 chain->decActiveTrackCnt();
3932 }
3933 }
3934
3935 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003936 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003937 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003938 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003939 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003940 chain->decTrackCnt();
3941 }
3942 }
3943 break;
3944 }
3945 }
3946 return mEffectChains.size();
3947}
3948
Andy Hungee58e4a2023-07-07 13:47:37 -07003949status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003950 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003951{
Andy Hung972bec12023-08-31 16:13:39 -07003952 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003953 return attachAuxEffect_l(track, EffectId);
3954}
3955
Andy Hungee58e4a2023-07-07 13:47:37 -07003956status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003957 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003958{
3959 status_t status = NO_ERROR;
3960
3961 if (EffectId == 0) {
3962 track->setAuxBuffer(0, NULL);
3963 } else {
3964 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003965 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003966 if (effect != 0) {
3967 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3968 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3969 } else {
3970 status = INVALID_OPERATION;
3971 }
3972 } else {
3973 status = BAD_VALUE;
3974 }
3975 }
3976 return status;
3977}
3978
Andy Hungee58e4a2023-07-07 13:47:37 -07003979void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003980{
3981 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003982 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003983 if (track->auxEffectId() == effectId) {
3984 attachAuxEffect_l(track, 0);
3985 }
3986 }
3987}
3988
Andy Hungee58e4a2023-07-07 13:47:37 -07003989bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003990NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003991{
Andy Hung78d8d952023-05-30 18:10:23 -07003992 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003993
Andy Hung077d62e2023-10-03 10:49:34 -07003994 if (mType == SPATIALIZER) {
3995 const pid_t tid = getTid();
3996 if (tid == -1) { // odd: we are here, we must be a running thread.
3997 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3998 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003999 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4000 if (priorityBoost > 0) {
4001 stream()->setHalThreadPriority(priorityBoost);
4002 }
Andy Hung077d62e2023-10-03 10:49:34 -07004003 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004004 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4005 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4006 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4007 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4008 // only on ARC.
4009 const pid_t tid = getTid();
4010 if (tid == -1) {
4011 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4012 } else {
4013 const status_t status = requestPriority(getpid(),
4014 tid,
4015 kPriorityPlaybackThreadArc,
4016 false /* isForApp */,
4017 true /* asynchronous */);
4018 if (status != OK) {
4019 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4020 status);
4021 } else {
4022 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4023 }
4024 }
Andy Hung077d62e2023-10-03 10:49:34 -07004025 }
4026
Andy Hung8d31fd22023-06-26 19:20:57 -07004027 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004028
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004029 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004030 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004031
4032 // MIXER
4033 nsecs_t lastWarning = 0;
4034
4035 // DUPLICATING
4036 // FIXME could this be made local to while loop?
4037 writeFrames = 0;
4038
4039 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004040 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004041
Andy Hungd3639922022-04-28 18:00:49 -07004042 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004043 sleepTimeShift = 0;
4044 }
4045
4046 CpuStats cpuStats;
4047 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4048
4049 acquireWakeLock();
4050
Glenn Kasteneef598c2017-04-03 14:41:13 -07004051 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4052 // thread associated with this PlaybackThread.
4053 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4054 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004055 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4056 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004057 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004058 const char *logString = NULL;
4059
rago1bb90822017-05-02 18:31:48 -07004060 // Estimated time for next buffer to be written to hal. This is used only on
4061 // suspended mode (for now) to help schedule the wait time until next iteration.
4062 nsecs_t timeLoopNextNs = 0;
4063
Eric Laurent664539d2013-09-23 18:24:31 -07004064 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004065
Andy Hung2dbffc22018-08-08 18:50:41 -07004066 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004067
Eric Laurentb3f315a2021-07-13 15:09:05 +02004068 sendCheckOutputStageEffectsEvent();
4069
Andy Hung446f4df2019-02-21 12:26:41 -08004070 // loopCount is used for statistics and diagnostics.
4071 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004072 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004073 // Log merge requests are performed during AudioFlinger binder transactions, but
4074 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004075 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004076
Eric Laurent81784c32012-11-19 14:55:58 -08004077 cpuStats.sample(myName);
4078
Andy Hung116bc262023-06-20 18:56:17 -07004079 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004080 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004081 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004082 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004083
Andy Hung2dbffc22018-08-08 18:50:41 -07004084 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4085 //
Andy Hungc5007f82023-08-29 14:26:09 -07004086 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004087 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004088 // Here, we try for the AF lock, but do not block on it as the latency
4089 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004090 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004091 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004092 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004093 status_t status = INVALID_OPERATION;
4094 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004095 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004096 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004097 && swPatches.size() > 0) {
4098 status = swPatches[0].getLatencyMs_l(&latencyMs);
4099 downstreamPatchHandle = swPatches[0].getPatchHandle();
4100 }
4101 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004102 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004103 lastDownstreamPatchHandle = downstreamPatchHandle;
4104 }
4105 if (status == OK) {
4106 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004107 // latency of 5 seconds).
4108 const double minLatency = 0., maxLatency = 5000.;
4109 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004110 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004111 } else {
4112 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004113 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004114 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004115 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004116 }
Andy Hung583043b2023-07-17 17:05:00 -07004117 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004118 }
4119 } else {
4120 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4121 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004122 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004123 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4124 }
4125 }
4126
Eric Laurentb3f315a2021-07-13 15:09:05 +02004127 if (mCheckOutputStageEffects.exchange(false)) {
4128 checkOutputStageEffects();
4129 }
4130
Vlad Popa7e81cea2023-01-19 16:34:16 +01004131 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004132 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004133
Andy Hungc5007f82023-08-29 14:26:09 -07004134 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004135
Eric Laurent021cf962014-05-13 10:18:14 -07004136 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004137 if (mCheckOutputStageEffects.load()) {
4138 continue;
4139 }
Eric Laurent10351942014-05-08 18:49:52 -07004140
Andy Hungc5007f82023-08-29 14:26:09 -07004141 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004142 if (logString != NULL) {
4143 mNBLogWriter->logTimestamp();
4144 mNBLogWriter->log(logString);
4145 logString = NULL;
4146 }
4147
Dean Wheatley12473e92021-03-18 23:00:55 +11004148 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004149
Eric Laurent81784c32012-11-19 14:55:58 -08004150 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004151 if (mSignalPending) {
4152 // A signal was raised while we were unlocked
4153 mSignalPending = false;
4154 } else if (waitingAsyncCallback_l()) {
4155 if (exitPending()) {
4156 break;
4157 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004158 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004159 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004160 releaseWakeLock_l();
4161 released = true;
4162 }
Andy Hung10cbff12017-02-21 17:30:14 -08004163
4164 const int64_t waitNs = computeWaitTimeNs_l();
4165 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004166 std::cv_status cvstatus =
4167 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4168 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004169 mSignalPending = true; // if timeout recheck everything
4170 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004171 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004172 if (released) {
4173 acquireWakeLock_l();
4174 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004175 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4176 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004177
4178 continue;
4179 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004180 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181 isSuspended()) {
4182 // put audio hardware into standby after short delay
4183 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004184
4185 threadLoop_standby();
4186
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004187 // This is where we go into standby
4188 if (!mStandby) {
4189 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004190 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004191 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004192 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004193 }
Andy Hungd0979812019-02-21 15:51:44 -08004194 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004195 }
4196
Eric Tan39ec8d62018-07-24 09:49:29 -07004197 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004198 // we're about to wait, flush the binder command buffer
4199 IPCThreadState::self()->flushCommands();
4200
4201 clearOutputTracks();
4202
4203 if (exitPending()) {
4204 break;
4205 }
4206
4207 releaseWakeLock_l();
4208 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004209 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004210 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004211 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004212 acquireWakeLock_l();
4213
4214 mMixerStatus = MIXER_IDLE;
4215 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4216 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004217 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004218 checkSilentMode_l();
4219
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004220 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4221 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004222 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004223 sleepTimeShift = 0;
4224 }
4225
4226 continue;
4227 }
4228 }
Eric Laurent81784c32012-11-19 14:55:58 -08004229 // mMixerStatusIgnoringFastTracks is also updated internally
4230 mMixerStatus = prepareTracks_l(&tracksToRemove);
4231
Andy Hungab65b182023-09-06 19:41:47 -07004232 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004233
Vlad Popa7e81cea2023-01-19 16:34:16 +01004234 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004235
Andy Hungf302e812024-01-26 11:55:15 -08004236 // Acquire a local copy of active tracks with lock (release w/o lock).
4237 //
4238 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4239 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4240 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4241 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4242
4243 setHalLatencyMode_l();
4244
4245 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4246 // so this is done before we lock our effect chains.
4247 for (const auto& track : mActiveTracks) {
4248 track->updateTeePatches_l();
4249 }
4250
4251 // signal actual start of output stream when the render position reported by
4252 // the kernel starts moving.
4253 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4254 && (mKernelPositionOnStandby
4255 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4256 mHalStarted = true;
4257 mWaitHalStartCV.notify_all();
4258 }
4259
Eric Laurent81784c32012-11-19 14:55:58 -08004260 // prevent any changes in effect chain list and in each effect chain
4261 // during mixing and effect process as the audio buffers could be deleted
4262 // or modified if an effect is created or deleted
4263 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004264
4265 // Determine which session to pick up haptic data.
4266 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004267 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004268 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004269 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004270 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004271 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004272 if (effectChain != nullptr
4273 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004274 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004275 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004276 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004277 break;
4278 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004279 if (activeHapticSessionId == AUDIO_SESSION_NONE
4280 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004281 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004282 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004283 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004284 }
4285 }
4286 }
Andy Hungc5007f82023-08-29 14:26:09 -07004287 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004288
Eric Laurentbfb1b832013-01-07 09:53:42 -08004289 if (mBytesRemaining == 0) {
4290 mCurrentWriteLength = 0;
4291 if (mMixerStatus == MIXER_TRACKS_READY) {
4292 // threadLoop_mix() sets mCurrentWriteLength
4293 threadLoop_mix();
4294 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4295 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004296 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004297 // must be written to HAL
4298 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004299 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004300 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004301
4302 // Tally underrun frames as we are inserting 0s here.
4303 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004304 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004305 && !track->isStopped()
4306 && !track->isPaused()
4307 && !track->isTerminated()) {
4308 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4309 __func__, track->id(), track->getTrackStateAsString(),
4310 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004311 track->audioTrackServerProxy()->tallyUnderrunFrames(
4312 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004313 }
4314 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004315 }
4316 }
Andy Hung98ef9782014-03-04 14:46:50 -08004317 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004318 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004319 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004320 // or mSinkBuffer (if there are no effects and there is no data already copied to
4321 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004322 //
4323 // This is done pre-effects computation; if effects change to
4324 // support higher precision, this needs to move.
4325 //
4326 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004327 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004328 uint32_t mixerChannelCount = mEffectBufferValid ?
4329 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004330 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004331 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4332 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4333
David Li88ee0902022-06-22 10:01:21 +08004334 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4335 // do these processes after effects are applied.
4336 if (!mEffectBufferValid) {
4337 // mono blend occurs for mixer threads only (not direct or offloaded)
4338 // and is handled here if we're going directly to the sink.
4339 if (requireMonoBlend()) {
4340 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4341 mNormalFrameCount, true /*limit*/);
4342 }
Andy Hung2ddee192015-12-18 17:34:44 -08004343
David Li88ee0902022-06-22 10:01:21 +08004344 if (!hasFastMixer()) {
4345 // Balance must take effect after mono conversion.
4346 // We do it here if there is no FastMixer.
4347 // mBalance detects zero balance within the class for speed
4348 // (not needed here).
4349 mBalance.setBalance(mMasterBalance.load());
4350 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4351 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004352 }
4353
Andy Hung98ef9782014-03-04 14:46:50 -08004354 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004355 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004356
4357 // If we're going directly to the sink and there are haptic channels,
4358 // we should adjust channels as the sample data is partially interleaved
4359 // in this case.
4360 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4361 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4362 mChannelCount + mHapticChannelCount,
4363 audio_bytes_per_sample(format),
4364 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4365 }
Andy Hung98ef9782014-03-04 14:46:50 -08004366 }
4367
Eric Laurentbfb1b832013-01-07 09:53:42 -08004368 mBytesRemaining = mCurrentWriteLength;
4369 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004370 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4371 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4372 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4373 mBytesWritten += mBytesRemaining;
4374 mFramesWritten += framesRemaining;
4375 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004376 mBytesRemaining = 0;
4377 }
Eric Laurent81784c32012-11-19 14:55:58 -08004378
Eric Laurentbfb1b832013-01-07 09:53:42 -08004379 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004380 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004381 for (size_t i = 0; i < effectChains.size(); i ++) {
4382 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004383 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004384 if (activeHapticSessionId != AUDIO_SESSION_NONE
4385 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004386 // Haptic data is active in this case, copy it directly from
4387 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004388 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4389 audio_channel_count_from_out_mask(mMixerChannelMask) :
4390 mChannelCount;
4391 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4392 hapticSessionChannelCount = mChannelCount;
4393 }
4394
jiabin47affe52019-04-04 18:02:07 -07004395 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004396 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004397 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004398 memcpy_by_audio_format(
4399 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004400 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004401 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004402 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004403 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 }
Eric Laurent81784c32012-11-19 14:55:58 -08004405 }
4406 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004407 // Process effect chains for offloaded thread even if no audio
4408 // was read from audio track: process only updates effect state
4409 // and thus does have to be synchronized with audio writes but may have
4410 // to be called while waiting for async write callback
4411 if (mType == OFFLOAD) {
4412 for (size_t i = 0; i < effectChains.size(); i ++) {
4413 effectChains[i]->process_l();
4414 }
4415 }
Eric Laurent81784c32012-11-19 14:55:58 -08004416
Andy Hung98ef9782014-03-04 14:46:50 -08004417 // Only if the Effects buffer is enabled and there is data in the
4418 // Effects buffer (buffer valid), we need to
4419 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004420 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004421 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004422 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004423 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004424 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004425 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004426 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004427 }
4428
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004429 if (!hasFastMixer()) {
4430 // Balance must take effect after mono conversion.
4431 // We do it here if there is no FastMixer.
4432 // mBalance detects zero balance within the class for speed (not needed here).
4433 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004434 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004435 }
4436
Eric Laurentb62d0362021-10-26 17:40:18 +02004437 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4438 // mPostSpatializerBuffer if the haptics track is spatialized.
4439 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4440 // For other thread types, the haptics channels are already in mEffectBuffer.
4441 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4442 const size_t srcBufferSize = mNormalFrameCount *
4443 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4444 mEffectBufferFormat);
4445 const size_t dstBufferSize = mNormalFrameCount
4446 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4447
4448 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4449 mEffectBufferFormat,
4450 (uint8_t*)mEffectBuffer + srcBufferSize,
4451 mEffectBufferFormat,
4452 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004453 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004454 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4455 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4456 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4457 // Clamp PCM float values more than this distance from 0 to insulate
4458 // a HAL which doesn't handle NaN correctly.
4459 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4460 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4461 static_cast<const float*>(effectBuffer),
4462 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4463 } else {
4464 memcpy_by_audio_format(mSinkBuffer, mFormat,
4465 effectBuffer, mEffectBufferFormat, framesToCopy);
4466 }
jiabin245cdd92018-12-07 17:55:15 -08004467 // The sample data is partially interleaved when haptic channels exist,
4468 // we need to adjust channels here.
4469 if (mHapticChannelCount > 0) {
4470 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4471 mChannelCount + mHapticChannelCount,
4472 audio_bytes_per_sample(mFormat),
4473 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4474 }
Andy Hung98ef9782014-03-04 14:46:50 -08004475 }
4476
Eric Laurent81784c32012-11-19 14:55:58 -08004477 // enable changes in effect chain
4478 unlockEffectChains(effectChains);
4479
Vlad Popafce10862023-02-03 10:37:07 +01004480 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004481 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004482 metadataUpdate.playbackMetadataUpdate);
4483 }
4484
Eric Laurentbfb1b832013-01-07 09:53:42 -08004485 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004486 // mSleepTimeUs == 0 means we must write to audio hardware
4487 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004488 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004489 // writePeriodNs is updated >= 0 when ret > 0.
4490 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004491 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004492 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004493 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004494 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004495 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004496 if (ret < 0) {
4497 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004498 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004499 mBytesWritten += ret;
4500 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004501 const int64_t frames = ret / mFrameSize;
4502 mFramesWritten += frames;
4503
4504 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4505 // process information relating to write time.
4506 if (audio_has_proportional_frames(mFormat)) {
4507 // we are in a continuous mixing cycle
4508 if (mMixerStatus == MIXER_TRACKS_READY &&
4509 loopCount == lastLoopCountWritten + 1) {
4510
4511 const double jitterMs =
4512 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4513 {frames, writePeriodNs},
4514 {0, 0} /* lastTimestamp */, mSampleRate);
4515 const double processMs =
4516 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4517
Andy Hung972bec12023-08-31 16:13:39 -07004518 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004519 mIoJitterMs.add(jitterMs);
4520 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004521
4522 if (mPipeSink.get() != nullptr) {
4523 // Using the Monopipe availableToWrite, we estimate the current
4524 // buffer size.
4525 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4526 const ssize_t
4527 availableToWrite = mPipeSink->availableToWrite();
4528 const size_t pipeFrames = monoPipe->maxFrames();
4529 const size_t
4530 remainingFrames = pipeFrames - max(availableToWrite, 0);
4531 mMonopipePipeDepthStats.add(remainingFrames);
4532 }
Andy Hung446f4df2019-02-21 12:26:41 -08004533 }
4534
4535 // write blocked detection
4536 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004537 if ((mType == MIXER || mType == SPATIALIZER)
4538 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004539 mNumDelayedWrites++;
4540 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4541 ATRACE_NAME("underrun");
4542 ALOGW("write blocked for %lld msecs, "
4543 "%d delayed writes, thread %d",
4544 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4545 mNumDelayedWrites, mId);
4546 lastWarning = lastIoEndNs;
4547 }
4548 }
4549 }
4550 // update timing info.
4551 mLastIoBeginNs = lastIoBeginNs;
4552 mLastIoEndNs = lastIoEndNs;
4553 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004554 }
4555 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4556 (mMixerStatus == MIXER_DRAIN_ALL)) {
4557 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004558 }
Andy Hungd3639922022-04-28 18:00:49 -07004559 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004560
4561 if (mThreadThrottle
4562 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004563 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004564 // Limit MixerThread data processing to no more than twice the
4565 // expected processing rate.
4566 //
4567 // This helps prevent underruns with NuPlayer and other applications
4568 // which may set up buffers that are close to the minimum size, or use
4569 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4570 //
4571 // The throttle smooths out sudden large data drains from the device,
4572 // e.g. when it comes out of standby, which often causes problems with
4573 // (1) mixer threads without a fast mixer (which has its own warm-up)
4574 // (2) minimum buffer sized tracks (even if the track is full,
4575 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004576 //
4577 // Total time spent in last processing cycle equals time spent in
4578 // 1. threadLoop_write, as well as time spent in
4579 // 2. threadLoop_mix (significant for heavy mixing, especially
4580 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004581
Andy Hung446f4df2019-02-21 12:26:41 -08004582 // it's OK if deltaMs is an overestimate.
4583
4584 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004585
Ivan Lozanoea04d392017-11-07 14:37:07 -08004586 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004587 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004588 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004589
Andy Hung08fb1742015-05-31 23:22:10 -07004590 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004591 // notify of throttle start on verbose log
4592 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4593 "mixer(%p) throttle begin:"
4594 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004595 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004596 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004597 // Throttle must be attributed to the previous mixer loop's write time
4598 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004599 // This also ensures proper timing statistics.
4600 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004601 } else {
4602 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4603 if (diff > 0) {
4604 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004605 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004606 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004607 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004608 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004609 outDeviceTypes_l(),
4610 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004611 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004612 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4613 }
Andy Hung08fb1742015-05-31 23:22:10 -07004614 }
4615 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004616 }
Eric Laurent81784c32012-11-19 14:55:58 -08004617
Eric Laurentbfb1b832013-01-07 09:53:42 -08004618 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004619 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004620 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004621 // suspended requires accurate metering of sleep time.
4622 if (isSuspended()) {
4623 // advance by expected sleepTime
4624 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4625 const nsecs_t nowNs = systemTime();
4626
4627 // compute expected next time vs current time.
4628 // (negative deltas are treated as delays).
4629 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4630 if (deltaNs < -kMaxNextBufferDelayNs) {
4631 // Delays longer than the max allowed trigger a reset.
4632 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4633 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4634 timeLoopNextNs = nowNs + deltaNs;
4635 } else if (deltaNs < 0) {
4636 // Delays within the max delay allowed: zero the delta/sleepTime
4637 // to help the system catch up in the next iteration(s)
4638 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4639 deltaNs = 0;
4640 }
4641 // update sleep time (which is >= 0)
4642 mSleepTimeUs = deltaNs / 1000;
4643 }
Eric Laurente93cc032016-05-05 10:15:10 -07004644 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004645 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004646 }
Glenn Kastene7754022014-10-31 12:11:26 -07004647 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004648 }
Eric Laurent81784c32012-11-19 14:55:58 -08004649 }
4650
4651 // Finally let go of removed track(s), without the lock held
4652 // since we can't guarantee the destructors won't acquire that
4653 // same lock. This will also mutate and push a new fast mixer state.
4654 threadLoop_removeTracks(tracksToRemove);
4655 tracksToRemove.clear();
4656
4657 // FIXME I don't understand the need for this here;
4658 // it was in the original code but maybe the
4659 // assignment in saveOutputTracks() makes this unnecessary?
4660 clearOutputTracks();
4661
4662 // Effect chains will be actually deleted here if they were removed from
4663 // mEffectChains list during mixing or effects processing
4664 effectChains.clear();
4665
4666 // FIXME Note that the above .clear() is no longer necessary since effectChains
4667 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004668
4669 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004670 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004671 mThreadloopExecutor.process(); // process any remaining deferred actions.
4672 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004673
Eric Laurentbfb1b832013-01-07 09:53:42 -08004674 threadLoop_exit();
4675
Eric Laurentcf817a22014-08-04 20:36:31 -07004676 if (!mStandby) {
4677 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004678 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004679 }
4680
4681 releaseWakeLock();
4682
4683 ALOGV("Thread %p type %d exiting", this, mType);
4684 return false;
4685}
4686
Andy Hungee58e4a2023-07-07 13:47:37 -07004687void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004688{
Dean Wheatley12473e92021-03-18 23:00:55 +11004689 if (mStandby) {
4690 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4691 return;
4692 } else if (mHwPaused) {
4693 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4694 return;
4695 }
4696
4697 // Gather the framesReleased counters for all active tracks,
4698 // and associate with the sink frames written out. We need
4699 // this to convert the sink timestamp to the track timestamp.
4700 bool kernelLocationUpdate = false;
4701 ExtendedTimestamp timestamp; // use private copy to fetch
4702
4703 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4704 // HAL may be draining some small duration buffered data for fade out.
4705 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4706 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4707 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4708 mSampleRate);
4709
Andy Hungab65b182023-09-06 19:41:47 -07004710 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004711 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4712 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4713 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4714 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4715 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4716 = correctedTimestamp.mFrames;
4717 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4718 = correctedTimestamp.mTimeNs;
4719 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4720 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4721 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4722
4723 // Note: Downstream latency only added if timestamp correction enabled.
4724 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4725 const int64_t newPosition =
4726 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4727 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4728 // prevent retrograde
4729 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4730 newPosition,
4731 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4732 - mSuspendedFrames));
4733 }
4734 }
4735
4736 // We always fetch the timestamp here because often the downstream
4737 // sink will block while writing.
4738
4739 // We keep track of the last valid kernel position in case we are in underrun
4740 // and the normal mixer period is the same as the fast mixer period, or there
4741 // is some error from the HAL.
4742 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4743 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4744 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4745 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4746 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4747
4748 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4749 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4750 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4751 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4752 }
4753
4754 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4755 kernelLocationUpdate = true;
4756 } else {
4757 ALOGVV("getTimestamp error - no valid kernel position");
4758 }
4759
4760 // copy over kernel info
4761 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4762 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4763 + mSuspendedFrames; // add frames discarded when suspended
4764 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4765 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4766 } else {
4767 mTimestampVerifier.error();
4768 }
4769
4770 // mFramesWritten for non-offloaded tracks are contiguous
4771 // even after standby() is called. This is useful for the track frame
4772 // to sink frame mapping.
4773 bool serverLocationUpdate = false;
4774 if (mFramesWritten != mLastFramesWritten) {
4775 serverLocationUpdate = true;
4776 mLastFramesWritten = mFramesWritten;
4777 }
4778 // Only update timestamps if there is a meaningful change.
4779 // Either the kernel timestamp must be valid or we have written something.
4780 if (kernelLocationUpdate || serverLocationUpdate) {
4781 if (serverLocationUpdate) {
4782 // use the time before we called the HAL write - it is a bit more accurate
4783 // to when the server last read data than the current time here.
4784 //
4785 // If we haven't written anything, mLastIoBeginNs will be -1
4786 // and we use systemTime().
4787 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4788 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004789 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004790 }
4791
Andy Hung8d31fd22023-06-26 19:20:57 -07004792 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004793 if (!t->isFastTrack()) {
4794 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004795 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004796 mFramesWritten,
4797 mSampleRate,
4798 mTimestamp);
4799 }
4800 }
4801 }
4802
4803 if (audio_has_proportional_frames(mFormat)) {
4804 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4805 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4806 mLatencyMs.add(latencyMs);
4807 }
4808 }
4809#if 0
4810 // logFormat example
4811 if (z % 100 == 0) {
4812 timespec ts;
4813 clock_gettime(CLOCK_MONOTONIC, &ts);
4814 LOGT("This is an integer %d, this is a float %f, this is my "
4815 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4816 LOGT("A deceptive null-terminated string %\0");
4817 }
4818 ++z;
4819#endif
4820}
4821
Andy Hungc5007f82023-08-29 14:26:09 -07004822// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004823void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004824NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004825{
Andy Hung6c498e92023-12-05 17:28:17 -08004826 if (tracksToRemove.empty()) return;
4827
4828 // Block all incoming TrackHandle requests until we are finished with the release.
4829 setThreadBusy_l(true);
4830
Andy Hungfe726a62018-09-27 15:17:25 -07004831 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004832 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004833 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004834 if (chain != 0) {
4835 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4836 __func__, track->id(), chain.get(), track->sessionId());
4837 chain->decActiveTrackCnt();
4838 }
Andy Hung6c498e92023-12-05 17:28:17 -08004839
Andy Hungfe726a62018-09-27 15:17:25 -07004840 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004841 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004842 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004843 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004844 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004845 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004846 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004847 }
Andy Hung6c498e92023-12-05 17:28:17 -08004848 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004849 }
jiabineb3bda02020-06-30 14:07:03 -07004850 if (mHapticChannelCount > 0 &&
4851 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004852 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004853 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004854 // Unlock due to VibratorService will lock for this call and will
4855 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004856 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004857 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004858
4859 // When the track is stop, set the haptic intensity as MUTE
4860 // for the HapticGenerator effect.
4861 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004862 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004863 }
jiabin245cdd92018-12-07 17:55:15 -08004864 }
Andy Hung6c498e92023-12-05 17:28:17 -08004865
4866 // Under lock, the track is removed from the active tracks list.
4867 //
4868 // Once the track is no longer active, the TrackHandle may directly
4869 // modify it as the threadLoop() is no longer responsible for its maintenance.
4870 // Do not modify the track from threadLoop after the mutex is unlocked
4871 // if it is not active.
4872 mActiveTracks.remove(track);
4873
4874 if (track->isTerminated()) {
4875 // remove from our tracks vector
4876 removeTrack_l(track);
4877 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004878 }
Andy Hung6c498e92023-12-05 17:28:17 -08004879
4880 // Allow incoming TrackHandle requests. We still hold the mutex,
4881 // so pending TrackHandle requests will occur after we unlock it.
4882 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004883}
Eric Laurent81784c32012-11-19 14:55:58 -08004884
Andy Hungee58e4a2023-07-07 13:47:37 -07004885status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004886{
4887 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004888 ExtendedTimestamp ets;
4889 status_t status = mNormalSink->getTimestamp(ets);
4890 if (status == NO_ERROR) {
4891 status = ets.getBestTimestamp(&timestamp);
4892 }
4893 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004894 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004895 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004896 collectTimestamps_l();
4897 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4898 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004899 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004900 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4901 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4902 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4903 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4904 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004905 }
4906 return INVALID_OPERATION;
4907}
Eric Laurent1c333e22014-05-20 10:48:17 -07004908
Eric Laurenteab90452019-06-24 15:17:46 -07004909// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4910// still applied by the mixer.
4911// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4912// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4913// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004914status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004915{
4916 status_t result = NO_ERROR;
4917 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4918 if (*volume != mLeftVolFloat) {
4919 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004920 // HAL can return INVALID_OPERATION if operation is not supported.
4921 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004922 "Error when setting output stream volume: %d", result);
4923 if (result == NO_ERROR) {
4924 mLeftVolFloat = *volume;
4925 }
4926 }
4927 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4928 // remove stream volume contribution from software volume.
4929 if (mLeftVolFloat == *volume) {
4930 *volume = 1.0f;
4931 }
4932 }
4933 return result;
4934}
4935
Andy Hungee58e4a2023-07-07 13:47:37 -07004936status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004937 audio_patch_handle_t *handle)
4938{
Andy Hungf60abce2016-08-26 11:37:54 -07004939 status_t status;
4940 if (property_get_bool("af.patch_park", false /* default_value */)) {
4941 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4942 // or if HAL does not properly lock against access.
4943 AutoPark<FastMixer> park(mFastMixer);
4944 status = PlaybackThread::createAudioPatch_l(patch, handle);
4945 } else {
4946 status = PlaybackThread::createAudioPatch_l(patch, handle);
4947 }
Eric Laurentb0463942022-12-20 16:31:10 +01004948
4949 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004950 return status;
4951}
4952
Andy Hungee58e4a2023-07-07 13:47:37 -07004953status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004954 audio_patch_handle_t *handle)
4955{
4956 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004957
4958 // store new device and send to effects
4959 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004960 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004961 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004962 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4963 && !mOutput->audioHwDev->supportsAudioPatches(),
4964 "Enumerated device type(%#x) must not be used "
4965 "as it does not support audio patches",
4966 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004967 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004968 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4969 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004970 }
4971
François Gaffie0c280aa2018-07-25 10:02:15 +02004972 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004973#ifdef ADD_BATTERY_DATA
4974 // when changing the audio output device, call addBatteryData to notify
4975 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004976 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004977 uint32_t params = 0;
4978 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004979 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004980 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004981 }
4982
Eric Laurent054d9d32015-04-24 08:48:48 -07004983 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004984 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004985 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4986 }
4987
4988 if (params != 0) {
4989 addBatteryData(params);
4990 }
4991 }
4992#endif
4993
4994 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004995 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004996 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004997
jiabinc52b1ff2019-10-31 17:20:42 -07004998 // mPatch.num_sinks is not set when the thread is created so that
4999 // the first patch creation triggers an ioConfigChanged callback
5000 bool configChanged = (mPatch.num_sinks == 0) ||
5001 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005002 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005003 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005004 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005005
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005006 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005007 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5008 status = hwDevice->createAudioPatch(patch->num_sources,
5009 patch->sources,
5010 patch->num_sinks,
5011 patch->sinks,
5012 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005013 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005014 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005015 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005016 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005017 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005018
5019 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005020 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005021 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005022 // also dispatch to active AudioTracks for MediaMetrics
5023 for (const auto &track : mActiveTracks) {
5024 track->logEndInterval();
5025 track->logBeginInterval(patchSinksAsString);
5026 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005027
Eric Laurente8726fe2015-06-26 09:39:24 -07005028 if (configChanged) {
5029 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5030 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005031 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005032 mActiveTracks.setHasChanged();
5033
Eric Laurent1c333e22014-05-20 10:48:17 -07005034 return status;
5035}
5036
Andy Hungee58e4a2023-07-07 13:47:37 -07005037status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005038{
Andy Hungf60abce2016-08-26 11:37:54 -07005039 status_t status;
5040 if (property_get_bool("af.patch_park", false /* default_value */)) {
5041 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5042 // or if HAL does not properly lock against access.
5043 AutoPark<FastMixer> park(mFastMixer);
5044 status = PlaybackThread::releaseAudioPatch_l(handle);
5045 } else {
5046 status = PlaybackThread::releaseAudioPatch_l(handle);
5047 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005048 return status;
5049}
5050
Andy Hungee58e4a2023-07-07 13:47:37 -07005051status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005052{
5053 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005054
jiabinc52b1ff2019-10-31 17:20:42 -07005055 mPatch = audio_patch{};
5056 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005057
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005058 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005059 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5060 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005061 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005062 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005063 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005064 // Force meteadata update after a route change
5065 mActiveTracks.setHasChanged();
5066
Eric Laurent1c333e22014-05-20 10:48:17 -07005067 return status;
5068}
5069
Andy Hungee58e4a2023-07-07 13:47:37 -07005070void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005071{
Andy Hung972bec12023-08-31 16:13:39 -07005072 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005073 mTracks.add(track);
5074}
5075
Andy Hungee58e4a2023-07-07 13:47:37 -07005076void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005077{
Andy Hung972bec12023-08-31 16:13:39 -07005078 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005079 destroyTrack_l(track);
5080}
5081
Andy Hungee58e4a2023-07-07 13:47:37 -07005082void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005083{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005084 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005085 config->role = AUDIO_PORT_ROLE_SOURCE;
5086 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5087 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005088 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5089 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5090 config->flags.output = mOutput->flags;
5091 }
Eric Laurent83b88082014-06-20 18:31:16 -07005092}
5093
Eric Laurent81784c32012-11-19 14:55:58 -08005094// ----------------------------------------------------------------------------
5095
Andy Hungee58e4a2023-07-07 13:47:37 -07005096/* static */
5097sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005098 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005099 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005100 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005101}
5102
Andy Hung583043b2023-07-17 17:05:00 -07005103MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005104 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005105 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005106 // mAudioMixer below
5107 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005108 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005109 mFastMixerFutex(0),
5110 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005111 // mOutputSink below
5112 // mPipeSink below
5113 // mNormalSink below
5114{
jiabinc52b1ff2019-10-31 17:20:42 -07005115 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005116 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005117 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005118 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5119 mNormalFrameCount);
5120 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5121
Andy Hungfbfc3952015-01-15 13:33:51 -08005122 if (type == DUPLICATING) {
5123 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5124 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5125 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005126 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5127 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005128 return;
5129 }
Eric Laurent81784c32012-11-19 14:55:58 -08005130 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005131 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005132 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005133 const NBAIO_Format offers[1] = {Format_from_SR_C(
5134 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005135#if !LOG_NDEBUG
5136 ssize_t index =
5137#else
5138 (void)
5139#endif
5140 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005141 ALOG_ASSERT(index == 0);
5142
5143 // initialize fast mixer depending on configuration
5144 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005145 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005146 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005147 } else {
5148 switch (kUseFastMixer) {
5149 case FastMixer_Never:
5150 initFastMixer = false;
5151 break;
5152 case FastMixer_Always:
5153 initFastMixer = true;
5154 break;
5155 case FastMixer_Static:
5156 case FastMixer_Dynamic:
5157 initFastMixer = mFrameCount < mNormalFrameCount;
5158 break;
5159 }
5160 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5161 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5162 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005163 }
5164 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005165 audio_format_t fastMixerFormat;
5166 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5167 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5168 } else {
5169 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5170 }
5171 if (mFormat != fastMixerFormat) {
5172 // change our Sink format to accept our intermediate precision
5173 mFormat = fastMixerFormat;
5174 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005175 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005176 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5177 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5178 }
Eric Laurent81784c32012-11-19 14:55:58 -08005179
5180 // create a MonoPipe to connect our submix to FastMixer
5181 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005182
Andy Hung1258c1a2014-05-23 21:22:17 -07005183 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005184 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005185 format.mFormat = fastMixerFormat;
5186 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5187
Eric Laurent81784c32012-11-19 14:55:58 -08005188 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5189 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5190 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5191 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005192 const NBAIO_Format offersFast[1] = {format};
5193 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005194#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005195 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005196#else
5197 (void)
5198#endif
Andy Hung920f6572022-10-06 12:09:49 -07005199 monoPipe->negotiate(offersFast, std::size(offersFast),
5200 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005201 ALOG_ASSERT(index == 0);
5202 monoPipe->setAvgFrames((mScreenState & 1) ?
5203 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5204 mPipeSink = monoPipe;
5205
Eric Laurent81784c32012-11-19 14:55:58 -08005206 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005207 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005208 FastMixerStateQueue *sq = mFastMixer->sq();
5209#ifdef STATE_QUEUE_DUMP
5210 sq->setObserverDump(&mStateQueueObserverDump);
5211 sq->setMutatorDump(&mStateQueueMutatorDump);
5212#endif
5213 FastMixerState *state = sq->begin();
5214 FastTrack *fastTrack = &state->mFastTracks[0];
5215 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5216 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5217 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005218 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5219 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5220 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005221 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005222 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005223 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005224 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005225 fastTrack->mGeneration++;
5226 state->mFastTracksGen++;
5227 state->mTrackMask = 1;
5228 // fast mixer will use the HAL output sink
5229 state->mOutputSink = mOutputSink.get();
5230 state->mOutputSinkGen++;
5231 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005232 // specify sink channel mask when haptic channel mask present as it can not
5233 // be calculated directly from channel count
5234 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005235 ? AUDIO_CHANNEL_NONE
5236 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005237 state->mCommand = FastMixerState::COLD_IDLE;
5238 // already done in constructor initialization list
5239 //mFastMixerFutex = 0;
5240 state->mColdFutexAddr = &mFastMixerFutex;
5241 state->mColdGen++;
5242 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005243 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005244 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005245 sq->end();
5246 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5247
Eric Tan0513b5d2018-09-17 10:32:48 -07005248 NBLog::thread_info_t info;
5249 info.id = mId;
5250 info.type = NBLog::FASTMIXER;
5251 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5252
Eric Laurent81784c32012-11-19 14:55:58 -08005253 // start the fast mixer
5254 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5255 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005256 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005257 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005258
5259#ifdef AUDIO_WATCHDOG
5260 // create and start the watchdog
5261 mAudioWatchdog = new AudioWatchdog();
5262 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5263 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5264 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005265 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005266#endif
Andy Hung8946a282018-04-19 20:04:56 -07005267 } else {
5268#ifdef TEE_SINK
5269 // Only use the MixerThread tee if there is no FastMixer.
5270 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5271 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5272#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005273 }
5274
5275 switch (kUseFastMixer) {
5276 case FastMixer_Never:
5277 case FastMixer_Dynamic:
5278 mNormalSink = mOutputSink;
5279 break;
5280 case FastMixer_Always:
5281 mNormalSink = mPipeSink;
5282 break;
5283 case FastMixer_Static:
5284 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5285 break;
5286 }
Andy Hung922617c2024-06-25 17:07:58 -07005287 // setMasterBalance needs to be called after the FastMixer
5288 // (if any) is set up, in order to deliver the balance settings to it.
5289 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005290}
5291
Andy Hungee58e4a2023-07-07 13:47:37 -07005292MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005293{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005294 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005295 FastMixerStateQueue *sq = mFastMixer->sq();
5296 FastMixerState *state = sq->begin();
5297 if (state->mCommand == FastMixerState::COLD_IDLE) {
5298 int32_t old = android_atomic_inc(&mFastMixerFutex);
5299 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005300 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005301 }
5302 }
5303 state->mCommand = FastMixerState::EXIT;
5304 sq->end();
5305 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5306 mFastMixer->join();
5307 // Though the fast mixer thread has exited, it's state queue is still valid.
5308 // We'll use that extract the final state which contains one remaining fast track
5309 // corresponding to our sub-mix.
5310 state = sq->begin();
5311 ALOG_ASSERT(state->mTrackMask == 1);
5312 FastTrack *fastTrack = &state->mFastTracks[0];
5313 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5314 delete fastTrack->mBufferProvider;
5315 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005316 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005317#ifdef AUDIO_WATCHDOG
5318 if (mAudioWatchdog != 0) {
5319 mAudioWatchdog->requestExit();
5320 mAudioWatchdog->requestExitAndWait();
5321 mAudioWatchdog.clear();
5322 }
5323#endif
5324 }
Andy Hung583043b2023-07-17 17:05:00 -07005325 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005326 delete mAudioMixer;
5327}
5328
Andy Hungee58e4a2023-07-07 13:47:37 -07005329void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005330 PlaybackThread::onFirstRef();
5331
Andy Hung972bec12023-08-31 16:13:39 -07005332 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005333 if (mOutput != nullptr && mOutput->stream != nullptr) {
5334 status_t status = mOutput->stream->setLatencyModeCallback(this);
5335 if (status != INVALID_OPERATION) {
5336 updateHalSupportedLatencyModes_l();
5337 }
5338 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5339 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5340 mBluetoothLatencyModesEnabled.store(
5341 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5342 }
5343}
Eric Laurent81784c32012-11-19 14:55:58 -08005344
Andy Hungee58e4a2023-07-07 13:47:37 -07005345uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005346{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005347 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005348 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5349 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5350 }
5351 return latency;
5352}
5353
Andy Hungee58e4a2023-07-07 13:47:37 -07005354ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005355{
5356 // FIXME we should only do one push per cycle; confirm this is true
5357 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005358 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005359 FastMixerStateQueue *sq = mFastMixer->sq();
5360 FastMixerState *state = sq->begin();
5361 if (state->mCommand != FastMixerState::MIX_WRITE &&
5362 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5363 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005364
5365 // FIXME workaround for first HAL write being CPU bound on some devices
5366 ATRACE_BEGIN("write");
5367 mOutput->write((char *)mSinkBuffer, 0);
5368 ATRACE_END();
5369
Eric Laurent81784c32012-11-19 14:55:58 -08005370 int32_t old = android_atomic_inc(&mFastMixerFutex);
5371 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005372 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005373 }
5374#ifdef AUDIO_WATCHDOG
5375 if (mAudioWatchdog != 0) {
5376 mAudioWatchdog->resume();
5377 }
5378#endif
5379 }
5380 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005381#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005382 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005383 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005384#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005385 sq->end();
5386 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5387 if (kUseFastMixer == FastMixer_Dynamic) {
5388 mNormalSink = mPipeSink;
5389 }
5390 } else {
5391 sq->end(false /*didModify*/);
5392 }
5393 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005394 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005395}
5396
Andy Hungee58e4a2023-07-07 13:47:37 -07005397void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005398{
5399 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005400 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005401 FastMixerStateQueue *sq = mFastMixer->sq();
5402 FastMixerState *state = sq->begin();
5403 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005404 // Report any frames trapped in the Monopipe
5405 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5406 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5407 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5408 "monoPipeWritten:%lld monoPipeLeft:%lld",
5409 (long long)mFramesWritten, (long long)mSuspendedFrames,
5410 (long long)mPipeSink->framesWritten(), pipeFrames);
5411 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5412
Eric Laurent81784c32012-11-19 14:55:58 -08005413 state->mCommand = FastMixerState::COLD_IDLE;
5414 state->mColdFutexAddr = &mFastMixerFutex;
5415 state->mColdGen++;
5416 mFastMixerFutex = 0;
5417 sq->end();
5418 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5419 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5420 if (kUseFastMixer == FastMixer_Dynamic) {
5421 mNormalSink = mOutputSink;
5422 }
5423#ifdef AUDIO_WATCHDOG
5424 if (mAudioWatchdog != 0) {
5425 mAudioWatchdog->pause();
5426 }
5427#endif
5428 } else {
5429 sq->end(false /*didModify*/);
5430 }
5431 }
5432 PlaybackThread::threadLoop_standby();
5433}
5434
Andy Hungee58e4a2023-07-07 13:47:37 -07005435bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005436{
5437 return false;
5438}
5439
Andy Hungee58e4a2023-07-07 13:47:37 -07005440bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441{
5442 return !mStandby;
5443}
5444
Andy Hungee58e4a2023-07-07 13:47:37 -07005445bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446{
Andy Hung972bec12023-08-31 16:13:39 -07005447 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448 return waitingAsyncCallback_l();
5449}
5450
Eric Laurent81784c32012-11-19 14:55:58 -08005451// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005452void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005453{
Andy Hung8d672e02023-09-15 18:19:28 -07005454 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5455 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005456 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005457 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005458 // discard any pending drain or write ack by incrementing sequence
5459 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5460 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005461 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005462 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5463 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005464 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005465 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005466 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005467}
5468
Andy Hungee58e4a2023-07-07 13:47:37 -07005469void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005470{
5471 ALOGV("signal playback thread");
5472 broadcast_l();
5473}
5474
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005475void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005476{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005477 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005478 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5479 invalidateTracks((audio_stream_type_t)i);
5480 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005481 if (isHardError) {
5482 mAfThreadCallback->onHardError(allTrackPortIds);
5483 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005484}
5485
Andy Hungee58e4a2023-07-07 13:47:37 -07005486void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005487{
Eric Laurent81784c32012-11-19 14:55:58 -08005488 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005489 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005490 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005491 // increase sleep time progressively when application underrun condition clears.
5492 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5493 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5494 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005495 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005496 sleepTimeShift--;
5497 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005498 mSleepTimeUs = 0;
5499 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005500 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005501
Eric Laurent81784c32012-11-19 14:55:58 -08005502}
5503
Andy Hungee58e4a2023-07-07 13:47:37 -07005504void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005505{
5506 // If no tracks are ready, sleep once for the duration of an output
5507 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005508 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005509 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005510 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5511 // Using the Monopipe availableToWrite, we estimate the
5512 // sleep time to retry for more data (before we underrun).
5513 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5514 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5515 const size_t pipeFrames = monoPipe->maxFrames();
5516 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5517 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5518 const size_t framesDelay = std::min(
5519 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5520 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5521 pipeFrames, framesLeft, framesDelay);
5522 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5523 } else {
5524 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5525 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5526 mSleepTimeUs = kMinThreadSleepTimeUs;
5527 }
5528 // reduce sleep time in case of consecutive application underruns to avoid
5529 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5530 // duration we would end up writing less data than needed by the audio HAL if
5531 // the condition persists.
5532 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5533 sleepTimeShift++;
5534 }
Eric Laurent81784c32012-11-19 14:55:58 -08005535 }
5536 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005537 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005538 }
5539 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005540 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5541 // before effects processing or output.
5542 if (mMixerBufferValid) {
5543 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005544 if (mType == SPATIALIZER) {
5545 memset(mSinkBuffer, 0, mSinkBufferSize);
5546 }
Andy Hung98ef9782014-03-04 14:46:50 -08005547 } else {
5548 memset(mSinkBuffer, 0, mSinkBufferSize);
5549 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005550 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005551 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5552 "anticipated start");
5553 }
5554 // TODO add standby time extension fct of effect tail
5555}
5556
Andy Hungc5007f82023-08-29 14:26:09 -07005557// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005558PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005559 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005560{
Andy Hungc0691382018-09-12 18:01:57 -07005561 // clean up deleted track ids in AudioMixer before allocating new tracks
5562 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5563 // for each trackId, destroy it in the AudioMixer
5564 if (mAudioMixer->exists(trackId)) {
5565 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005566 }
5567 });
Andy Hungc0691382018-09-12 18:01:57 -07005568 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005569
5570 mixer_state mixerStatus = MIXER_IDLE;
5571 // find out which tracks need to be processed
5572 size_t count = mActiveTracks.size();
5573 size_t mixedTracks = 0;
5574 size_t tracksWithEffect = 0;
5575 // counts only _active_ fast tracks
5576 size_t fastTracks = 0;
5577 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5578
5579 float masterVolume = mMasterVolume;
5580 bool masterMute = mMasterMute;
5581
5582 if (masterMute) {
5583 masterVolume = 0;
5584 }
5585 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005586 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005587 if (chain != 0) {
5588 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005589 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005590 masterVolume = (float)((v + (1 << 23)) >> 24);
5591 chain.clear();
5592 }
5593
5594 // prepare a new state to push
5595 FastMixerStateQueue *sq = NULL;
5596 FastMixerState *state = NULL;
5597 bool didModify = false;
5598 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005599 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005600 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005601 sq = mFastMixer->sq();
5602 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005603 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005604 }
5605
Andy Hung69aed5f2014-02-25 17:24:40 -08005606 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005607 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005608
Andy Hungbd3b2b02018-05-21 10:53:11 -07005609 // DeferredOperations handles statistics after setting mixerStatus.
5610 class DeferredOperations {
5611 public:
Andy Hungea840382020-05-05 21:50:17 -07005612 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5613 : mMixerStatus(mixerStatus)
5614 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005615
5616 // when leaving scope, tally frames properly.
5617 ~DeferredOperations() {
5618 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5619 // because that is when the underrun occurs.
5620 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005621 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005622 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005623 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005624 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005625 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005626 }
5627 }
Andy Hungea840382020-05-05 21:50:17 -07005628 // send the max underrun frames for this mixer period
5629 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005630 }
5631
5632 // tallyUnderrunFrames() is called to update the track counters
5633 // with the number of underrun frames for a particular mixer period.
5634 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005635 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005636 mUnderrunFrames.emplace_back(track, underrunFrames);
5637 }
5638
5639 private:
5640 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005641 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005642 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005643 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005644 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005645
jiabin245cdd92018-12-07 17:55:15 -08005646 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005647 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005648 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005649
5650 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005651 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005652
5653 // process fast tracks
5654 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005655 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5656 "%s(%d): FastTrack(%d) present without FastMixer",
5657 __func__, id(), track->id());
5658
jiabin245cdd92018-12-07 17:55:15 -08005659 if (track->getHapticPlaybackEnabled()) {
5660 noFastHapticTrack = false;
5661 }
Eric Laurent81784c32012-11-19 14:55:58 -08005662
5663 // It's theoretically possible (though unlikely) for a fast track to be created
5664 // and then removed within the same normal mix cycle. This is not a problem, as
5665 // the track never becomes active so it's fast mixer slot is never touched.
5666 // The converse, of removing an (active) track and then creating a new track
5667 // at the identical fast mixer slot within the same normal mix cycle,
5668 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005669 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005670 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005671 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5672 FastTrack *fastTrack = &state->mFastTracks[j];
5673
5674 // Determine whether the track is currently in underrun condition,
5675 // and whether it had a recent underrun.
5676 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5677 FastTrackUnderruns underruns = ftDump->mUnderruns;
5678 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005679 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005680 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005681 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005682 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005683 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005684 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005685 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005686 // don't count underruns that occur while stopping or pausing
5687 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005688 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005689 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5690 recentUnderruns > 0) {
5691 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005692 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005693 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005694 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005695 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005696
5697 // This is similar to the state machine for normal tracks,
5698 // with a few modifications for fast tracks.
5699 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005700 switch (track->state()) {
5701 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005702 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005703 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005704 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005705 }
5706 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005707 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005708 // ramp down is not yet implemented
5709 track->setPaused();
5710 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005711 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005712 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005713 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005714 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005715 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005716 if (recentFull > 0 || recentPartial > 0) {
5717 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005718 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005719 }
5720 if (recentUnderruns == 0) {
5721 // no recent underruns: stay active
5722 break;
5723 }
5724 // there has recently been an underrun of some kind
5725 if (track->sharedBuffer() == 0) {
5726 // were any of the recent underruns "empty" (no frames available)?
5727 if (recentEmpty == 0) {
5728 // no, then ignore the partial underruns as they are allowed indefinitely
5729 break;
5730 }
5731 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005732 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005733 break;
5734 }
5735 // indicate to client process that the track was disabled because of underrun;
5736 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005737 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005738 // remove from active list, but state remains ACTIVE [confusing but true]
5739 isActive = false;
5740 break;
5741 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005742 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005743 case IAfTrackBase::STOPPING_2:
5744 case IAfTrackBase::PAUSED:
5745 case IAfTrackBase::STOPPED:
5746 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005747 // Check for presentation complete if track is inactive
5748 // We have consumed all the buffers of this track.
5749 // This would be incomplete if we auto-paused on underrun
5750 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005751 uint32_t latency = 0;
5752 status_t result = mOutput->stream->getLatency(&latency);
5753 ALOGE_IF(result != OK,
5754 "Error when retrieving output stream latency: %d", result);
5755 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005756 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005757 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5758 // track stays in active list until presentation is complete
5759 break;
5760 }
5761 }
5762 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005763 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005764 }
5765 if (track->isStopped()) {
5766 // Can't reset directly, as fast mixer is still polling this track
5767 // track->reset();
5768 // So instead mark this track as needing to be reset after push with ack
5769 resetMask |= 1 << i;
5770 }
5771 isActive = false;
5772 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005773 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005774 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005775 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005776 }
5777
5778 if (isActive) {
5779 // was it previously inactive?
5780 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005781 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5782 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005783 fastTrack->mBufferProvider = eabp;
5784 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005785 fastTrack->mChannelMask = track->channelMask();
5786 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005787 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005788 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005789 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005790 fastTrack->mGeneration++;
5791 state->mTrackMask |= 1 << j;
5792 didModify = true;
5793 // no acknowledgement required for newly active tracks
5794 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005795 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005796 float volume;
Eric Laurent277a37e2024-07-29 18:37:52 +00005797 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5798 volume = 0.f;
Eric Laurenteab90452019-06-24 15:17:46 -07005799 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +00005800 volume = masterVolume * mStreamTypes[track->streamType()].volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005801 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005802
Eric Laurenteab90452019-06-24 15:17:46 -07005803 handleVoipVolume_l(&volume);
5804
Eric Laurent81784c32012-11-19 14:55:58 -08005805 // cache the combined master volume and stream type volume for fast mixer; this
5806 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005807 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005808 proxy->framesReleased()).first;
5809 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005810 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005811 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005812 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5813 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent277a37e2024-07-29 18:37:52 +00005814
5815 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5816 /*muteState=*/{masterVolume == 0.f,
5817 mStreamTypes[track->streamType()].volume == 0.f,
5818 mStreamTypes[track->streamType()].mute,
5819 track->isPlaybackRestricted(),
5820 vlf == 0.f && vrf == 0.f,
5821 vh == 0.f});
5822
Vlad Popae2f5aef2022-07-25 16:00:20 +02005823 vlf *= volume;
5824 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005825
jiabin220eea12024-05-17 17:55:20 +00005826 if (track->getInternalMute()) {
5827 vlf = 0.f;
5828 vrf = 0.f;
5829 }
5830
jiabin76d94692022-12-15 21:51:21 +00005831 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005832 ++fastTracks;
5833 } else {
5834 // was it previously active?
5835 if (state->mTrackMask & (1 << j)) {
5836 fastTrack->mBufferProvider = NULL;
5837 fastTrack->mGeneration++;
5838 state->mTrackMask &= ~(1 << j);
5839 didModify = true;
5840 // If any fast tracks were removed, we must wait for acknowledgement
5841 // because we're about to decrement the last sp<> on those tracks.
5842 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5843 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005844 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5845 // AudioTrack may start (which may not be with a start() but with a write()
5846 // after underrun) and immediately paused or released. In that case the
5847 // FastTrack state hasn't had time to update.
5848 // TODO Remove the ALOGW when this theory is confirmed.
5849 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005850 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005851 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005852 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005853 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005854 }
5855 tracksToRemove->add(track);
5856 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005857 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005858 }
jiabin245cdd92018-12-07 17:55:15 -08005859 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5860 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5861 didModify = true;
5862 }
Eric Laurent81784c32012-11-19 14:55:58 -08005863 continue;
5864 }
5865
5866 { // local variable scope to avoid goto warning
5867
5868 audio_track_cblk_t* cblk = track->cblk();
5869
5870 // The first time a track is added we wait
5871 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005872 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005873
5874 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005875 // use the trackId as the AudioMixer name.
5876 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005877 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005878 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005879 track->channelMask(),
5880 track->format(),
5881 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005882 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005883 ALOGW("%s(): AudioMixer cannot create track(%d)"
5884 " mask %#x, format %#x, sessionId %d",
5885 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005886 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005887 tracksToRemove->add(track);
5888 track->invalidate(); // consider it dead.
5889 continue;
5890 }
5891 }
5892
Eric Laurent81784c32012-11-19 14:55:58 -08005893 // make sure that we have enough frames to mix one full buffer.
5894 // enforce this condition only once to enable draining the buffer in case the client
5895 // app does not call stop() and relies on underrun to stop:
5896 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5897 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005898 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005899 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5900 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005901
5902 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005903 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005904 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5905 // add frames already consumed but not yet released by the resampler
5906 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005907 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005908
Eric Laurent81784c32012-11-19 14:55:58 -08005909 uint32_t minFrames = 1;
5910 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5911 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005912 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005913 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005914
5915 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005916 if (ATRACE_ENABLED()) {
5917 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005918 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005919 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005920 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005921 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005922 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005923 !track->isPaused() && !track->isTerminated())
5924 {
Andy Hungc0691382018-09-12 18:01:57 -07005925 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005926
5927 mixedTracks++;
5928
Shunkai Yaof4847652024-01-12 00:25:20 +00005929 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005930 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005931 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005932 if (track->mainBuffer() != mSinkBuffer &&
5933 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005934 if (mEffectBufferEnabled) {
5935 mEffectBufferValid = true; // Later can set directly.
5936 }
Eric Laurent81784c32012-11-19 14:55:58 -08005937 chain = getEffectChain_l(track->sessionId());
5938 // Delegate volume control to effect in track effect chain if needed
5939 if (chain != 0) {
5940 tracksWithEffect++;
5941 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005942 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005943 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005944 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005945 }
5946 }
5947
5948
5949 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005950 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005951 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005952 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5953 if (track->state() == IAfTrackBase::RESUMING) {
5954 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005955 // If a new track is paused immediately after start, do not ramp on resume.
5956 if (cblk->mServer != 0) {
5957 param = AudioMixer::RAMP_VOLUME;
5958 }
Eric Laurent81784c32012-11-19 14:55:58 -08005959 }
Andy Hungc0691382018-09-12 18:01:57 -07005960 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005961 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005962 // FIXME should not make a decision based on mServer
5963 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005964 // If the track is stopped before the first frame was mixed,
5965 // do not apply ramp
5966 param = AudioMixer::RAMP_VOLUME;
5967 }
5968
5969 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005970 uint32_t vl, vr; // in U8.24 integer format
5971 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005972 // read original volumes with volume control
Eric Laurent277a37e2024-07-29 18:37:52 +00005973 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005974 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005975 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005976 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005977 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent277a37e2024-07-29 18:37:52 +00005978
5979 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5980 v = 0;
Eric Laurenteab90452019-06-24 15:17:46 -07005981 }
Eric Laurent277a37e2024-07-29 18:37:52 +00005982
Eric Laurenteab90452019-06-24 15:17:46 -07005983 handleVoipVolume_l(&v);
5984
5985 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005986 vl = vr = 0;
5987 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005988 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005989 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005990 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005991 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5992 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005993 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005994 if (vlf > GAIN_FLOAT_UNITY) {
5995 ALOGV("Track left volume out of range: %.3g", vlf);
5996 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005997 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005998 if (vrf > GAIN_FLOAT_UNITY) {
5999 ALOGV("Track right volume out of range: %.3g", vrf);
6000 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006001 }
Eric Laurent277a37e2024-07-29 18:37:52 +00006002
6003 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6004 /*muteState=*/{masterVolume == 0.f,
6005 mStreamTypes[track->streamType()].volume == 0.f,
6006 mStreamTypes[track->streamType()].mute,
6007 track->isPlaybackRestricted(),
6008 vlf == 0.f && vrf == 0.f,
6009 vh == 0.f});
6010
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006011 // now apply the master volume and stream type volume and shaper volume
6012 vlf *= v * vh;
6013 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006014 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006015 // then derive vl and vr as U8.24 versions for the effect chain
6016 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6017 vl = (uint32_t) (scaleto8_24 * vlf);
6018 vr = (uint32_t) (scaleto8_24 * vrf);
6019 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006020 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006021 // send level comes from shared memory and so may be corrupt
6022 if (sendLevel > MAX_GAIN_INT) {
6023 ALOGV("Track send level out of range: %04X", sendLevel);
6024 sendLevel = MAX_GAIN_INT;
6025 }
Andy Hung6be49402014-05-30 10:42:03 -07006026 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6027 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006028 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006029
jiabin220eea12024-05-17 17:55:20 +00006030 if (track->getInternalMute()) {
6031 vrf = 0.f;
6032 vlf = 0.f;
6033 }
6034
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006035 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006036
Eric Laurent81784c32012-11-19 14:55:58 -08006037 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006038 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006039 // Do not ramp volume if volume is controlled by effect
6040 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006041 // Update remaining floating point volume levels
6042 vlf = (float)vl / (1 << 24);
6043 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006044 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006045 } else {
6046 // force no volume ramp when volume controller was just disabled or removed
6047 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006048 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006049 param = AudioMixer::VOLUME;
6050 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006051 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006052 }
6053
Eric Laurent81784c32012-11-19 14:55:58 -08006054 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006055 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006056 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006057
Andy Hungc0691382018-09-12 18:01:57 -07006058 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6059 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6060 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006061 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006062 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006063 AudioMixer::TRACK,
6064 AudioMixer::FORMAT, (void *)track->format());
6065 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006066 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006067 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006068 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006069
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006070 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006071 mAudioMixer->setParameter(
6072 trackId,
6073 AudioMixer::TRACK,
6074 AudioMixer::MIXER_CHANNEL_MASK,
6075 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6076 } else {
6077 mAudioMixer->setParameter(
6078 trackId,
6079 AudioMixer::TRACK,
6080 AudioMixer::MIXER_CHANNEL_MASK,
6081 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6082 }
6083
Glenn Kastene3aa6592012-12-04 12:22:46 -08006084 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006085 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006086 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006087 if (reqSampleRate == 0) {
6088 reqSampleRate = mSampleRate;
6089 } else if (reqSampleRate > maxSampleRate) {
6090 reqSampleRate = maxSampleRate;
6091 }
Eric Laurent81784c32012-11-19 14:55:58 -08006092 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006093 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006094 AudioMixer::RESAMPLE,
6095 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006096 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006097
Andy Hung8edb8dc2015-03-26 19:13:55 -07006098 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006099 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006100 AudioMixer::TIMESTRETCH,
6101 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006102 // cast away constness for this generic API.
6103 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006104
Andy Hung69aed5f2014-02-25 17:24:40 -08006105 /*
6106 * Select the appropriate output buffer for the track.
6107 *
Andy Hung98ef9782014-03-04 14:46:50 -08006108 * Tracks with effects go into their own effects chain buffer
6109 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006110 *
6111 * Other tracks can use mMixerBuffer for higher precision
6112 * channel accumulation. If this buffer is enabled
6113 * (mMixerBufferEnabled true), then selected tracks will accumulate
6114 * into it.
6115 *
6116 */
6117 if (mMixerBufferEnabled
6118 && (track->mainBuffer() == mSinkBuffer
6119 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006120 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006121 mAudioMixer->setParameter(
6122 trackId,
6123 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006124 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006125 mAudioMixer->setParameter(
6126 trackId,
6127 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006128 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006129 } else {
6130 mAudioMixer->setParameter(
6131 trackId,
6132 AudioMixer::TRACK,
6133 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6134 mAudioMixer->setParameter(
6135 trackId,
6136 AudioMixer::TRACK,
6137 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6138 // TODO: override track->mainBuffer()?
6139 mMixerBufferValid = true;
6140 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006141 } else {
6142 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006143 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006144 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006145 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006146 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006147 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006148 AudioMixer::TRACK,
6149 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6150 }
Eric Laurent81784c32012-11-19 14:55:58 -08006151 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006152 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006153 AudioMixer::TRACK,
6154 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006155 mAudioMixer->setParameter(
6156 trackId,
6157 AudioMixer::TRACK,
6158 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006159 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006160 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006161 trackId,
6162 AudioMixer::TRACK,
6163 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006164 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006165 mAudioMixer->setParameter(
6166 trackId,
6167 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006168 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006169
6170 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006171 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006172
6173 // If one track is ready, set the mixer ready if:
6174 // - the mixer was not ready during previous round OR
6175 // - no other track is not ready
6176 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6177 mixerStatus != MIXER_TRACKS_ENABLED) {
6178 mixerStatus = MIXER_TRACKS_READY;
6179 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006180
6181 // Enable the next few lines to instrument a test for underrun log handling.
6182 // TODO: Remove when we have a better way of testing the underrun log.
6183#if 0
6184 static int i;
6185 if ((++i & 0xf) == 0) {
6186 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6187 }
6188#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006189 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006190 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006191 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006192 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6193 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006194 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006195 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006196 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006197
Eric Laurent81784c32012-11-19 14:55:58 -08006198 // clear effect chain input buffer if an active track underruns to avoid sending
6199 // previous audio buffer again to effects
6200 chain = getEffectChain_l(track->sessionId());
6201 if (chain != 0) {
6202 chain->clearInputBuffer();
6203 }
6204
Andy Hungc0691382018-09-12 18:01:57 -07006205 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006206 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6207 track->isStopped() || track->isPaused()) {
6208 // We have consumed all the buffers of this track.
6209 // Remove it from the list of active tracks.
6210 // TODO: use actual buffer filling status instead of latency when available from
6211 // audio HAL
6212 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006213 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006214 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6215 if (track->isStopped()) {
6216 track->reset();
6217 }
6218 tracksToRemove->add(track);
6219 }
6220 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006221 // No buffers for this track. Give it a few chances to
6222 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006223 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006224 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6225 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006226 tracksToRemove->add(track);
6227 // indicate to client process that the track was disabled because of underrun;
6228 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006229 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006230 // If one track is not ready, mark the mixer also not ready if:
6231 // - the mixer was ready during previous round OR
6232 // - no other track is ready
6233 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6234 mixerStatus != MIXER_TRACKS_READY) {
6235 mixerStatus = MIXER_TRACKS_ENABLED;
6236 }
6237 }
Andy Hungc0691382018-09-12 18:01:57 -07006238 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006239 }
6240
6241 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006242
6243 }
6244
jiabin245cdd92018-12-07 17:55:15 -08006245 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6246 // When there is no fast track playing haptic and FastMixer exists,
6247 // enabling the first FastTrack, which provides mixed data from normal
6248 // tracks, to play haptic data.
6249 FastTrack *fastTrack = &state->mFastTracks[0];
6250 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6251 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6252 didModify = true;
6253 }
6254 }
6255
Eric Laurent81784c32012-11-19 14:55:58 -08006256 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006257 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006258 if (didModify) {
6259 state->mFastTracksGen++;
6260 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6261 if (kUseFastMixer == FastMixer_Dynamic &&
6262 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6263 state->mCommand = FastMixerState::COLD_IDLE;
6264 state->mColdFutexAddr = &mFastMixerFutex;
6265 state->mColdGen++;
6266 mFastMixerFutex = 0;
6267 if (kUseFastMixer == FastMixer_Dynamic) {
6268 mNormalSink = mOutputSink;
6269 }
6270 // If we go into cold idle, need to wait for acknowledgement
6271 // so that fast mixer stops doing I/O.
6272 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6273 pauseAudioWatchdog = true;
6274 }
Eric Laurent81784c32012-11-19 14:55:58 -08006275 }
6276 if (sq != NULL) {
6277 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006278 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6279 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6280 // when bringing the output sink into standby.)
6281 //
6282 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6283 //
6284 // This occurs with BT suspend when we idle the FastMixer with
6285 // active tracks, which may be added or removed.
6286 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006287 }
6288#ifdef AUDIO_WATCHDOG
6289 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6290 mAudioWatchdog->pause();
6291 }
6292#endif
6293
6294 // Now perform the deferred reset on fast tracks that have stopped
6295 while (resetMask != 0) {
6296 size_t i = __builtin_ctz(resetMask);
6297 ALOG_ASSERT(i < count);
6298 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006299 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006300 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6301 track->reset();
6302 }
6303
Andy Hung80d03d22018-04-10 10:32:11 -07006304 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6305 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6306 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6307 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6308 // See also the implementation of destroyTrack_l().
6309 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006310 const int trackId = track->id();
6311 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6312 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006313 }
6314 }
6315
Eric Laurent81784c32012-11-19 14:55:58 -08006316 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006317 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006318
Eric Laurentb3f315a2021-07-13 15:09:05 +02006319 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6320 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006321 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006322 }
6323
6324 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006325 // as long as there are effects we should clear the effects buffer, to avoid
6326 // passing a non-clean buffer to the effect chain
6327 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006328 if (mType == SPATIALIZER) {
6329 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6330 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006331 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006332 // sink or mix buffer must be cleared if all tracks are connected to an
6333 // effect chain as in this case the mixer will not write to the sink or mix buffer
6334 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006335 // always clear sink buffer for spatializer output as the output of the spatializer
6336 // effect will be accumulated into it
6337 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6338 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006339 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006340 if (mMixerBufferValid) {
6341 memset(mMixerBuffer, 0, mMixerBufferSize);
6342 // TODO: In testing, mSinkBuffer below need not be cleared because
6343 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6344 // after mixing.
6345 //
6346 // To enforce this guarantee:
6347 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6348 // (mixedTracks == 0 && fastTracks > 0))
6349 // must imply MIXER_TRACKS_READY.
6350 // Later, we may clear buffers regardless, and skip much of this logic.
6351 }
Andy Hung98ef9782014-03-04 14:46:50 -08006352 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006353 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006354 }
6355
6356 // if any fast tracks, then status is ready
6357 mMixerStatusIgnoringFastTracks = mixerStatus;
6358 if (fastTracks > 0) {
6359 mixerStatus = MIXER_TRACKS_READY;
6360 }
6361 return mixerStatus;
6362}
6363
Andy Hungc5007f82023-08-29 14:26:09 -07006364// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006365uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006366{
6367 uint32_t trackCount = 0;
6368 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006369 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006370 trackCount++;
6371 }
6372 }
6373 return trackCount;
6374}
6375
Andy Hungee58e4a2023-07-07 13:47:37 -07006376bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006377{
Brian Lindahl65e90012022-07-27 18:01:07 +02006378 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6379 // could falsely detect that the frame position has stalled due to underrun because we haven't
6380 // given the Audio HAL enough time to update.
6381 const nsecs_t nowNs = systemTime();
6382 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6383 return mLatchedValue;
6384 }
6385 mPreviousNs = nowNs;
6386 mLatchedValue = false;
6387 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006388 uint64_t position = 0;
6389 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006390 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006391 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006392 if (position != mPreviousPosition) {
6393 mPreviousPosition = position;
6394 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006395 }
6396 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006397 return mLatchedValue;
6398}
6399
Andy Hungee58e4a2023-07-07 13:47:37 -07006400void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006401{
6402 mLatchedValue = true;
6403 mPreviousPosition = 0;
6404 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006405}
6406
Andy Hungc5007f82023-08-29 14:26:09 -07006407// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006408bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006409 audio_channel_mask_t channelMask, audio_format_t format,
6410 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006411{
Andy Hung1bc088a2018-02-09 15:57:31 -08006412 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6413 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006414 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006415 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006416 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006417 ALOGW("%s: invalid format: %#x", __func__, format);
6418 return false;
6419 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006420 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006421 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6422 return false;
6423 }
6424 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006425}
6426
Andy Hungc5007f82023-08-29 14:26:09 -07006427// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006428bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006429 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006430{
Eric Laurent81784c32012-11-19 14:55:58 -08006431 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006432 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006433
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006434 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006435
Eric Laurent10351942014-05-08 18:49:52 -07006436 AudioParameter param = AudioParameter(keyValuePair);
6437 int value;
6438 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6439 reconfig = true;
6440 }
6441 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006442 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006443 status = BAD_VALUE;
6444 } else {
6445 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006446 reconfig = true;
6447 }
Eric Laurent10351942014-05-08 18:49:52 -07006448 }
6449 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006450 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006451 status = BAD_VALUE;
6452 } else {
6453 // no need to save value, since it's constant
6454 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006455 }
Eric Laurent10351942014-05-08 18:49:52 -07006456 }
6457 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6458 // do not accept frame count changes if tracks are open as the track buffer
6459 // size depends on frame count and correct behavior would not be guaranteed
6460 // if frame count is changed after track creation
6461 if (!mTracks.isEmpty()) {
6462 status = INVALID_OPERATION;
6463 } else {
6464 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006465 }
Eric Laurent10351942014-05-08 18:49:52 -07006466 }
6467 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006468 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006469 }
Eric Laurent81784c32012-11-19 14:55:58 -08006470
Eric Laurent10351942014-05-08 18:49:52 -07006471 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006472 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006473 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006474 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6475 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006476 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006477 mThreadMetrics.logEndInterval();
6478 mThreadSnapshot.onEnd();
6479 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006480 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006481 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006482 }
Eric Laurent10351942014-05-08 18:49:52 -07006483 if (status == NO_ERROR && reconfig) {
6484 readOutputParameters_l();
6485 delete mAudioMixer;
6486 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006487 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006488 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006489 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006490 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006491 track->channelMask(),
6492 track->format(),
6493 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006494 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006495 "%s(): AudioMixer cannot create track(%d)"
6496 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006497 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006498 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006499 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006500 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006501 }
Eric Laurent81784c32012-11-19 14:55:58 -08006502 }
6503
Dean Wheatley68918102021-03-19 22:09:19 +11006504 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006505}
6506
6507
Andy Hungee58e4a2023-07-07 13:47:37 -07006508void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006509{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006510 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006511 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006512 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006513 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006514 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6515 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6516 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006517 if (hasFastMixer()) {
6518 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6519
6520 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6521 // while we are dumping it. It may be inconsistent, but it won't mutate!
6522 // This is a large object so we place it on the heap.
6523 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006524 const std::unique_ptr<FastMixerDumpState> copy =
6525 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006526 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006527
6528#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006529 // Similar for state queue
6530 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6531 observerCopy.dump(fd);
6532 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6533 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006534#endif
6535
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006536#ifdef AUDIO_WATCHDOG
6537 if (mAudioWatchdog != 0) {
6538 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6539 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6540 wdCopy.dump(fd);
6541 }
6542#endif
6543
6544 } else {
6545 dprintf(fd, " No FastMixer\n");
6546 }
Eric Laurent90cea102023-05-15 15:08:27 +02006547
6548 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6549 mBluetoothLatencyModesEnabled ? "" : "not ");
6550 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6551 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6552 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006553}
6554
Andy Hungee58e4a2023-07-07 13:47:37 -07006555uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006556{
6557 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6558}
6559
Andy Hungee58e4a2023-07-07 13:47:37 -07006560uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006561{
6562 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6563}
6564
Andy Hungee58e4a2023-07-07 13:47:37 -07006565void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006566{
6567 PlaybackThread::cacheParameters_l();
6568
6569 // FIXME: Relaxed timing because of a certain device that can't meet latency
6570 // Should be reduced to 2x after the vendor fixes the driver issue
6571 // increase threshold again due to low power audio mode. The way this warning
6572 // threshold is calculated and its usefulness should be reconsidered anyway.
6573 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6574}
6575
Andy Hungee58e4a2023-07-07 13:47:37 -07006576void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006577 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006578}
6579
Andy Hungee58e4a2023-07-07 13:47:37 -07006580void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006581 // Only handle latency mode if:
6582 // - mBluetoothLatencyModesEnabled is true
6583 // - the HAL supports latency modes
6584 // - the selected device is Bluetooth LE or A2DP
6585 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6586 return;
6587 }
6588 if (mOutDeviceTypeAddrs.size() != 1
6589 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6590 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6591 return;
6592 }
6593
6594 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6595 if (mSupportedLatencyModes.size() == 1) {
6596 // If the HAL only support one latency mode currently, confirm the choice
6597 latencyMode = mSupportedLatencyModes[0];
6598 } else if (mSupportedLatencyModes.size() > 1) {
6599 // Request low latency if:
6600 // - At least one active track is either:
6601 // - a fast track with gaming usage or
6602 // - a track with acessibility usage
6603 for (const auto& track : mActiveTracks) {
6604 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6605 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6606 latencyMode = AUDIO_LATENCY_MODE_LOW;
6607 break;
6608 }
6609 }
6610 }
6611
6612 if (latencyMode != mSetLatencyMode) {
6613 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6614 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6615 __func__, mId, toString(latencyMode).c_str(), status);
6616 if (status == NO_ERROR) {
6617 mSetLatencyMode = latencyMode;
6618 }
6619 }
6620}
6621
Andy Hungee58e4a2023-07-07 13:47:37 -07006622void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006623
6624 if (mOutput == nullptr || mOutput->stream == nullptr) {
6625 return;
6626 }
6627 std::vector<audio_latency_mode_t> latencyModes;
6628 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6629 if (status != NO_ERROR) {
6630 latencyModes.clear();
6631 }
6632 if (latencyModes != mSupportedLatencyModes) {
6633 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6634 __func__, mId, status, toString(latencyModes).c_str());
6635 mSupportedLatencyModes.swap(latencyModes);
6636 sendHalLatencyModesChangedEvent_l();
6637 }
6638}
6639
Andy Hungee58e4a2023-07-07 13:47:37 -07006640status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006641 std::vector<audio_latency_mode_t>* modes) {
6642 if (modes == nullptr) {
6643 return BAD_VALUE;
6644 }
Andy Hung972bec12023-08-31 16:13:39 -07006645 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006646 *modes = mSupportedLatencyModes;
6647 return NO_ERROR;
6648}
6649
Andy Hungee58e4a2023-07-07 13:47:37 -07006650void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006651 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006652 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006653 if (modes != mSupportedLatencyModes) {
6654 ALOGD("%s: thread(%d) supported latency modes: %s",
6655 __func__, mId, toString(modes).c_str());
6656 mSupportedLatencyModes.swap(modes);
6657 sendHalLatencyModesChangedEvent_l();
6658 }
6659}
6660
Andy Hungee58e4a2023-07-07 13:47:37 -07006661status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006662 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6663 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6664 return INVALID_OPERATION;
6665 }
6666 mBluetoothLatencyModesEnabled.store(enabled);
6667 return NO_ERROR;
6668}
6669
Eric Laurent81784c32012-11-19 14:55:58 -08006670// ----------------------------------------------------------------------------
6671
Andy Hungee58e4a2023-07-07 13:47:37 -07006672/* static */
6673sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006674 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006675 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6676 const audio_offload_info_t& offloadInfo) {
6677 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006678 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006679}
6680
Andy Hung583043b2023-07-17 17:05:00 -07006681DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006682 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6683 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006684 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006685 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006686{
Andy Hung583043b2023-07-17 17:05:00 -07006687 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006688}
6689
Andy Hungee58e4a2023-07-07 13:47:37 -07006690DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006691{
6692}
6693
Andy Hungee58e4a2023-07-07 13:47:37 -07006694void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006695{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006696 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006697 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6698 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6699}
6700
Andy Hungee58e4a2023-07-07 13:47:37 -07006701void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006702{
Andy Hung972bec12023-08-31 16:13:39 -07006703 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006704 if (mMasterBalance != balance) {
6705 mMasterBalance.store(balance);
6706 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6707 broadcast_l();
6708 }
6709}
6710
Andy Hungee58e4a2023-07-07 13:47:37 -07006711void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006712{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006713 float left, right;
6714
Andy Hung333ab962019-05-28 20:23:35 -07006715 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006716 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006717
Andy Hung398ffa22022-12-13 19:19:53 -08006718 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6719 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6720
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006721 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6722 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006723
6724 const int64_t volumeShaperFrames =
6725 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6726 const auto [shaperVolume, shaperActive] =
6727 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006728 mVolumeShaperActive = shaperActive;
6729
Vlad Popae2f5aef2022-07-25 16:00:20 +02006730 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6731 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6732 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6733
6734 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6735
Eric Laurent277a37e2024-07-29 18:37:52 +00006736 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6737 left = right = 0;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006738 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +00006739 float typeVolume = mStreamTypes[track->streamType()].volume;
6740 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006741
Eric Laurent277a37e2024-07-29 18:37:52 +00006742 if (left > GAIN_FLOAT_UNITY) {
6743 left = GAIN_FLOAT_UNITY;
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006744 }
Eric Laurent277a37e2024-07-29 18:37:52 +00006745 if (right > GAIN_FLOAT_UNITY) {
6746 right = GAIN_FLOAT_UNITY;
6747 }
6748 left *= v;
6749 right *= v;
6750 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6751 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6752 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6753 right *= mMasterBalanceRight;
6754 }
Francois Gaffie55b2a0f2021-06-24 15:58:37 +02006755 }
Vlad Popae8d99472022-06-30 16:02:48 +02006756
Eric Laurent277a37e2024-07-29 18:37:52 +00006757 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6758 /*muteState=*/{mMasterMute,
6759 mStreamTypes[track->streamType()].volume == 0.f,
6760 mStreamTypes[track->streamType()].mute,
6761 track->isPlaybackRestricted(),
6762 clientVolumeMute,
6763 shaperVolume == 0.f});
6764
Eric Laurentbfb1b832013-01-07 09:53:42 -08006765 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006766 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006767 if (left != mLeftVolFloat || right != mRightVolFloat) {
6768 mLeftVolFloat = left;
6769 mRightVolFloat = right;
6770
Eric Laurentbfb1b832013-01-07 09:53:42 -08006771 // Delegate volume control to effect in track effect chain if needed
6772 // only one effect chain can be present on DirectOutputThread, so if
6773 // there is one, the track is connected to it
6774 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006775 // if effect chain exists, volume is handled by it.
6776 // Convert volumes from float to 8.24
6777 uint32_t vl = (uint32_t)(left * (1 << 24));
6778 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006779 // Direct/Offload effect chains set output volume in setVolume().
6780 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006781 } else {
6782 // otherwise we directly set the volume.
6783 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006784 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006785 }
6786 }
6787}
6788
Andy Hungee58e4a2023-07-07 13:47:37 -07006789void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006790{
Andy Hung8d31fd22023-06-26 19:20:57 -07006791 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6792 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006793
Eric Laurent0f0631e2015-07-06 18:01:25 -07006794 if (previousTrack != 0 && latestTrack != 0) {
6795 if (mType == DIRECT) {
6796 if (previousTrack.get() != latestTrack.get()) {
6797 mFlushPending = true;
6798 }
6799 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006800 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6801 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006802 mFlushPending = true;
6803 }
6804 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006805 } else if (previousTrack == 0) {
6806 // there could be an old track added back during track transition for direct
6807 // output, so always issues flush to flush data of the previous track if it
6808 // was already destroyed with HAL paused, then flush can resume the playback
6809 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006810 }
6811 PlaybackThread::onAddNewTrack_l();
6812}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006813
Andy Hungee58e4a2023-07-07 13:47:37 -07006814PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006815 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006816)
6817{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006818 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006819 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006820 bool doHwPause = false;
6821 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006822
6823 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006824 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006825 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006826 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006827 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006828 continue;
6829 }
6830
Andy Hung8d31fd22023-06-26 19:20:57 -07006831 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006832#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006833 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006834#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006835 // Only consider last track started for volume and mixer state control.
6836 // In theory an older track could underrun and restart after the new one starts
6837 // but as we only care about the transition phase between two tracks on a
6838 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006839 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006840 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006841
Kuowei Li23666472021-01-20 10:23:25 +08006842 if (track->isPausePending()) {
6843 track->pauseAck();
6844 // It is possible a track might have been flushed or stopped.
6845 // Other operations such as flush pending might occur on the next prepare.
6846 if (track->isPausing()) {
6847 track->setPaused();
6848 }
6849 // Always perform pause, as an immediate flush will change
6850 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006851 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006852 doHwPause = true;
6853 mHwPaused = true;
6854 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006855 } else if (track->isFlushPending()) {
6856 track->flushAck();
6857 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006858 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006859 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006860 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006861 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006862 if (last) {
6863 mLeftVolFloat = mRightVolFloat = -1.0;
6864 if (mHwPaused) {
6865 doHwResume = true;
6866 mHwPaused = false;
6867 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006868 }
6869 }
6870
Eric Laurent81784c32012-11-19 14:55:58 -08006871 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006872 // for all its buffers to be filled before processing it.
6873 // Allow draining the buffer in case the client
6874 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006875 // hence the test on (track->retryCount() > 1).
6876 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006877 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6878 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006879 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006880
6881 // target retry count that we will use is based on the time we wait for retries.
6882 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6883 // the retry threshold is when we accept any size for PCM data. This is slightly
6884 // smaller than the retry count so we can push small bits of data without a glitch.
6885 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006886 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006887 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006888 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006889 minFrames = mNormalFrameCount;
6890 } else {
6891 minFrames = 1;
6892 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006893
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006894 const size_t framesReady = track->framesReady();
6895 const int trackId = track->id();
6896 if (ATRACE_ENABLED()) {
6897 std::string traceName("nRdy");
6898 traceName += std::to_string(trackId);
6899 ATRACE_INT(traceName.c_str(), framesReady);
6900 }
6901 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006902 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006903 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006904 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006905
Andy Hung8d31fd22023-06-26 19:20:57 -07006906 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6907 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006908 if (last) {
6909 // make sure processVolume_l() will apply new volume even if 0
6910 mLeftVolFloat = mRightVolFloat = -1.0;
6911 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006912 if (!mHwSupportsPause) {
6913 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006914 }
6915 }
6916
6917 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006918 processVolume_l(track, last);
6919 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006920 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006921 if (previousTrack != 0) {
6922 if (track != previousTrack.get()) {
6923 // Flush any data still being written from last track
6924 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006925 // Invalidate previous track to force a seek when resuming.
6926 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006927 }
6928 }
6929 mPreviousTrack = track;
6930
Eric Laurentd595b7c2013-04-03 17:27:56 -07006931 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006932 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006933 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006934 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006935 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006936 doHwResume = true;
6937 mHwPaused = false;
6938 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006939 }
Eric Laurent81784c32012-11-19 14:55:58 -08006940 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006941 // clear effect chain input buffer if the last active track started underruns
6942 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006943 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006944 mEffectChains[0]->clearInputBuffer();
6945 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006946 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006947 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006948 if (last && mHwPaused) {
6949 doHwResume = true;
6950 mHwPaused = false;
6951 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006952 }
6953 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6954 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006955 // We have consumed all the buffers of this track.
6956 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006957 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006958 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006959 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006960 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006961 if (presComplete) {
6962 mOutput->presentationComplete();
6963 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006964 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006965 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006966 }
Eric Laurent81784c32012-11-19 14:55:58 -08006967 if (track->isStopped()) {
6968 track->reset();
6969 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006970 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006971 }
6972 } else {
6973 // No buffers for this track. Give it a few chances to
6974 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006975 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006976 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006977 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006978 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006979 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006980 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006981 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00006982 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
6983 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08006984 tracksToRemove->add(track);
6985 // indicate to client process that the track was disabled because of
6986 // underrun; it will then automatically call start() when data is available
6987 track->disable();
6988 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6989 // unlike mixerthread, HAL can be paused for direct output
6990 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6991 "minFrames = %u, mFormat = %#x",
6992 framesReady, minFrames, mFormat);
6993 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6994 doHwPause = true;
6995 mHwPaused = true;
6996 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006997 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006998 } else if (last) {
6999 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007000 }
7001 }
7002 }
7003 }
7004
Eric Laurentd1f69b02014-12-15 14:33:13 -08007005 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007006 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007007 for (size_t i = 0; i < mTracks.size(); i++) {
7008 if (mTracks[i]->isFlushPending()) {
7009 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007010 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007011 }
7012 }
7013 }
7014
7015 // make sure the pause/flush/resume sequence is executed in the right order.
7016 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7017 // before flush and then resume HW. This can happen in case of pause/flush/resume
7018 // if resume is received before pause is executed.
7019 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007020 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007021 status_t result = mOutput->stream->pause();
7022 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007023 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007024 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007025 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007026 flushHw_l();
7027 }
7028 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007029 status_t result = mOutput->stream->resume();
7030 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007031 }
Eric Laurent81784c32012-11-19 14:55:58 -08007032 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007033 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007034
7035 return mixerStatus;
7036}
7037
Andy Hungee58e4a2023-07-07 13:47:37 -07007038void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007039{
Eric Laurent81784c32012-11-19 14:55:58 -08007040 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007041 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007042 // output audio to hardware
7043 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007044 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007045 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007046 status_t status = mActiveTrack->getNextBuffer(&buffer);
7047 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007048 // no need to pad with 0 for compressed audio
7049 if (audio_has_proportional_frames(mFormat)) {
7050 memset(curBuf, 0, frameCount * mFrameSize);
7051 }
Eric Laurent81784c32012-11-19 14:55:58 -08007052 break;
7053 }
7054 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7055 frameCount -= buffer.frameCount;
7056 curBuf += buffer.frameCount * mFrameSize;
7057 mActiveTrack->releaseBuffer(&buffer);
7058 }
Andy Hung2098f272014-02-27 14:00:06 -08007059 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007060 mSleepTimeUs = 0;
7061 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007062 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007063}
7064
Andy Hungee58e4a2023-07-07 13:47:37 -07007065void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007066{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007067 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007068 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007069 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007070 return;
7071 }
Andy Hung85ba3332021-04-27 17:40:26 -07007072 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7073 mSleepTimeUs = mActiveSleepTimeUs;
7074 } else {
7075 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007076 }
Andy Hung85ba3332021-04-27 17:40:26 -07007077 // Note: In S or later, we do not write zeroes for
7078 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007079}
7080
Andy Hungee58e4a2023-07-07 13:47:37 -07007081void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007082{
7083 {
Andy Hung972bec12023-08-31 16:13:39 -07007084 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007085 for (size_t i = 0; i < mTracks.size(); i++) {
7086 if (mTracks[i]->isFlushPending()) {
7087 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007088 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007089 }
7090 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007091 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007092 flushHw_l();
7093 }
7094 }
7095 PlaybackThread::threadLoop_exit();
7096}
7097
7098// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007099bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007100{
7101 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007102 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007103 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007104
Eric Laurent022a5132024-04-12 17:02:51 +00007105 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007106 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007107 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007108 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007109 const auto& mainTrack = mTracks[mTracks.size() - 1];
7110
7111 trackPaused = mainTrack->isPaused();
7112 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7113 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007114 }
7115
Eric Laurent022a5132024-04-12 17:02:51 +00007116 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007117}
7118
Andy Hungc5007f82023-08-29 14:26:09 -07007119// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007120bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007121 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007122{
7123 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007124 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007125
Eric Laurent10351942014-05-08 18:49:52 -07007126 AudioParameter param = AudioParameter(keyValuePair);
7127 int value;
7128 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007129 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007130 }
Eric Laurent10351942014-05-08 18:49:52 -07007131 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7132 // do not accept frame count changes if tracks are open as the track buffer
7133 // size depends on frame count and correct behavior would not be garantied
7134 // if frame count is changed after track creation
7135 if (!mTracks.isEmpty()) {
7136 status = INVALID_OPERATION;
7137 } else {
7138 reconfig = true;
7139 }
7140 }
7141 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007142 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007143 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007144 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007145 if (!mStandby) {
7146 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007147 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007148 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007149 }
Eric Laurent10351942014-05-08 18:49:52 -07007150 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007151 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007152 }
7153 if (status == NO_ERROR && reconfig) {
7154 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007155 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007156 }
7157 }
7158
Dean Wheatley68918102021-03-19 22:09:19 +11007159 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007160}
7161
Andy Hungee58e4a2023-07-07 13:47:37 -07007162uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007163{
7164 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007165 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007166 time = PlaybackThread::activeSleepTimeUs();
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::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007174{
7175 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007176 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007177 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
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 -07007184uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007185{
7186 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007187 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007188 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7189 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007190 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007191 }
7192 return time;
7193}
7194
Andy Hungee58e4a2023-07-07 13:47:37 -07007195void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007196{
7197 PlaybackThread::cacheParameters_l();
7198
7199 // use shorter standby delay as on normal output to release
7200 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007201 // no delay on outputs with HW A/V sync
7202 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007203 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007204 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007205 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007206 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007207 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007208 }
Eric Laurent81784c32012-11-19 14:55:58 -08007209}
7210
Andy Hungee58e4a2023-07-07 13:47:37 -07007211void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007212{
ziyangch8f194f12021-12-01 13:48:04 -08007213 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007214 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007215 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007216 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007217 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007218 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007219 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007220}
7221
Andy Hungee58e4a2023-07-07 13:47:37 -07007222int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007223 // If a VolumeShaper is active, we must wake up periodically to update volume.
7224 const int64_t NS_PER_MS = 1000000;
7225 return mVolumeShaperActive ?
7226 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7227}
7228
Eric Laurent81784c32012-11-19 14:55:58 -08007229// ----------------------------------------------------------------------------
7230
Andy Hungee58e4a2023-07-07 13:47:37 -07007231AsyncCallbackThread::AsyncCallbackThread(
7232 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007233 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007234 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007235 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007236 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007237 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007238{
7239}
7240
Andy Hungee58e4a2023-07-07 13:47:37 -07007241void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007242{
7243 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7244}
7245
Andy Hungee58e4a2023-07-07 13:47:37 -07007246bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007247{
7248 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007249 uint32_t writeAckSequence;
7250 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007251 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007252
7253 {
Andy Hungc5007f82023-08-29 14:26:09 -07007254 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007255 while (!((mWriteAckSequence & 1) ||
7256 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007257 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007258 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007259 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007260 }
7261
Eric Laurentbfb1b832013-01-07 09:53:42 -08007262 if (exitPending()) {
7263 break;
7264 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007265 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7266 mWriteAckSequence, mDrainSequence);
7267 writeAckSequence = mWriteAckSequence;
7268 mWriteAckSequence &= ~1;
7269 drainSequence = mDrainSequence;
7270 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007271 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007272 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007273 }
7274 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007275 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007276 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007277 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007278 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007279 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007280 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007281 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007282 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007283 if (asyncError != ASYNC_ERROR_NONE) {
7284 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007285 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007286 }
7287 }
7288 }
7289 return false;
7290}
7291
Andy Hungee58e4a2023-07-07 13:47:37 -07007292void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007293{
7294 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007295 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007296 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007297 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007298}
7299
Andy Hungee58e4a2023-07-07 13:47:37 -07007300void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007301{
Andy Hung972bec12023-08-31 16:13:39 -07007302 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007303 // bit 0 is cleared
7304 mWriteAckSequence = sequence << 1;
7305}
7306
Andy Hungee58e4a2023-07-07 13:47:37 -07007307void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007308{
Andy Hung972bec12023-08-31 16:13:39 -07007309 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007310 // ignore unexpected callbacks
7311 if (mWriteAckSequence & 2) {
7312 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007313 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007314 }
7315}
7316
Andy Hungee58e4a2023-07-07 13:47:37 -07007317void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007318{
Andy Hung972bec12023-08-31 16:13:39 -07007319 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007320 // bit 0 is cleared
7321 mDrainSequence = sequence << 1;
7322}
7323
Andy Hungee58e4a2023-07-07 13:47:37 -07007324void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007325{
Andy Hung972bec12023-08-31 16:13:39 -07007326 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007327 // ignore unexpected callbacks
7328 if (mDrainSequence & 2) {
7329 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007330 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 }
7332}
7333
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007334void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007335{
Andy Hung972bec12023-08-31 16:13:39 -07007336 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007337 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007338 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007339}
7340
Eric Laurentbfb1b832013-01-07 09:53:42 -08007341
7342// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007343
7344/* static */
7345sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007346 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007347 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7348 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007349 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007350}
7351
Andy Hung583043b2023-07-17 17:05:00 -07007352OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007353 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7354 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007355 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007356 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007357{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007358 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007359 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007360 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361}
7362
Andy Hungee58e4a2023-07-07 13:47:37 -07007363void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007364{
7365 if (mFlushPending || mHwPaused) {
7366 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007367 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007368 flushHw_l();
7369 } else {
7370 mMixerStatus = MIXER_DRAIN_ALL;
7371 threadLoop_drain();
7372 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007373 if (mUseAsyncWrite) {
7374 ALOG_ASSERT(mCallbackThread != 0);
7375 mCallbackThread->exit();
7376 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007377 PlaybackThread::threadLoop_exit();
7378}
7379
Andy Hungee58e4a2023-07-07 13:47:37 -07007380PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007381 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007382)
7383{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007384 size_t count = mActiveTracks.size();
7385
7386 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007387 bool doHwPause = false;
7388 bool doHwResume = false;
7389
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007390 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007391
Eric Laurentbfb1b832013-01-07 09:53:42 -08007392 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007393 for (const sp<IAfTrack>& t : mActiveTracks) {
7394 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007395#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007396 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007397#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007398 // Only consider last track started for volume and mixer state control.
7399 // In theory an older track could underrun and restart after the new one starts
7400 // but as we only care about the transition phase between two tracks on a
7401 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007402 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007403 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007404
Haynes Mathew George7844f672014-01-15 12:32:55 -08007405 if (track->isInvalid()) {
7406 ALOGW("An invalidated track shouldn't be in active list");
7407 tracksToRemove->add(track);
7408 continue;
7409 }
7410
Andy Hung8d31fd22023-06-26 19:20:57 -07007411 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007412 ALOGW("An idle track shouldn't be in active list");
7413 continue;
7414 }
7415
Kuowei Li23666472021-01-20 10:23:25 +08007416 if (track->isPausePending()) {
7417 track->pauseAck();
7418 // It is possible a track might have been flushed or stopped.
7419 // Other operations such as flush pending might occur on the next prepare.
7420 if (track->isPausing()) {
7421 track->setPaused();
7422 }
7423 // Always perform pause if last, as an immediate flush will change
7424 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007425 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007426 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007427 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007428 mHwPaused = true;
7429 }
7430 // If we were part way through writing the mixbuffer to
7431 // the HAL we must save this until we resume
7432 // BUG - this will be wrong if a different track is made active,
7433 // in that case we want to discard the pending data in the
7434 // mixbuffer and tell the client to present it again when the
7435 // track is resumed
7436 mPausedWriteLength = mCurrentWriteLength;
7437 mPausedBytesRemaining = mBytesRemaining;
7438 mBytesRemaining = 0; // stop writing
7439 }
7440 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007441 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007442 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007443 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007444 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007445 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007446 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007447 track->flushAck();
7448 if (last) {
7449 mFlushPending = true;
7450 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007451 } else if (track->isResumePending()){
7452 track->resumeAck();
7453 if (last) {
7454 if (mPausedBytesRemaining) {
7455 // Need to continue write that was interrupted
7456 mCurrentWriteLength = mPausedWriteLength;
7457 mBytesRemaining = mPausedBytesRemaining;
7458 mPausedBytesRemaining = 0;
7459 }
7460 if (mHwPaused) {
7461 doHwResume = true;
7462 mHwPaused = false;
7463 // threadLoop_mix() will handle the case that we need to
7464 // resume an interrupted write
7465 }
7466 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007467 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007468
Eric Laurent3df841a2016-07-15 15:15:40 -07007469 mLeftVolFloat = mRightVolFloat = -1.0;
7470
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007471 // Do not handle new data in this iteration even if track->framesReady()
7472 mixerStatus = MIXER_TRACKS_ENABLED;
7473 }
7474 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007475 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007476 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007477 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7478 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007479 if (last) {
7480 // make sure processVolume_l() will apply new volume even if 0
7481 mLeftVolFloat = mRightVolFloat = -1.0;
7482 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007483 }
7484
7485 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007486 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007487 if (previousTrack != 0) {
7488 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007489 // Flush any data still being written from last track
7490 mBytesRemaining = 0;
7491 if (mPausedBytesRemaining) {
7492 // Last track was paused so we also need to flush saved
7493 // mixbuffer state and invalidate track so that it will
7494 // re-submit that unwritten data when it is next resumed
7495 mPausedBytesRemaining = 0;
7496 // Invalidate is a bit drastic - would be more efficient
7497 // to have a flag to tell client that some of the
7498 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007499 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007500 }
7501 // flush data already sent to the DSP if changing audio session as audio
7502 // comes from a different source. Also invalidate previous track to force a
7503 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007504 if (previousTrack->sessionId() != track->sessionId()) {
7505 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007506 }
7507 }
7508 }
7509 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007510 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007511 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007512 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007513 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007514 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007515 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007516 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007517 mixerStatus = MIXER_TRACKS_READY;
7518 }
7519 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007520 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007521 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007522 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007523 // Hardware buffer can hold a large amount of audio so we must
7524 // wait for all current track's data to drain before we say
7525 // that the track is stopped.
7526 if (mBytesRemaining == 0) {
7527 // Only start draining when all data in mixbuffer
7528 // has been written
7529 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007530 track->setState(IAfTrackBase::STOPPING_2);
7531 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007532 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7533 if (last && !mStandby) {
7534 // do not modify drain sequence if we are already draining. This happens
7535 // when resuming from pause after drain.
7536 if ((mDrainSequence & 1) == 0) {
7537 mSleepTimeUs = 0;
7538 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7539 mixerStatus = MIXER_DRAIN_TRACK;
7540 mDrainSequence += 2;
7541 }
7542 if (mHwPaused) {
7543 // It is possible to move from PAUSED to STOPPING_1 without
7544 // a resume so we must ensure hardware is running
7545 doHwResume = true;
7546 mHwPaused = false;
7547 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007548 }
7549 }
Eric Laurente93cc032016-05-05 10:15:10 -07007550 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007551 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007552 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007553 }
7554 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007555 // Drain has completed or we are in standby, signal presentation complete
7556 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007557 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007558 mOutput->presentationComplete();
7559 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007560 track->reset();
7561 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007562 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007563 if (!mUseAsyncWrite) {
7564 // If we don't get explicit drain notification we must
7565 // register discontinuity regardless of whether this is
7566 // the previous (!last) or the upcoming (last) track
7567 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007568 mTimestampVerifier.discontinuity(
7569 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007570 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007571 }
7572 } else {
7573 // No buffers for this track. Give it a few chances to
7574 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007575 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007576 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007577 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007578 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007579 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007580 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007581 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7582 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007583 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007584 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007585 // it will then automatically call start() when data is available
7586 track->disable();
7587 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007588 } else if (last){
7589 mixerStatus = MIXER_TRACKS_ENABLED;
7590 }
7591 }
7592 }
7593 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007594 if (track->isReady()) { // check ready to prevent premature start.
7595 processVolume_l(track, last);
7596 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007597 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007598
Eric Laurentea0fade2013-10-04 16:23:48 -07007599 // make sure the pause/flush/resume sequence is executed in the right order.
7600 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7601 // before flush and then resume HW. This can happen in case of pause/flush/resume
7602 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007603 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007604 status_t result = mOutput->stream->pause();
7605 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007606 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007607 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007608 if (mFlushPending) {
7609 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007610 }
Eric Laurentfd477972013-10-25 18:10:40 -07007611 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007612 status_t result = mOutput->stream->resume();
7613 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007614 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007615
Eric Laurentbfb1b832013-01-07 09:53:42 -08007616 // remove all the tracks that need to be...
7617 removeTracks_l(*tracksToRemove);
7618
7619 return mixerStatus;
7620}
7621
Eric Laurentbfb1b832013-01-07 09:53:42 -08007622// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007623bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007624{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007625 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7626 mWriteAckSequence, mDrainSequence);
7627 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007628 return true;
7629 }
7630 return false;
7631}
7632
Andy Hungee58e4a2023-07-07 13:47:37 -07007633bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007634{
Andy Hung972bec12023-08-31 16:13:39 -07007635 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007636 return waitingAsyncCallback_l();
7637}
7638
Andy Hungee58e4a2023-07-07 13:47:37 -07007639void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007640{
Eric Laurente659ef42014-09-29 13:06:46 -07007641 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007642 // Flush anything still waiting in the mixbuffer
7643 mCurrentWriteLength = 0;
7644 mBytesRemaining = 0;
7645 mPausedWriteLength = 0;
7646 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007647 // reset bytes written count to reflect that DSP buffers are empty after flush.
7648 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007649
Eric Laurentbfb1b832013-01-07 09:53:42 -08007650 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007651 // discard any pending drain or write ack by incrementing sequence
7652 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7653 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007654 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007655 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7656 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007657 }
7658}
7659
Andy Hungee58e4a2023-07-07 13:47:37 -07007660void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007661{
Andy Hung972bec12023-08-31 16:13:39 -07007662 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007663 if (PlaybackThread::invalidateTracks_l(streamType)) {
7664 mFlushPending = true;
7665 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007666}
7667
Andy Hungee58e4a2023-07-07 13:47:37 -07007668void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007669 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007670 if (PlaybackThread::invalidateTracks_l(portIds)) {
7671 mFlushPending = true;
7672 }
7673}
7674
Eric Laurentbfb1b832013-01-07 09:53:42 -08007675// ----------------------------------------------------------------------------
7676
Andy Hungee58e4a2023-07-07 13:47:37 -07007677/* static */
7678sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007679 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007680 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007681 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007682}
7683
Andy Hung583043b2023-07-17 17:05:00 -07007684DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007685 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007686 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007687 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007688 mWaitTimeMs(UINT_MAX)
7689{
7690 addOutputTrack(mainThread);
7691}
7692
Andy Hungee58e4a2023-07-07 13:47:37 -07007693DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007694{
7695 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7696 mOutputTracks[i]->destroy();
7697 }
7698}
7699
Andy Hungee58e4a2023-07-07 13:47:37 -07007700void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007701{
7702 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007703 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007704 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007705 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007706 if (mMixerBufferValid) {
7707 memset(mMixerBuffer, 0, mMixerBufferSize);
7708 } else {
7709 memset(mSinkBuffer, 0, mSinkBufferSize);
7710 }
Eric Laurent81784c32012-11-19 14:55:58 -08007711 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007712 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007713 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007714 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007715 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007716}
7717
Andy Hungee58e4a2023-07-07 13:47:37 -07007718void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007719{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007720 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007721 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007722 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007723 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007724 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007725 }
7726 } else if (mBytesWritten != 0) {
7727 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7728 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007729 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007730 } else {
7731 // flush remaining overflow buffers in output tracks
7732 writeFrames = 0;
7733 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007734 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007735 }
7736}
7737
Andy Hungee58e4a2023-07-07 13:47:37 -07007738ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007739{
7740 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007741 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7742
7743 // Consider the first OutputTrack for timestamp and frame counting.
7744
7745 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7746 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7747 // we always claim success.
7748 if (i == 0) {
7749 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7750 ALOGD_IF(correction != 0 && writeFrames != 0,
7751 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7752 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7753 mFramesWritten -= correction;
7754 }
7755
7756 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007757 }
Andy Hungcf10d742020-04-28 15:38:24 -07007758 if (mStandby) {
7759 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007760 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007761 mStandby = false;
7762 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007763 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007764}
7765
Andy Hungee58e4a2023-07-07 13:47:37 -07007766void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007767{
7768 // DuplicatingThread implements standby by stopping all tracks
7769 for (size_t i = 0; i < outputTracks.size(); i++) {
7770 outputTracks[i]->stop();
7771 }
7772}
7773
Andy Hung8a5abfd2023-12-07 19:35:12 -08007774void DuplicatingThread::threadLoop_exit()
7775{
7776 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7777 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7778 // Do so here in the threadLoop_exit().
7779
7780 SortedVector <sp<IAfOutputTrack>> localTracks;
7781 {
7782 audio_utils::lock_guard l(mutex());
7783 localTracks = std::move(mOutputTracks);
7784 mOutputTracks.clear();
7785 }
7786 localTracks.clear();
7787 outputTracks.clear();
7788 PlaybackThread::threadLoop_exit();
7789}
7790
Andy Hungee58e4a2023-07-07 13:47:37 -07007791void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007792{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007793 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007794
7795 std::stringstream ss;
7796 const size_t numTracks = mOutputTracks.size();
7797 ss << " " << numTracks << " OutputTracks";
7798 if (numTracks > 0) {
7799 ss << ":";
7800 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007801 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007802 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007803 if (thread.get() != nullptr) {
7804 ss << thread.get() << ", " << thread->id();
7805 } else {
7806 ss << "null";
7807 }
7808 ss << ")";
7809 }
7810 }
7811 ss << "\n";
7812 std::string result = ss.str();
7813 write(fd, result.c_str(), result.size());
7814}
7815
Andy Hungee58e4a2023-07-07 13:47:37 -07007816void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007817{
7818 outputTracks = mOutputTracks;
7819}
7820
Andy Hungee58e4a2023-07-07 13:47:37 -07007821void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007822{
7823 outputTracks.clear();
7824}
7825
Andy Hungee58e4a2023-07-07 13:47:37 -07007826void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007827{
Andy Hung972bec12023-08-31 16:13:39 -07007828 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007829 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7830 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7831 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7832 const size_t frameCount =
7833 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7834 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7835 // from different OutputTracks and their associated MixerThreads (e.g. one may
7836 // nearly empty and the other may be dropping data).
7837
Svet Ganov33761132021-05-13 22:51:08 +00007838 // TODO b/182392769: use attribution source util, move to server edge
7839 AttributionSourceState attributionSource = AttributionSourceState();
7840 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007841 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007842 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007843 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007844 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007845 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007846 this,
7847 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007848 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007849 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007850 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007851 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007852 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7853 if (status != NO_ERROR) {
7854 ALOGE("addOutputTrack() initCheck failed %d", status);
7855 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007856 }
Eric Laurent277a37e2024-07-29 18:37:52 +00007857 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007858 mOutputTracks.add(outputTrack);
7859 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7860 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007861}
7862
Andy Hungee58e4a2023-07-07 13:47:37 -07007863void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007864{
Andy Hung972bec12023-08-31 16:13:39 -07007865 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007866 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7867 if (mOutputTracks[i]->thread() == thread) {
7868 mOutputTracks[i]->destroy();
7869 mOutputTracks.removeAt(i);
7870 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007871 // NO_THREAD_SAFETY_ANALYSIS
7872 // Lambda workaround: as thread != this
7873 // we can safely call the remote thread getOutput.
7874 const bool equalOutput =
7875 [&](){ return thread->getOutput() == mOutput; }();
7876 if (equalOutput) {
7877 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007878 }
Eric Laurent81784c32012-11-19 14:55:58 -08007879 return;
7880 }
7881 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007882 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007883}
7884
Andy Hungc5007f82023-08-29 14:26:09 -07007885// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007886void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007887{
7888 mWaitTimeMs = UINT_MAX;
7889 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007890 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007891 if (strong != 0) {
7892 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7893 if (waitTimeMs < mWaitTimeMs) {
7894 mWaitTimeMs = waitTimeMs;
7895 }
7896 }
7897 }
7898}
7899
Andy Hungee58e4a2023-07-07 13:47:37 -07007900bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007901{
7902 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007903 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007904 if (thread == 0) {
7905 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7906 outputTracks[i].get());
7907 return false;
7908 }
Andy Hung87c693c2023-07-06 20:56:16 -07007909 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007910 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007911 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007912 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7913 thread.get());
7914 return false;
7915 }
7916 }
7917 return true;
7918}
7919
Andy Hungee58e4a2023-07-07 13:47:37 -07007920void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007921 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007922{
Kevin Rocard12381092018-04-11 09:19:59 -07007923 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7924 outputTrack->setMetadatas(metadata.tracks);
7925 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007926}
7927
Andy Hungee58e4a2023-07-07 13:47:37 -07007928uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007929{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007930 // return half the wait time in microseconds.
7931 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007932}
7933
Andy Hungee58e4a2023-07-07 13:47:37 -07007934void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007935{
7936 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7937 updateWaitTime_l();
7938
7939 MixerThread::cacheParameters_l();
7940}
7941
Eric Laurentb3f315a2021-07-13 15:09:05 +02007942// ----------------------------------------------------------------------------
7943
Andy Hungee58e4a2023-07-07 13:47:37 -07007944/* static */
7945sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007946 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007947 AudioStreamOut* output,
7948 audio_io_handle_t id,
7949 bool systemReady,
7950 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007951 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007952}
7953
Andy Hung583043b2023-07-17 17:05:00 -07007954SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007955 AudioStreamOut* output,
7956 audio_io_handle_t id,
7957 bool systemReady,
7958 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007959 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007960{
7961}
7962
Andy Hungee58e4a2023-07-07 13:47:37 -07007963void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007964 // if mSupportedLatencyModes is empty, the HAL stream does not support
7965 // latency mode control and we can exit.
7966 if (mSupportedLatencyModes.empty()) {
7967 return;
7968 }
Eric Laurent4c85e372024-02-23 16:50:06 +00007969 // Do not update the HAL latency mode if no track is active
7970 if (mActiveTracks.isEmpty()) {
7971 return;
7972 }
7973
Eric Laurent68a40a82022-05-03 18:15:04 +02007974 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7975 if (mSupportedLatencyModes.size() == 1) {
7976 // If the HAL only support one latency mode currently, confirm the choice
7977 latencyMode = mSupportedLatencyModes[0];
7978 } else if (mSupportedLatencyModes.size() > 1) {
7979 // Request low latency if:
7980 // - The low latency mode is requested by the spatializer controller
7981 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7982 // AND
7983 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007984 for (const auto& track : mActiveTracks) {
7985 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007986 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007987 break;
7988 }
7989 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007990 }
7991
7992 if (latencyMode != mSetLatencyMode) {
7993 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007994 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7995 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007996 if (status == NO_ERROR) {
7997 mSetLatencyMode = latencyMode;
7998 }
7999 }
8000}
8001
Andy Hungee58e4a2023-07-07 13:47:37 -07008002status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008003 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008004 return BAD_VALUE;
8005 }
Andy Hung972bec12023-08-31 16:13:39 -07008006 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008007 mRequestedLatencyMode = mode;
8008 return NO_ERROR;
8009}
8010
Andy Hungee58e4a2023-07-07 13:47:37 -07008011void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008012NO_THREAD_SAFETY_ANALYSIS
8013// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008014{
8015 bool hasVirtualizer = false;
8016 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008017 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008018 {
Andy Hung972bec12023-08-31 16:13:39 -07008019 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008020 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008021 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008022 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008023 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8024 }
8025
8026 finalDownMixer = mFinalDownMixer;
8027 mFinalDownMixer.clear();
8028 }
8029
8030 if (hasVirtualizer) {
8031 if (finalDownMixer != nullptr) {
8032 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008033 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008034 }
8035 finalDownMixer.clear();
8036 } else if (!hasDownMixer) {
8037 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008038 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008039 EFFECT_UIID_DOWNMIX, &descriptors);
8040 if (status != NO_ERROR) {
8041 return;
8042 }
8043 ALOG_ASSERT(!descriptors.empty(),
8044 "%s getDescriptors() returned no error but empty list", __func__);
8045
8046 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8047 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008048 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008049
8050 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8051 ALOGW("%s error creating downmixer %d", __func__, status);
8052 finalDownMixer.clear();
8053 } else {
8054 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008055 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008056 }
8057 }
8058
8059 {
Andy Hung972bec12023-08-31 16:13:39 -07008060 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008061 mFinalDownMixer = finalDownMixer;
8062 }
8063}
8064
Andy Hunge2514462023-12-06 14:59:24 -08008065void SpatializerThread::threadLoop_exit()
8066{
8067 // The Spatializer EffectHandle must be released on the PlaybackThread
8068 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8069 mFinalDownMixer.clear();
8070
8071 PlaybackThread::threadLoop_exit();
8072}
8073
Eric Laurent81784c32012-11-19 14:55:58 -08008074// ----------------------------------------------------------------------------
8075// Record
8076// ----------------------------------------------------------------------------
8077
Andy Hung583043b2023-07-17 17:05:00 -07008078sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008079 AudioStreamIn* input,
8080 audio_io_handle_t id,
8081 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008082 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008083}
8084
Andy Hung583043b2023-07-17 17:05:00 -07008085RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008086 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008087 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008088 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008089 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008090 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008091 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008092 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008093 mActiveTracks(&this->mLocalLog),
8094 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008095 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008096 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008097 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8098 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008099 // mFastCapture below
8100 , mFastCaptureFutex(0)
8101 // mInputSource
8102 // mPipeSink
8103 // mPipeSource
8104 , mPipeFramesP2(0)
8105 // mPipeMemory
8106 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008107 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008108 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008109{
Glenn Kastend7dca052015-03-05 16:05:54 -08008110 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008111 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008112
George Burgess IVa8f90c12020-05-14 11:27:19 -07008113 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008114 mIsMsdDevice = strcmp(
8115 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8116 }
8117
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008118 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008119
Andy Hungc8fddf32018-08-08 18:32:37 -07008120 // TODO: We may also match on address as well as device type for
8121 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008122 // TODO: This property should be ensure that only contains one single device type.
8123 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8124 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008125 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8126 : AUDIO_DEVICE_NONE));
8127
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008128 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008129 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008130 size_t numCounterOffers = 0;
8131 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008132#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008133 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008134#else
8135 (void)
8136#endif
8137 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008138 ALOG_ASSERT(index == 0);
8139
8140 // initialize fast capture depending on configuration
8141 bool initFastCapture;
8142 switch (kUseFastCapture) {
8143 case FastCapture_Never:
8144 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008145 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008146 break;
8147 case FastCapture_Always:
8148 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008149 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008150 break;
8151 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008152 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008153 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008154 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008155 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8156 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8157 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008158 break;
8159 // case FastCapture_Dynamic:
8160 }
8161
8162 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008163 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008164 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008165 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8166 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008167 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008168 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008169 const sp<MemoryDealer> roHeap(readOnlyHeap());
8170 sp<IMemory> pipeMemory;
8171 if ((roHeap == 0) ||
8172 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008173 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008174 ALOGE("not enough memory for pipe buffer size=%zu; "
8175 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8176 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8177 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008178 goto failed;
8179 }
8180 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8181 memset(pipeBuffer, 0, pipeSize);
8182 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008183 const NBAIO_Format offersFast[1] = {format};
8184 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008185 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008186 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008187 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008188 mPipeSink = pipe;
8189 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008190 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008191 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008192 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008193 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008194 mPipeSource = pipeReader;
8195 mPipeFramesP2 = pipeFramesP2;
8196 mPipeMemory = pipeMemory;
8197
8198 // create fast capture
8199 mFastCapture = new FastCapture();
8200 FastCaptureStateQueue *sq = mFastCapture->sq();
8201#ifdef STATE_QUEUE_DUMP
8202 // FIXME
8203#endif
8204 FastCaptureState *state = sq->begin();
8205 state->mCblk = NULL;
8206 state->mInputSource = mInputSource.get();
8207 state->mInputSourceGen++;
8208 state->mPipeSink = pipe;
8209 state->mPipeSinkGen++;
8210 state->mFrameCount = mFrameCount;
8211 state->mCommand = FastCaptureState::COLD_IDLE;
8212 // already done in constructor initialization list
8213 //mFastCaptureFutex = 0;
8214 state->mColdFutexAddr = &mFastCaptureFutex;
8215 state->mColdGen++;
8216 state->mDumpState = &mFastCaptureDumpState;
8217#ifdef TEE_SINK
8218 // FIXME
8219#endif
Andy Hung583043b2023-07-17 17:05:00 -07008220 mFastCaptureNBLogWriter =
8221 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008222 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8223 sq->end();
8224 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8225
8226 // start the fast capture
8227 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8228 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008229 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008230 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008231#ifdef AUDIO_WATCHDOG
8232 // FIXME
8233#endif
8234
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008235 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008236 }
Andy Hung8946a282018-04-19 20:04:56 -07008237#ifdef TEE_SINK
8238 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8239 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8240#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008241failed: ;
8242
8243 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008244}
8245
Andy Hungee58e4a2023-07-07 13:47:37 -07008246RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008247{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008248 if (mFastCapture != 0) {
8249 FastCaptureStateQueue *sq = mFastCapture->sq();
8250 FastCaptureState *state = sq->begin();
8251 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8252 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8253 if (old == -1) {
8254 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8255 }
8256 }
8257 state->mCommand = FastCaptureState::EXIT;
8258 sq->end();
8259 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8260 mFastCapture->join();
8261 mFastCapture.clear();
8262 }
Andy Hung583043b2023-07-17 17:05:00 -07008263 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8264 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008265 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008266}
8267
Andy Hungee58e4a2023-07-07 13:47:37 -07008268void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008269{
Glenn Kastend7dca052015-03-05 16:05:54 -08008270 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008271}
8272
Andy Hungee58e4a2023-07-07 13:47:37 -07008273void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008274{
8275 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008276 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008277 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008278 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008279 track->invalidate();
8280 }
8281 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008282 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008283}
8284
Andy Hungee58e4a2023-07-07 13:47:37 -07008285bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008286{
Eric Laurent81784c32012-11-19 14:55:58 -08008287 nsecs_t lastWarning = 0;
8288
8289 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008290
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008291reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008292 {
Andy Hung972bec12023-08-31 16:13:39 -07008293 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008294 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008295 }
8296
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008297 // used to request a deferred sleep, to be executed later while mutex is unlocked
8298 uint32_t sleepUs = 0;
8299
Andy Hung95c94a22023-10-20 16:41:18 -07008300 // timestamp correction enable is determined under lock, used in processing step.
8301 bool timestampCorrectionEnabled = false;
8302
Andy Hung446f4df2019-02-21 12:26:41 -08008303 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8304
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008305 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008306 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008307 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8308 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008309 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008310 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008311
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008312 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008313 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008314
Glenn Kasten735f45f2014-08-18 15:51:59 -07008315 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008316 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008317
Glenn Kasten735f45f2014-08-18 15:51:59 -07008318 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008319 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008320
Eric Laurent33403f02020-05-29 18:35:06 -07008321 bool silenceFastCapture = false;
8322
Andy Hungc5007f82023-08-29 14:26:09 -07008323 { // scope for mutex()
8324 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008325
Eric Laurent021cf962014-05-13 10:18:14 -07008326 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008327
Eric Laurent000a4192014-01-29 15:17:32 -08008328 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008329 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008330 if (exitPending()) {
8331 break;
8332 }
8333
Eric Laurent5c25d562016-07-13 17:17:45 -07008334 // sleep with mutex unlocked
8335 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008336 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008337 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008338 ATRACE_END();
8339 sleepUs = 0;
8340 continue;
8341 }
8342
Glenn Kasten2b806402013-11-20 16:37:38 -08008343 // if no active track(s), then standby and release wakelock
8344 size_t size = mActiveTracks.size();
8345 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008346 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008347 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008348 releaseWakeLock_l();
8349 ALOGV("RecordThread: loop stopping");
8350 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008351 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008352 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008353 goto reacquire_wakelock;
8354 }
8355
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008356 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008357 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008358 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008359 if (activeTrack) { // ensure track release is outside lock.
8360 oldActiveTracks.emplace_back(std::move(activeTrack));
8361 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008362 activeTrack = mActiveTracks[i];
8363 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008364 if (activeTrack->isFastTrack()) {
8365 ALOG_ASSERT(fastTrackToRemove == 0);
8366 fastTrackToRemove = activeTrack;
8367 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008368 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008369 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008370 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008371 continue;
8372 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008373
Andy Hung8d31fd22023-06-26 19:20:57 -07008374 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008375 switch (activeTrackState) {
8376
Andy Hung8d31fd22023-06-26 19:20:57 -07008377 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008378 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008379 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008380 if (activeTrack->isFastTrack()) {
8381 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8382 // Keep a ref on fast track to wait for FastCapture thread to get updated
8383 // state before potential track removal
8384 fastTrackToRemove = activeTrack;
8385 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008386 doBroadcast = true;
8387 size--;
8388 continue;
8389
Andy Hung8d31fd22023-06-26 19:20:57 -07008390 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008391 sleepUs = 10000;
8392 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008393 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008394 continue;
8395
Andy Hung8d31fd22023-06-26 19:20:57 -07008396 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008397 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008398 if (mStandby) {
8399 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008400 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008401 mStandby = false;
8402 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008403 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008404 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008405 break;
8406
Andy Hung8d31fd22023-06-26 19:20:57 -07008407 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008408 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008409 break;
8410
Andy Hung8d31fd22023-06-26 19:20:57 -07008411 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8412 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8413 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008414 default:
Andy Hungce685402018-10-05 17:23:27 -07008415 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8416 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008417 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008418
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008419 if (activeTrack->isFastTrack()) {
8420 ALOG_ASSERT(!mFastTrackAvail);
8421 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008422 // if the active fast track is silenced either:
8423 // 1) silence the whole capture from fast capture buffer if this is
8424 // the only active track
8425 // 2) invalidate this track: this will cause the client to reconnect and possibly
8426 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008427 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008428 if (activeTrack->isSilenced()) {
8429 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008430 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008431 } else {
8432 silenceFastCapture = true;
8433 }
8434 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008435 // Invalidate fast tracks if access to audio history is required as this is not
8436 // possible with fast tracks. Once the fast track has been invalidated, no new
8437 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8438 if (mMaxSharedAudioHistoryMs != 0) {
8439 invalidate = true;
8440 }
8441 if (invalidate) {
8442 activeTrack->invalidate();
8443 ALOG_ASSERT(fastTrackToRemove == 0);
8444 fastTrackToRemove = activeTrack;
8445 removeTrack_l(activeTrack);
8446 mActiveTracks.remove(activeTrack);
8447 size--;
8448 continue;
8449 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008450 fastTrack = activeTrack;
8451 }
Eric Laurent33403f02020-05-29 18:35:06 -07008452
8453 activeTracks.add(activeTrack);
8454 i++;
8455
Glenn Kasten9e982352013-08-14 14:39:50 -07008456 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008457
Andy Hungab65b182023-09-06 19:41:47 -07008458 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008459
Kevin Rocard069c2712018-03-29 19:09:14 -07008460 updateMetadata_l();
8461
Eric Laurent5c25d562016-07-13 17:17:45 -07008462 if (allStopped) {
8463 standbyIfNotAlreadyInStandby();
8464 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008465 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008466 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008467 }
8468
8469 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008470 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008471 if (sleepUs == 0) {
8472 sleepUs = kRecordThreadSleepUs;
8473 }
8474 continue;
8475 }
8476 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008477
Andy Hung95c94a22023-10-20 16:41:18 -07008478 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008479 lockEffectChains_l(effectChains);
8480 }
8481
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008482 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008483
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 size_t size = effectChains.size();
8485 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008486 // thread mutex is not locked, but effect chain is locked
8487 effectChains[i]->process_l();
8488 }
8489
Glenn Kasten735f45f2014-08-18 15:51:59 -07008490 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008491 if (mFastCapture != 0) {
8492 FastCaptureStateQueue *sq = mFastCapture->sq();
8493 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008494 bool didModify = false;
8495 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008496 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8497 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8498 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8499 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8500 if (old == -1) {
8501 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8502 }
8503 }
8504 state->mCommand = FastCaptureState::READ_WRITE;
8505#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008506 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008507 FastThreadDumpState::kSamplingNforLowRamDevice :
8508 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008509#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008510 didModify = true;
8511 }
8512 audio_track_cblk_t *cblkOld = state->mCblk;
8513 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8514 if (cblkNew != cblkOld) {
8515 state->mCblk = cblkNew;
8516 // block until acked if removing a fast track
8517 if (cblkOld != NULL) {
8518 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8519 }
8520 didModify = true;
8521 }
jiabin01c8f562018-07-19 17:47:28 -07008522 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8523 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8524 if (state->mFastPatchRecordBufferProvider != abp) {
8525 state->mFastPatchRecordBufferProvider = abp;
8526 state->mFastPatchRecordFormat = fastTrack == 0 ?
8527 AUDIO_FORMAT_INVALID : fastTrack->format();
8528 didModify = true;
8529 }
Eric Laurent33403f02020-05-29 18:35:06 -07008530 if (state->mSilenceCapture != silenceFastCapture) {
8531 state->mSilenceCapture = silenceFastCapture;
8532 didModify = true;
8533 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008534 sq->end(didModify);
8535 if (didModify) {
8536 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008537#if 0
8538 if (kUseFastCapture == FastCapture_Dynamic) {
8539 mNormalSource = mPipeSource;
8540 }
8541#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008542 }
8543 }
8544
Glenn Kasten735f45f2014-08-18 15:51:59 -07008545 // now run the fast track destructor with thread mutex unlocked
8546 fastTrackToRemove.clear();
8547
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008548 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8549 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8550 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8551 // If destination is non-contiguous, first read past the nominal end of buffer, then
8552 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008553
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008554 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008555 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008556 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008557
8558 // If an NBAIO source is present, use it to read the normal capture's data
8559 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008560 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008561
8562 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8563 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8564 // we immediately retry the read() to get data and prevent another overflow.
8565 for (int retries = 0; retries <= 2; ++retries) {
8566 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8567 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8568 framesToRead);
8569 if (framesRead != OVERRUN) break;
8570 }
8571
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008572 const ssize_t availableToRead = mPipeSource->availableToRead();
8573 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008574 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008575 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008576 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8577 "more frames to read than fifo size, %zd > %zu",
8578 availableToRead, mPipeFramesP2);
8579 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8580 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8581 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8582 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008583 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8584 }
8585 if (framesRead < 0) {
8586 status_t status = (status_t) framesRead;
8587 switch (status) {
8588 case OVERRUN:
8589 ALOGW("overrun on read from pipe");
8590 framesRead = 0;
8591 break;
8592 case NEGOTIATE:
8593 ALOGE("re-negotiation is needed");
8594 framesRead = -1; // Will cause an attempt to recover.
8595 break;
8596 default:
8597 ALOGE("unknown error %d on read from pipe", status);
8598 break;
8599 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008600 }
8601 // otherwise use the HAL / AudioStreamIn directly
8602 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008603 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008604 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008605 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008606 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008607 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008608 if (result < 0) {
8609 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008610 } else {
8611 framesRead = bytesRead / mFrameSize;
8612 }
8613 }
8614
Andy Hung446f4df2019-02-21 12:26:41 -08008615 const int64_t lastIoEndNs = systemTime(); // end IO timing
8616
Andy Hung3f0c9022016-01-15 17:49:46 -08008617 // Update server timestamp with server stats
8618 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008619 if (framesRead >= 0) {
8620 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8621 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8622 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008623
8624 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008625 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008626 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008627 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008628 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8629 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8630 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008631 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008632 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8633
8634 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008635 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008636 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008637 id(), (long long)time, (long long)position);
8638 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8639 position = correctedTimestamp.mFrames;
8640 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008641 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008642 id(), (long long)time, (long long)position);
8643 }
8644
Andy Hung3f0c9022016-01-15 17:49:46 -08008645 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8646 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8647 // Note: In general record buffers should tend to be empty in
8648 // a properly running pipeline.
8649 //
8650 // Also, it is not advantageous to call get_presentation_position during the read
8651 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008652 } else {
8653 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008654 }
8655 }
Andy Hunge6c37112019-02-26 17:38:10 -08008656
8657 // From the timestamp, input read latency is negative output write latency.
8658 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008659 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008660 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8661 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8662 mLatencyMs.add(latencyMs);
8663 }
8664
Andy Hung3f0c9022016-01-15 17:49:46 -08008665 // Use this to track timestamp information
8666 // ALOGD("%s", mTimestamp.toString().c_str());
8667
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008668 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008669 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008670 // Force input into standby so that it tries to recover at next read attempt
8671 inputStandBy();
8672 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008673 }
8674 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008675 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008676 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008677 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008678 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008679
Andy Hung8946a282018-04-19 20:04:56 -07008680#ifdef TEE_SINK
8681 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8682#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008683 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008684 {
8685 size_t part1 = mRsmpInFramesP2 - rear;
8686 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008687 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008688 (framesRead - part1) * mFrameSize);
8689 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008690 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008691 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008692
8693 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008694
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008695 // loop over each active track
8696 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008697 if (activeTrack) { // ensure track release is outside lock.
8698 oldActiveTracks.emplace_back(std::move(activeTrack));
8699 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008700 activeTrack = activeTracks[i];
8701
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008702 // skip fast tracks, as those are handled directly by FastCapture
8703 if (activeTrack->isFastTrack()) {
8704 continue;
8705 }
8706
Andy Hung73c02e42015-03-29 01:13:58 -07008707 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008708 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8709
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008710 enum {
8711 OVERRUN_UNKNOWN,
8712 OVERRUN_TRUE,
8713 OVERRUN_FALSE
8714 } overrun = OVERRUN_UNKNOWN;
8715
8716 // loop over getNextBuffer to handle circular sink
8717 for (;;) {
8718
Andy Hung8d31fd22023-06-26 19:20:57 -07008719 activeTrack->sinkBuffer().frameCount = ~0;
8720 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8721 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008722 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8723
Andy Hung73c02e42015-03-29 01:13:58 -07008724 // check available frames and handle overrun conditions
8725 // if the record track isn't draining fast enough.
8726 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008727 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008728 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008729 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008730 overrun = OVERRUN_TRUE;
8731 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008732 if (framesOut == 0 || framesIn == 0) {
8733 break;
8734 }
8735
Andy Hung6770c6f2015-04-07 13:43:36 -07008736 // Don't allow framesOut to be larger than what is possible with resampling
8737 // from framesIn.
8738 // This isn't strictly necessary but helps limit buffer resizing in
8739 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008740 if (audio_is_linear_pcm(activeTrack->format())) {
8741 framesOut = min(framesOut,
8742 destinationFramesPossible(
8743 framesIn, mSampleRate, activeTrack->sampleRate()));
8744 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008745
8746 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008747 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008748 // straight from RecordThread buffer to RecordTrack buffer.
8749 AudioBufferProvider::Buffer buffer;
8750 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008751 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008752 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008753 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008754 ALOGV_IF(buffer.frameCount != framesOut,
8755 "%s() read less than expected (%zu vs %zu)",
8756 __func__, buffer.frameCount, framesOut);
8757 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008758 memcpy(activeTrack->sinkBuffer().raw,
8759 buffer.raw, buffer.frameCount * mFrameSize);
8760 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008761 } else {
8762 framesOut = 0;
8763 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008764 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008765 }
8766 } else {
8767 // process frames from the RecordThread buffer provider to the RecordTrack
8768 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008769 framesOut = activeTrack->recordBufferConverter()->convert(
8770 activeTrack->sinkBuffer().raw,
8771 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008772 framesOut);
8773 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008774
8775 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8776 overrun = OVERRUN_FALSE;
8777 }
8778
Andy Hung93bb5732023-05-04 21:16:34 -07008779 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8780 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008781 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008782 if (framesToDrop == 0) {
8783 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008784 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008785 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008786 // Sanitize before releasing if the track has no access to the source data
8787 // An idle UID receives silence from non virtual devices until active
8788 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008789 memset(activeTrack->sinkBuffer().raw,
8790 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008791 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008792 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008793 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008794 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008795 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008796 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008797 }
8798 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008799
8800 switch (overrun) {
8801 case OVERRUN_TRUE:
8802 // client isn't retrieving buffers fast enough
8803 if (!activeTrack->setOverflow()) {
8804 nsecs_t now = systemTime();
8805 // FIXME should lastWarning per track?
8806 if ((now - lastWarning) > kWarningThrottleNs) {
8807 ALOGW("RecordThread: buffer overflow");
8808 lastWarning = now;
8809 }
8810 }
8811 break;
8812 case OVERRUN_FALSE:
8813 activeTrack->clearOverflow();
8814 break;
8815 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008816 break;
8817 }
8818
Andy Hung3f0c9022016-01-15 17:49:46 -08008819 // update frame information and push timestamp out
8820 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008821 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008822 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8823 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008824 }
8825
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008826unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008827 // enable changes in effect chain
8828 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008829 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008830 if (audio_has_proportional_frames(mFormat)
8831 && loopCount == lastLoopCountRead + 1) {
8832 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8833 const double jitterMs =
8834 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8835 {framesRead, readPeriodNs},
8836 {0, 0} /* lastTimestamp */, mSampleRate);
8837 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8838
Andy Hung972bec12023-08-31 16:13:39 -07008839 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008840 mIoJitterMs.add(jitterMs);
8841 mProcessTimeMs.add(processMs);
8842 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008843 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008844 // update timing info.
8845 mLastIoBeginNs = lastIoBeginNs;
8846 mLastIoEndNs = lastIoEndNs;
8847 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008848 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008849 mThreadloopExecutor.process(); // process any remaining deferred actions.
8850 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008851
Glenn Kasten93e471f2013-08-19 08:40:07 -07008852 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008853
8854 {
Andy Hung972bec12023-08-31 16:13:39 -07008855 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008856 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008857 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008858 track->invalidate();
8859 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008860 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008861 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008862 }
8863
8864 releaseWakeLock();
8865
8866 ALOGV("RecordThread %p exiting", this);
8867 return false;
8868}
8869
Andy Hungee58e4a2023-07-07 13:47:37 -07008870void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008871{
8872 if (!mStandby) {
8873 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008874 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008875 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008876 mStandby = true;
8877 }
8878}
8879
Andy Hungee58e4a2023-07-07 13:47:37 -07008880void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008881{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008882 // Idle the fast capture if it's currently running
8883 if (mFastCapture != 0) {
8884 FastCaptureStateQueue *sq = mFastCapture->sq();
8885 FastCaptureState *state = sq->begin();
8886 if (!(state->mCommand & FastCaptureState::IDLE)) {
8887 state->mCommand = FastCaptureState::COLD_IDLE;
8888 state->mColdFutexAddr = &mFastCaptureFutex;
8889 state->mColdGen++;
8890 mFastCaptureFutex = 0;
8891 sq->end();
8892 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8893 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8894#if 0
8895 if (kUseFastCapture == FastCapture_Dynamic) {
8896 // FIXME
8897 }
8898#endif
8899#ifdef AUDIO_WATCHDOG
8900 // FIXME
8901#endif
8902 } else {
8903 sq->end(false /*didModify*/);
8904 }
8905 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008906 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008907 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008908
8909 // If going into standby, flush the pipe source.
8910 if (mPipeSource.get() != nullptr) {
8911 const ssize_t flushed = mPipeSource->flush();
8912 if (flushed > 0) {
8913 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8914 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8915 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8916 }
8917 }
Eric Laurent81784c32012-11-19 14:55:58 -08008918}
8919
Andy Hungc5007f82023-08-29 14:26:09 -07008920// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008921sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008922 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008923 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008924 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008925 audio_format_t format,
8926 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008927 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008928 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008929 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008930 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008931 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008932 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008933 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008934 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008935 audio_port_handle_t portId,
8936 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008937{
Glenn Kasten74935e42013-12-19 08:56:45 -08008938 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008939 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008940 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008941 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008942 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008943 audio_input_flags_t requestedFlags = *flags;
8944 uint32_t sampleRate;
8945
8946 lStatus = initCheck();
8947 if (lStatus != NO_ERROR) {
8948 ALOGE("createRecordTrack_l() audio driver not initialized");
8949 goto Exit;
8950 }
8951
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008952 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8953 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8954 lStatus = BAD_VALUE;
8955 goto Exit;
8956 }
8957
Eric Laurentec376dc2021-04-08 20:41:22 +02008958 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008959 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008960 lStatus = PERMISSION_DENIED;
8961 goto Exit;
8962 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008963 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008964 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008965 lStatus = BAD_VALUE;
8966 goto Exit;
8967 }
8968 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008969 if (*pSampleRate == 0) {
8970 *pSampleRate = mSampleRate;
8971 }
8972 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008973
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008974 // special case for FAST flag considered OK if fast capture is present and access to
8975 // audio history is not required
8976 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008977 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8978 }
8979
Eric Laurentf14db3c2017-12-08 14:20:36 -08008980 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008981 if ((*flags & inputFlags) != *flags) {
8982 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8983 " input flags (%08x)",
8984 *flags, inputFlags);
8985 *flags = (audio_input_flags_t)(*flags & inputFlags);
8986 }
Eric Laurent81784c32012-11-19 14:55:58 -08008987
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008988 // client expresses a preference for FAST and no access to audio history,
8989 // but we get the final say
8990 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008991 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008992 // we formerly checked for a callback handler (non-0 tid),
8993 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008994 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008995 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008996 // Frame count is not specified (0), or is less than or equal the pipe depth.
8997 // It is OK to provide a higher capacity than requested.
8998 // We will force it to mPipeFramesP2 below.
8999 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009000 // PCM data
9001 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009002 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009003 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009004 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009005 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009006 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009007 hasFastCapture() &&
9008 // there are sufficient fast track slots available
9009 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009010 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009011 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009012 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009013 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009014 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009015 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009016 audio_input_flags_t old = *flags;
9017 chain->checkInputFlagCompatibility(flags);
9018 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009019 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9020 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009021 }
9022 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009023 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009024 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9025 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009026 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009027 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9028 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009029 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009030 this, frameCount, mFrameCount, mPipeFramesP2,
9031 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009032 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009033 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009034 }
9035 }
9036
Eric Laurentf14db3c2017-12-08 14:20:36 -08009037 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9038 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9039 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9040 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9041 lStatus = BAD_TYPE;
9042 goto Exit;
9043 }
9044
Glenn Kasten74105912014-07-03 12:28:53 -07009045 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009046 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009047 // fast track: frame count is exactly the pipe depth
9048 frameCount = mPipeFramesP2;
9049 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009050 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009051 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009052 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9053 // or 20 ms if there is a fast capture
9054 // TODO This could be a roundupRatio inline, and const
9055 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9056 * sampleRate + mSampleRate - 1) / mSampleRate;
9057 // minimum number of notification periods is at least kMinNotifications,
9058 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9059 static const size_t kMinNotifications = 3;
9060 static const uint32_t kMinMs = 30;
9061 // TODO This could be a roundupRatio inline
9062 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9063 // TODO This could be a roundupRatio inline
9064 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9065 maxNotificationFrames;
9066 const size_t minFrameCount = maxNotificationFrames *
9067 max(kMinNotifications, minNotificationsByMs);
9068 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009069 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9070 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009071 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009072 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009073 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009074 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009075
Andy Hungc5007f82023-08-29 14:26:09 -07009076 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009077 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009078 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009079 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009080 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009081 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009082 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009083 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009084 }
Eric Laurent81784c32012-11-19 14:55:58 -08009085
Andy Hung8d31fd22023-06-26 19:20:57 -07009086 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009087 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009088 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009089 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009090 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009091
Glenn Kasten03003332013-08-06 15:40:54 -07009092 lStatus = track->initCheck();
9093 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009094 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009095 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009096 goto Exit;
9097 }
9098 mTracks.add(track);
9099
Eric Laurent05067782016-06-01 18:27:28 -07009100 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009101 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9102 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9103 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009104 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009105 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009106
9107 if (maxSharedAudioHistoryMs != 0) {
9108 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9109 }
Eric Laurent81784c32012-11-19 14:55:58 -08009110 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009111
Eric Laurent81784c32012-11-19 14:55:58 -08009112 lStatus = NO_ERROR;
9113
9114Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009115 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009116 return track;
9117}
9118
Andy Hungee58e4a2023-07-07 13:47:37 -07009119status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009120 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009121 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009122{
9123 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9124 sp<ThreadBase> strongMe = this;
9125 status_t status = NO_ERROR;
9126
9127 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009128 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009129 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009130 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009131 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009132 event, triggerSession,
9133 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009134 }
9135
9136 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009137 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009138 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009139 if (recordTrack->isInvalid()) {
9140 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009141 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9142 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009143 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009144 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009145 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009146 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9147 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009148 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009149 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009150 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009151 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009152 }
9153 return status;
9154 }
9155
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009156 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9157 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9158 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009159 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009160 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009161 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009162 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009163 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009164 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009165 if (recordTrack->isInvalid()) {
9166 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009167 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9168 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009169 // STARTING_2 forces destroy to call stopInput.
9170 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009171 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9172 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009173 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009174 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009175 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009176 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009177 // Someone else has changed state, let them take over,
9178 // leave mState in the new state.
9179 recordTrack->clearSyncStartEvent();
9180 return INVALID_OPERATION;
9181 }
9182 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009183 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009184 ALOGW("%s(%d): startInput failed, status %d",
9185 __func__, recordTrack->id(), status);
9186 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9187 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009188 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009189 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009190 return status;
9191 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009192 sendIoConfigEvent_l(
9193 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009194 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009195
9196 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9197
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009198 // Catch up with current buffer indices if thread is already running.
9199 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9200 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9201 // see previously buffered data before it called start(), but with greater risk of overrun.
9202
Andy Hung8d31fd22023-06-26 19:20:57 -07009203 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009204 if (!recordTrack->isDirect()) {
9205 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009206 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009207 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009208 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009209 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009210 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009211 return status;
9212 }
Eric Laurent81784c32012-11-19 14:55:58 -08009213}
9214
Andy Hungee58e4a2023-07-07 13:47:37 -07009215void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009216{
Andy Hungee58e4a2023-07-07 13:47:37 -07009217 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009218
9219 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009220 sp<IAfTrackBase> ptr =
9221 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9222 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009223 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009224 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009225 }
Eric Laurent81784c32012-11-19 14:55:58 -08009226 }
9227}
9228
Andy Hungee58e4a2023-07-07 13:47:37 -07009229bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009230 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009231 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009232 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009233 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009234 return false;
9235 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009236 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009237 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009238
Andy Hungabfab202019-03-07 19:45:54 -08009239 // NOTE: Waiting here is important to keep stop synchronous.
9240 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009241 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009242 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009243 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009244 }
Andy Hungce685402018-10-05 17:23:27 -07009245
Andy Hung8d31fd22023-06-26 19:20:57 -07009246 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009247 ALOGV("Record stopped OK");
9248 return true;
9249 }
Andy Hungce685402018-10-05 17:23:27 -07009250
9251 // don't handle anything - we've been invalidated or restarted and in a different state
9252 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009253 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009254 return false;
9255}
9256
Andy Hungee58e4a2023-07-07 13:47:37 -07009257bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009258{
9259 return false;
9260}
9261
Andy Hungee58e4a2023-07-07 13:47:37 -07009262status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009263{
9264#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9265 if (!isValidSyncEvent(event)) {
9266 return BAD_VALUE;
9267 }
9268
Glenn Kastend848eb42016-03-08 13:42:11 -08009269 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009270 status_t ret = NAME_NOT_FOUND;
9271
Andy Hung972bec12023-08-31 16:13:39 -07009272 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009273
9274 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009275 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009276 if (eventSession == track->sessionId()) {
9277 (void) track->setSyncEvent(event);
9278 ret = NO_ERROR;
9279 }
9280 }
9281 return ret;
9282#else
9283 return BAD_VALUE;
9284#endif
9285}
9286
Andy Hungee58e4a2023-07-07 13:47:37 -07009287status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009288 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009289{
9290 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009291 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009292 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009293 return NO_INIT;
9294 }
jiabin9ff780e2018-03-19 18:19:52 -07009295 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9296 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009297}
9298
Andy Hungee58e4a2023-07-07 13:47:37 -07009299status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009300 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009301{
Paul McLean12340082019-03-19 09:35:05 -06009302 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009303 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009304 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009305 return NO_INIT;
9306 }
Paul McLean12340082019-03-19 09:35:05 -06009307 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009308}
9309
Andy Hungee58e4a2023-07-07 13:47:37 -07009310status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009311{
Paul McLean12340082019-03-19 09:35:05 -06009312 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009313 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009314 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009315 return NO_INIT;
9316 }
Paul McLean12340082019-03-19 09:35:05 -06009317 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009318}
9319
Andy Hungee58e4a2023-07-07 13:47:37 -07009320status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009321 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9322 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009323 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009324 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9325}
9326
Andy Hungee58e4a2023-07-07 13:47:37 -07009327status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009328 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9329 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009330
Eric Laurentec376dc2021-04-08 20:41:22 +02009331 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9332 return BAD_VALUE;
9333 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009334
9335 if (sharedAudioStartMs < 0
9336 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009337 return BAD_VALUE;
9338 }
9339
Eric Laurent2407ce32021-04-26 14:56:03 +02009340 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9341 // As we cannot detect more than one wraparound, only accept values up current write position
9342 // after one wraparound
9343 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9344 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009345 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009346 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9347 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009348 // Bring the start frame position within the input buffer to match the documented
9349 // "best effort" behavior of the API.
9350 if (sharedOffset < 0) {
9351 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009352 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009353 sharedAudioStartFrames =
9354 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009355 }
9356
Eric Laurentec376dc2021-04-08 20:41:22 +02009357 mSharedAudioPackageName = sharedAudioPackageName;
9358 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009359 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009360 } else {
9361 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009362 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009363 }
9364 return NO_ERROR;
9365}
9366
Andy Hungee58e4a2023-07-07 13:47:37 -07009367void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009368 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9369 mSharedAudioStartFrames = -1;
9370 mSharedAudioPackageName = "";
9371}
9372
Andy Hungee58e4a2023-07-07 13:47:37 -07009373ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009374{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009375 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009376 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009377 }
9378 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009379 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009380 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009381 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009382 }
9383 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009384 MetadataUpdate change;
9385 change.recordMetadataUpdate = metadata.tracks;
9386 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009387}
9388
Andy Hungc5007f82023-08-29 14:26:09 -07009389// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009390void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009391{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009392 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009393 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009394
Eric Laurent81784c32012-11-19 14:55:58 -08009395 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009396 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009397 removeTrack_l(track);
9398 }
9399}
9400
Andy Hungee58e4a2023-07-07 13:47:37 -07009401void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009402{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009403 String8 result;
9404 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009405 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009406
Eric Laurent81784c32012-11-19 14:55:58 -08009407 mTracks.remove(track);
9408 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009409 if (track->isFastTrack()) {
9410 ALOG_ASSERT(!mFastTrackAvail);
9411 mFastTrackAvail = true;
9412 }
Eric Laurent81784c32012-11-19 14:55:58 -08009413}
9414
Andy Hungee58e4a2023-07-07 13:47:37 -07009415void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009416{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009417 AudioStreamIn *input = mInput;
9418 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9419 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009420 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009421 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009422 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009423 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009424 }
Andy Hungbfa64962017-06-12 14:43:19 -07009425
9426 if (input != nullptr) {
9427 dprintf(fd, " Hal stream dump:\n");
9428 (void)input->stream->dump(fd);
9429 }
9430
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009431 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009432 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009433
Glenn Kasten2f90c512015-12-02 11:40:09 -08009434 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9435 // while we are dumping it. It may be inconsistent, but it won't mutate!
9436 // This is a large object so we place it on the heap.
9437 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009438 const std::unique_ptr<FastCaptureDumpState> copy =
9439 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009440 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009441}
9442
Andy Hungee58e4a2023-07-07 13:47:37 -07009443void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009444{
Eric Laurent81784c32012-11-19 14:55:58 -08009445 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009446 size_t numtracks = mTracks.size();
9447 size_t numactive = mActiveTracks.size();
9448 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009449 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009450 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009451 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009452 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009453 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009454 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009455 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009456 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009457 if (track != 0) {
9458 bool active = mActiveTracks.indexOf(track) >= 0;
9459 if (active) {
9460 numactiveseen++;
9461 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009462 result.append(prefix);
9463 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009464 }
Eric Laurent81784c32012-11-19 14:55:58 -08009465 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009466 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009467 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009468 }
9469
Marco Nelissenb2208842014-02-07 14:00:50 -08009470 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009471 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009472 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009473 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009474 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009475 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009476 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009477 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009478 result.append(prefix);
9479 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009480 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009481 }
Eric Laurent81784c32012-11-19 14:55:58 -08009482
9483 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009484 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009485}
9486
Andy Hungee58e4a2023-07-07 13:47:37 -07009487void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009488{
Andy Hung972bec12023-08-31 16:13:39 -07009489 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009490 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009491 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009492 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009493 track->setSilenced(silenced);
9494 }
9495 }
9496}
Andy Hung73c02e42015-03-29 01:13:58 -07009497
Andy Hung8d31fd22023-06-26 19:20:57 -07009498void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009499{
Andy Hung87c693c2023-07-06 20:56:16 -07009500 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009501 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009502 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009503 const int32_t rear = recordThread->mRsmpInRear;
9504 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009505 if (mRecordTrack->startFrames() >= 0) {
9506 int32_t startFrames = mRecordTrack->startFrames();
9507 // Accept a recent wraparound of mRsmpInRear
9508 if (startFrames <= rear) {
9509 deltaFrames = rear - startFrames;
9510 } else {
9511 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009512 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009513 // start frame cannot be further in the past than start of resampling buffer
9514 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9515 deltaFrames = recordThread->mRsmpInFrames;
9516 }
9517 }
9518 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009519}
9520
Andy Hung8d31fd22023-06-26 19:20:57 -07009521void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009522 size_t *framesAvailable, bool *hasOverrun)
9523{
Andy Hung87c693c2023-07-06 20:56:16 -07009524 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009525 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009526 const int32_t rear = recordThread->mRsmpInRear;
9527 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009528 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009529
9530 size_t framesIn;
9531 bool overrun = false;
9532 if (filled < 0) {
9533 // should not happen, but treat like a massive overrun and re-sync
9534 framesIn = 0;
9535 mRsmpInFront = rear;
9536 overrun = true;
9537 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9538 framesIn = (size_t) filled;
9539 } else {
9540 // client is not keeping up with server, but give it latest data
9541 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009542 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9543 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009544 overrun = true;
9545 }
9546 if (framesAvailable != NULL) {
9547 *framesAvailable = framesIn;
9548 }
9549 if (hasOverrun != NULL) {
9550 *hasOverrun = overrun;
9551 }
9552}
9553
Eric Laurent81784c32012-11-19 14:55:58 -08009554// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009555status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009556 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009557{
Andy Hung87c693c2023-07-06 20:56:16 -07009558 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009559 if (threadBase == 0) {
9560 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009561 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009562 return NOT_ENOUGH_DATA;
9563 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009564 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009565 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009566 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009567 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009568 // FIXME should not be P2 (don't want to increase latency)
9569 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009570 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009571 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009572
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009573 front &= recordThread->mRsmpInFramesP2 - 1;
9574 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009575 if (part1 > (size_t) filled) {
9576 part1 = filled;
9577 }
9578 size_t ask = buffer->frameCount;
9579 ALOG_ASSERT(ask > 0);
9580 if (part1 > ask) {
9581 part1 = ask;
9582 }
9583 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009584 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009585 buffer->raw = NULL;
9586 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009587 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009588 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009589 }
9590
Andy Hung57446612015-04-19 23:56:46 -07009591 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009592 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009593 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009594 return NO_ERROR;
9595}
9596
9597// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009598void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009599 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009600{
Hongwei Wang95e37682019-04-12 11:13:36 -07009601 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009602 if (stepCount == 0) {
9603 return;
9604 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009605 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009606 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009607 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009608 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009609 buffer->frameCount = 0;
9610}
9611
Andy Hungee58e4a2023-07-07 13:47:37 -07009612void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009613{
Andy Hung972bec12023-08-31 16:13:39 -07009614 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009615 checkBtNrec_l();
9616}
9617
Andy Hungee58e4a2023-07-07 13:47:37 -07009618void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009619{
9620 // disable AEC and NS if the device is a BT SCO headset supporting those
9621 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009622 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009623 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009624 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9625 for (size_t i = 0; i < mEffectChains.size(); i++) {
9626 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9627 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9628 }
9629 }
9630}
9631
Andy Hung97a893e2015-03-29 01:03:07 -07009632
Andy Hungee58e4a2023-07-07 13:47:37 -07009633bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009634 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009635{
9636 bool reconfig = false;
9637
Eric Laurent10351942014-05-08 18:49:52 -07009638 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009639
Eric Laurent10351942014-05-08 18:49:52 -07009640 audio_format_t reqFormat = mFormat;
9641 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009642 // 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 +08009643 [[maybe_unused]] audio_channel_mask_t channelMask =
9644 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009645
9646 AudioParameter param = AudioParameter(keyValuePair);
9647 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009648
9649 // scope for AutoPark extends to end of method
9650 AutoPark<FastCapture> park(mFastCapture);
9651
Eric Laurent10351942014-05-08 18:49:52 -07009652 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9653 // channel count change can be requested. Do we mandate the first client defines the
9654 // HAL sampling rate and channel count or do we allow changes on the fly?
9655 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9656 samplingRate = value;
9657 reconfig = true;
9658 }
9659 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009660 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009661 status = BAD_VALUE;
9662 } else {
9663 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009664 reconfig = true;
9665 }
Eric Laurent10351942014-05-08 18:49:52 -07009666 }
9667 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9668 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009669 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009670 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009671 status = BAD_VALUE;
9672 } else {
9673 channelMask = mask;
9674 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009675 }
Eric Laurent10351942014-05-08 18:49:52 -07009676 }
9677 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9678 // do not accept frame count changes if tracks are open as the track buffer
9679 // size depends on frame count and correct behavior would not be guaranteed
9680 // if frame count is changed after track creation
9681 if (mActiveTracks.size() > 0) {
9682 status = INVALID_OPERATION;
9683 } else {
9684 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009685 }
Eric Laurent10351942014-05-08 18:49:52 -07009686 }
9687 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009688 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009689 }
9690 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9691 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009692 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009693 }
Glenn Kastene198c362013-08-13 09:13:36 -07009694
Eric Laurent10351942014-05-08 18:49:52 -07009695 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009696 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009697 if (status == INVALID_OPERATION) {
9698 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009699 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009700 }
9701 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009702 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009703 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9704 if (mInput->stream->getAudioProperties(&config) == OK &&
9705 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9706 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009707 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009708 status = NO_ERROR;
9709 }
Eric Laurent81784c32012-11-19 14:55:58 -08009710 }
Eric Laurent10351942014-05-08 18:49:52 -07009711 if (status == NO_ERROR) {
9712 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009713 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009714 }
9715 }
Eric Laurent81784c32012-11-19 14:55:58 -08009716 }
Eric Laurent10351942014-05-08 18:49:52 -07009717
Eric Laurent81784c32012-11-19 14:55:58 -08009718 return reconfig;
9719}
9720
Andy Hungee58e4a2023-07-07 13:47:37 -07009721String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009722{
Andy Hung972bec12023-08-31 16:13:39 -07009723 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009724 if (initCheck() == NO_ERROR) {
9725 String8 out_s8;
9726 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9727 return out_s8;
9728 }
Eric Laurent81784c32012-11-19 14:55:58 -08009729 }
Andy Hung920f6572022-10-06 12:09:49 -07009730 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009731}
9732
Andy Hungab65b182023-09-06 19:41:47 -07009733void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009734 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009735 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009736 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009737 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009738 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009739 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009740 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9741 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009742 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009743 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009744 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009745 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009746 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009747 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009748 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009749 break;
9750 }
Andy Hungab65b182023-09-06 19:41:47 -07009751 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009752}
9753
Andy Hungee58e4a2023-07-07 13:47:37 -07009754void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009755{
Dean Wheatley6c009512023-10-23 09:34:14 +11009756 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9757 mSampleRate = audioConfig.sample_rate;
9758 mChannelMask = audioConfig.channel_mask;
9759 if (!audio_is_input_channel(mChannelMask)) {
9760 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9761 }
9762
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009763 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009764
9765 // Get actual HAL format.
9766 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9767 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9768 // Get format from the shim, which will be different than the HAL format
9769 // if recording compressed audio from IEC61937 wrapped sources.
9770 mFormat = audioConfig.format;
9771 if (!audio_is_valid_format(mFormat)) {
9772 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9773 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009774 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009775 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9776 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009777 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009778 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009779 ALOGI("HAL format %#x is not linear pcm", mFormat);
9780 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009781 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009782 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9783 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009784 result = mInput->stream->getBufferSize(&mBufferSize);
9785 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009786 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009787 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9788 "mBufferSize=%zu, mFrameCount=%zu",
9789 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009790
Eric Laurentec376dc2021-04-08 20:41:22 +02009791 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9792 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009793 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009794
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009795 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9796 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009797
9798 audio_input_flags_t flags = mInput->flags;
9799 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9800 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009801 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009802 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9803 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9804 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9805 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9806 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9807 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009808}
9809
Andy Hungee58e4a2023-07-07 13:47:37 -07009810uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009811{
Andy Hung972bec12023-08-31 16:13:39 -07009812 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009813 uint32_t result;
9814 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9815 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009816 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009817 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009818}
9819
Andy Hungee58e4a2023-07-07 13:47:37 -07009820KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009821{
Glenn Kastend848eb42016-03-08 13:42:11 -08009822 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009823 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009824 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009825 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009826 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009827 if (ids.indexOfKey(sessionId) < 0) {
9828 ids.add(sessionId, true);
9829 }
9830 }
9831 return ids;
9832}
9833
Andy Hungee58e4a2023-07-07 13:47:37 -07009834AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009835{
Andy Hung972bec12023-08-31 16:13:39 -07009836 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009837 AudioStreamIn *input = mInput;
9838 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009839 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009840 return input;
9841}
9842
Andy Hungc5007f82023-08-29 14:26:09 -07009843// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009844sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009845{
9846 if (mInput == NULL) {
9847 return NULL;
9848 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009849 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009850}
9851
Andy Hungee58e4a2023-07-07 13:47:37 -07009852status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009853{
Eric Laurent81784c32012-11-19 14:55:58 -08009854 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009855 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009856 chain->setInBuffer(NULL);
9857 chain->setOutBuffer(NULL);
9858
9859 checkSuspendOnAddEffectChain_l(chain);
9860
Eric Laurent1b928682014-10-02 19:41:47 -07009861 // make sure enabled pre processing effects state is communicated to the HAL as we
9862 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009863 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009864
Eric Laurent81784c32012-11-19 14:55:58 -08009865 mEffectChains.add(chain);
9866
9867 return NO_ERROR;
9868}
9869
Andy Hungee58e4a2023-07-07 13:47:37 -07009870size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009871{
9872 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009873
9874 for (size_t i = 0; i < mEffectChains.size(); i++) {
9875 if (chain == mEffectChains[i]) {
9876 mEffectChains.removeAt(i);
9877 break;
9878 }
Eric Laurent81784c32012-11-19 14:55:58 -08009879 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009880 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009881}
9882
Andy Hungee58e4a2023-07-07 13:47:37 -07009883status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009884 audio_patch_handle_t *handle)
9885{
9886 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009887
9888 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009889 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009890 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009891 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009892 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009893 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009894 }
9895
Eric Laurentd8365c52017-07-16 15:27:05 -07009896 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009897
9898 // store new source and send to effects
9899 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9900 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009901 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009902 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009903 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009904 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009905
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009906 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009907 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9908 status = hwDevice->createAudioPatch(patch->num_sources,
9909 patch->sources,
9910 patch->num_sinks,
9911 patch->sinks,
9912 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009913 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009914 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9915 patch->sinks[0].ext.mix.usecase.source,
9916 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009917 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009918 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009919
jiabinc52b1ff2019-10-31 17:20:42 -07009920 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009921 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009922 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009923 }
Eric Laurent296fb132015-05-01 11:38:42 -07009924
Andy Hungc2b11cb2020-04-22 09:04:01 -07009925 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009926 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009927 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009928 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009929 // also dispatch to active AudioRecords
9930 for (const auto &track : mActiveTracks) {
9931 track->logEndInterval();
9932 track->logBeginInterval(pathSourcesAsString);
9933 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009934 // Force meteadata update after a route change
9935 mActiveTracks.setHasChanged();
9936
Eric Laurent1c333e22014-05-20 10:48:17 -07009937 return status;
9938}
9939
Andy Hungee58e4a2023-07-07 13:47:37 -07009940status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009941{
9942 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009943
jiabinc52b1ff2019-10-31 17:20:42 -07009944 mPatch = audio_patch{};
9945 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009946
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009947 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009948 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9949 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009950 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009951 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009952 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009953 // Force meteadata update after a route change
9954 mActiveTracks.setHasChanged();
9955
Eric Laurent1c333e22014-05-20 10:48:17 -07009956 return status;
9957}
9958
Andy Hungee58e4a2023-07-07 13:47:37 -07009959void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009960{
Andy Hung972bec12023-08-31 16:13:39 -07009961 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009962 mOutDevices = outDevices;
9963 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9964 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009965 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009966 }
9967}
9968
Andy Hungee58e4a2023-07-07 13:47:37 -07009969int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009970{
9971 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009972 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009973 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009974 int32_t oldestFront = mRsmpInRear;
9975 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009976 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009977 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009978 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009979 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009980 if (filled > maxFilled) {
9981 oldestFront = front;
9982 maxFilled = filled;
9983 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009984 }
Andy Hung920f6572022-10-06 12:09:49 -07009985 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009986 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9987 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009988 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009989}
9990
Andy Hungee58e4a2023-07-07 13:47:37 -07009991void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009992{
9993 if (offset == 0) {
9994 return;
9995 }
9996 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009997 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009998 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009999 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010000 }
10001}
10002
Andy Hungee58e4a2023-07-07 13:47:37 -070010003void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010004{
10005 // This is the formula for calculating the temporary buffer size.
10006 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10007 // 1 full output buffer, regardless of the alignment of the available input.
10008 // The value is somewhat arbitrary, and could probably be even larger.
10009 // A larger value should allow more old data to be read after a track calls start(),
10010 // without increasing latency.
10011 //
10012 // Note this is independent of the maximum downsampling ratio permitted for capture.
10013 size_t minRsmpInFrames = mFrameCount * 7;
10014
10015 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10016 // capture history available to another client using the same session ID:
10017 // dimension the resampler input buffer accordingly.
10018
10019 // Get oldest client read position: getOldestFront_l() must be called before altering
10020 // mRsmpInRear, or mRsmpInFrames
10021 int32_t previousFront = getOldestFront_l();
10022 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10023 int32_t previousRear = mRsmpInRear;
10024 mRsmpInRear = 0;
10025
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010026 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010027 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010028 "resizeInputBuffer_l() called with invalid max shared history %d",
10029 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010030 if (maxSharedAudioHistoryMs != 0) {
10031 // resizeInputBuffer_l should never be called with a non zero shared history if the
10032 // buffer was not already allocated
10033 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10034 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10035 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10036 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010037 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010038 return;
10039 }
10040 mRsmpInFrames = rsmpInFrames;
10041 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010042 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010043 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10044 // initialized
10045 if (mRsmpInFrames < minRsmpInFrames) {
10046 mRsmpInFrames = minRsmpInFrames;
10047 }
10048 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10049
10050 // TODO optimize audio capture buffer sizes ...
10051 // Here we calculate the size of the sliding buffer used as a source
10052 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10053 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10054 // be better to have it derived from the pipe depth in the long term.
10055 // The current value is higher than necessary. However it should not add to latency.
10056
10057 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10058 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10059
10060 void *rsmpInBuffer;
10061 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10062 // if posix_memalign fails, will segv here.
10063 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10064
10065 // Copy audio history if any from old buffer before freeing it
10066 if (previousRear != 0) {
10067 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10068 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10069
10070 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10071 previousFront &= previousRsmpInFramesP2 - 1;
10072 size_t part1 = previousRsmpInFramesP2 - previousFront;
10073 if (part1 > (size_t) unread) {
10074 part1 = unread;
10075 }
10076 if (part1 != 0) {
10077 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10078 part1 * mFrameSize);
10079 mRsmpInRear = part1;
10080 part1 = unread - part1;
10081 if (part1 != 0) {
10082 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10083 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10084 mRsmpInRear += part1;
10085 }
10086 }
10087 // Update front for all clients according to new rear
10088 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10089 } else {
10090 mRsmpInRear = 0;
10091 }
10092 free(mRsmpInBuffer);
10093 mRsmpInBuffer = rsmpInBuffer;
10094}
10095
Andy Hungee58e4a2023-07-07 13:47:37 -070010096void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010097{
Andy Hung972bec12023-08-31 16:13:39 -070010098 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010099 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010100 if (record->getSource()) {
10101 mSource = record->getSource();
10102 }
Eric Laurent83b88082014-06-20 18:31:16 -070010103}
10104
Andy Hungee58e4a2023-07-07 13:47:37 -070010105void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010106{
Andy Hung972bec12023-08-31 16:13:39 -070010107 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010108 if (mSource == record->getSource()) {
10109 mSource = mInput;
10110 }
Eric Laurent83b88082014-06-20 18:31:16 -070010111 destroyTrack_l(record);
10112}
10113
Andy Hungee58e4a2023-07-07 13:47:37 -070010114void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010115{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010116 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010117 config->role = AUDIO_PORT_ROLE_SINK;
10118 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10119 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010120 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10121 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10122 config->flags.input = mInput->flags;
10123 }
Eric Laurent83b88082014-06-20 18:31:16 -070010124}
Eric Laurent1c333e22014-05-20 10:48:17 -070010125
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126// ----------------------------------------------------------------------------
10127// Mmap
10128// ----------------------------------------------------------------------------
10129
Andy Hung7aa7d102023-07-07 15:58:48 -070010130// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10131// MmapPlaybackThread or MmapCaptureThread instance.
10132class MmapThreadHandle : public MmapStreamInterface {
10133public:
10134 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10135 ~MmapThreadHandle() override;
10136
10137 // MmapStreamInterface virtuals
10138 status_t createMmapBuffer(int32_t minSizeFrames,
10139 struct audio_mmap_buffer_info* info) final;
10140 status_t getMmapPosition(struct audio_mmap_position* position) final;
10141 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10142 status_t start(const AudioClient& client,
10143 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10144 status_t stop(audio_port_handle_t handle) final;
10145 status_t standby() final;
10146 status_t reportData(const void* buffer, size_t frameCount) final;
10147private:
10148 const sp<IAfMmapThread> mThread;
10149};
10150
10151/* static */
10152sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10153 const sp<IAfMmapThread>& mmapThread) {
10154 return sp<MmapThreadHandle>::make(mmapThread);
10155}
10156
10157MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 : mThread(thread)
10159{
Phil Burk9fabbf82017-08-03 12:02:00 -070010160 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161}
10162
Andy Hung7aa7d102023-07-07 15:58:48 -070010163// MmapStreamInterface could be directly implemented by MmapThread excepting this
10164// special handling on adapter dtor.
10165MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010166{
Phil Burk9fabbf82017-08-03 12:02:00 -070010167 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168}
10169
Andy Hung7aa7d102023-07-07 15:58:48 -070010170status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010171 struct audio_mmap_buffer_info *info)
10172{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010173 return mThread->createMmapBuffer(minSizeFrames, info);
10174}
10175
Andy Hung7aa7d102023-07-07 15:58:48 -070010176status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010177{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 return mThread->getMmapPosition(position);
10179}
10180
Andy Hung7aa7d102023-07-07 15:58:48 -070010181status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010182 int64_t *timeNanos) {
10183 return mThread->getExternalPosition(position, timeNanos);
10184}
10185
Andy Hung7aa7d102023-07-07 15:58:48 -070010186status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010187 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010188{
jiabind1f1cb62020-03-24 11:57:57 -070010189 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010190}
10191
Andy Hung7aa7d102023-07-07 15:58:48 -070010192status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010193{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010194 return mThread->stop(handle);
10195}
10196
Andy Hung7aa7d102023-07-07 15:58:48 -070010197status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010198{
Eric Laurent18b57012017-02-13 16:23:52 -080010199 return mThread->standby();
10200}
10201
Andy Hung7aa7d102023-07-07 15:58:48 -070010202status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10203{
jiabinfc791ee2023-02-15 19:43:40 +000010204 return mThread->reportData(buffer, frameCount);
10205}
10206
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207
Andy Hungee58e4a2023-07-07 13:47:37 -070010208MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010209 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010210 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010211 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010212 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010213 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010214 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010215 mActiveTracks(&this->mLocalLog),
10216 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10217 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010218{
Eric Laurent18b57012017-02-13 16:23:52 -080010219 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010220 readHalParameters_l();
10221}
10222
Andy Hungee58e4a2023-07-07 13:47:37 -070010223void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010224{
10225 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10226}
10227
Andy Hungee58e4a2023-07-07 13:47:37 -070010228void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229{
Andy Hung8d31fd22023-06-26 19:20:57 -070010230 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010231 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010232 {
Andy Hung972bec12023-08-31 16:13:39 -070010233 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010234 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010235 activeTracks.add(t);
10236 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010237 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010238 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010239 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010240 stop(t->portId());
10241 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010242 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010243 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010244 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010246 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010247 }
10248}
10249
10250
Andy Hung8d672e02023-09-15 18:19:28 -070010251void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010252 audio_stream_type_t streamType __unused,
10253 audio_session_t sessionId,
10254 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010255 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010256 audio_port_handle_t portId)
10257{
10258 mAttr = *attr;
10259 mSessionId = sessionId;
10260 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010261 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010262 mPortId = portId;
10263}
10264
Andy Hungee58e4a2023-07-07 13:47:37 -070010265status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266 struct audio_mmap_buffer_info *info)
10267{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010268 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 if (mHalStream == 0) {
10270 return NO_INIT;
10271 }
Eric Laurent18b57012017-02-13 16:23:52 -080010272 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010273 return mHalStream->createMmapBuffer(minSizeFrames, info);
10274}
10275
Andy Hungee58e4a2023-07-07 13:47:37 -070010276status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010277{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010278 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010279 if (mHalStream == 0) {
10280 return NO_INIT;
10281 }
10282 return mHalStream->getMmapPosition(position);
10283}
10284
Andy Hungee58e4a2023-07-07 13:47:37 -070010285status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010286{
Eric Laurentdda206a2022-07-08 17:28:35 +020010287 // The HAL must receive track metadata before starting the stream
10288 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010289 status_t ret = mHalStream->start();
10290 if (ret != NO_ERROR) {
10291 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10292 return ret;
10293 }
Andy Hungcf10d742020-04-28 15:38:24 -070010294 if (mStandby) {
10295 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010296 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010297 mStandby = false;
10298 }
Eric Laurent331679c2018-04-16 17:03:16 -070010299 return NO_ERROR;
10300}
10301
Andy Hungee58e4a2023-07-07 13:47:37 -070010302status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010303 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010304 audio_port_handle_t *handle)
10305{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010306 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010307 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010308 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010309 if (mHalStream == 0) {
10310 return NO_INIT;
10311 }
10312
10313 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314
Eric Laurentdda206a2022-07-08 17:28:35 +020010315 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010316 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010317 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010318 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010319 }
10320
10321 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10322
10323 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010324 AttributionSourceState adjAttributionSource;
10325 if (!com::android::media::audio::audioserver_permissions()) {
10326 adjAttributionSource = afutils::checkAttributionSourcePackage(
10327 client.attributionSource);
10328 } else {
10329 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10330 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10331 client.attributionSource,
10332 mAfThreadCallback->getPermissionProvider()
10333 );
10334 if (!validatedRes.has_value()) {
10335 ALOGE("MMAP client package validation fail: %s",
10336 validatedRes.error().toString8().c_str());
10337 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10338 }
10339 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10340 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010341
Andy Hung3f49ebb2023-09-19 14:48:41 -070010342 const auto localSessionId = mSessionId;
10343 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010344 if (isOutput()) {
10345 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10346 config.sample_rate = mSampleRate;
10347 config.channel_mask = mChannelMask;
10348 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010349 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010350 audio_output_flags_t flags =
10351 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010352 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010353 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010354 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010355 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010356 mutex().unlock();
10357 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10358 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010359 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010360 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010361 &config,
10362 flags,
10363 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010364 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010365 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010366 &isSpatialized,
Eric Laurent277a37e2024-07-29 18:37:52 +000010367 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010368 mutex().lock();
10369 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010370 ALOGD_IF(!secondaryOutputs.empty(),
10371 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010372 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010373 audio_config_base_t config;
10374 config.sample_rate = mSampleRate;
10375 config.channel_mask = mChannelMask;
10376 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010377 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010378 mutex().unlock();
10379 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010380 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010381 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010382 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010383 &config,
10384 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10385 &deviceId,
10386 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010387 mutex().lock();
10388 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010389 }
10390 // APM should not chose a different input or output stream for the same set of attributes
10391 // and audo configuration
10392 if (ret != NO_ERROR || io != mId) {
10393 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10394 __FUNCTION__, ret, io, mId);
10395 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396 }
10397
10398 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010399 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010400 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010401 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 } else {
jiabin09609032022-06-15 19:26:01 +000010403 {
10404 // Add the track record before starting input so that the silent status for the
10405 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010406 setClientSilencedState_l(portId, false /*silenced*/);
10407 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010408 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010409 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010410 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411 }
10412
10413 // abort if start is rejected by audio policy manager
10414 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010415 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010416 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010417 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010418 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010419 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010421 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422 }
Andy Hungc5007f82023-08-29 14:26:09 -070010423 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010424 } else {
10425 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426 }
jiabin09609032022-06-15 19:26:01 +000010427 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010428 return PERMISSION_DENIED;
10429 }
10430
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010431 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010432 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10433 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010434 mChannelMask, mSessionId, isOutput(),
10435 client.attributionSource,
Eric Laurent277a37e2024-07-29 18:37:52 +000010436 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010437 if (!isOutput()) {
10438 track->setSilenced_l(isClientSilenced_l(portId));
10439 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010440
Eric Laurent4eb58f12018-12-07 16:41:02 -080010441 if (isOutput()) {
10442 // force volume update when a new track is added
10443 mHalVolFloat = -1.0f;
10444 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010445 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010446 if (t->isSilenced_l()
10447 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010448 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010449 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010450 }
10451 }
10452
Eric Laurent6acd1d42017-01-04 14:23:29 -080010453 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010454 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010455 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010456 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457 chain->incTrackCnt();
10458 chain->incActiveTrackCnt();
10459 }
10460
Andy Hungc2b11cb2020-04-22 09:04:01 -070010461 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010463
10464 if (mActiveTracks.size() == 1) {
10465 ret = exitStandby_l();
10466 }
10467
Eric Laurent6acd1d42017-01-04 14:23:29 -080010468 broadcast_l();
10469
Eric Laurentdda206a2022-07-08 17:28:35 +020010470 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010471
Eric Laurentdda206a2022-07-08 17:28:35 +020010472 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010473}
10474
Andy Hungee58e4a2023-07-07 13:47:37 -070010475status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010476{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010477 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010478 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010479
10480 if (mHalStream == 0) {
10481 return NO_INIT;
10482 }
10483
Eric Laurenta54f1282017-07-01 19:39:32 -070010484 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010485 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010486 return NO_ERROR;
10487 }
10488
Andy Hung8d31fd22023-06-26 19:20:57 -070010489 sp<IAfMmapTrack> track;
10490 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 if (handle == t->portId()) {
10492 track = t;
10493 break;
10494 }
10495 }
10496 if (track == 0) {
10497 return BAD_VALUE;
10498 }
10499
10500 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010501 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010502
Andy Hungc5007f82023-08-29 14:26:09 -070010503 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010504 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010505 AudioSystem::stopOutput(track->portId());
10506 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010507 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010508 AudioSystem::stopInput(track->portId());
10509 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010510 }
Andy Hungc5007f82023-08-29 14:26:09 -070010511 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512
Andy Hung116bc262023-06-20 18:56:17 -070010513 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010514 if (chain != 0) {
10515 chain->decActiveTrackCnt();
10516 chain->decTrackCnt();
10517 }
10518
Eric Laurentdda206a2022-07-08 17:28:35 +020010519 if (mActiveTracks.isEmpty()) {
10520 mHalStream->stop();
10521 }
10522
Eric Laurent6acd1d42017-01-04 14:23:29 -080010523 broadcast_l();
10524
Eric Laurent6acd1d42017-01-04 14:23:29 -080010525 return NO_ERROR;
10526}
10527
Andy Hungee58e4a2023-07-07 13:47:37 -070010528status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010529NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010530{
10531 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010532 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010533
10534 if (mHalStream == 0) {
10535 return NO_INIT;
10536 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010537 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010538 return INVALID_OPERATION;
10539 }
10540 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010541 if (!mStandby) {
10542 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010543 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010544 mStandby = true;
10545 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010546 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010547 return NO_ERROR;
10548}
10549
Andy Hungee58e4a2023-07-07 13:47:37 -070010550status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010551 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10552 return INVALID_OPERATION;
10553}
10554
Andy Hungee58e4a2023-07-07 13:47:37 -070010555void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010556{
10557 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10558 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10559 mFormat = mHALFormat;
10560 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10561 result = mHalStream->getFrameSize(&mFrameSize);
10562 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010563 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10564 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 result = mHalStream->getBufferSize(&mBufferSize);
10566 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10567 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010568
Andy Hungcf10d742020-04-28 15:38:24 -070010569 // TODO: make a readHalParameters call?
10570 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010571 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010572 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010573 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10574 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10575 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10576 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10577 /*
10578 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10579 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10580 (int32_t)mHapticChannelMask)
10581 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10582 (int32_t)mHapticChannelCount)
10583 */
10584 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010585 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010586 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10587 (int32_t)mFrameCount) // sic - added HAL
10588 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010589}
10590
Andy Hungee58e4a2023-07-07 13:47:37 -070010591bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592{
Andy Hungab65b182023-09-06 19:41:47 -070010593 {
10594 audio_utils::unique_lock _l(mutex());
10595 checkSilentMode_l();
10596 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010597
10598 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10599
10600 while (!exitPending())
10601 {
Andy Hung116bc262023-06-20 18:56:17 -070010602 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603
Andy Hung13850be2019-03-14 11:33:09 -070010604 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010605 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010606
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 if (mSignalPending) {
10608 // A signal was raised while we were unlocked
10609 mSignalPending = false;
10610 } else {
10611 if (mConfigEvents.isEmpty()) {
10612 // we're about to wait, flush the binder command buffer
10613 IPCThreadState::self()->flushCommands();
10614
10615 if (exitPending()) {
10616 break;
10617 }
10618
Eric Laurent6acd1d42017-01-04 14:23:29 -080010619 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010620 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010621 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010622 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623
10624 checkSilentMode_l();
10625
10626 continue;
10627 }
10628 }
10629
10630 processConfigEvents_l();
10631
10632 processVolume_l();
10633
10634 checkInvalidTracks_l();
10635
Andy Hungab65b182023-09-06 19:41:47 -070010636 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010637
Kevin Rocard069c2712018-03-29 19:09:14 -070010638 updateMetadata_l();
10639
Eric Laurent6acd1d42017-01-04 14:23:29 -080010640 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010641 } // release Thread lock
10642
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010644 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010645 }
Andy Hung13850be2019-03-14 11:33:09 -070010646
10647 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010648 unlockEffectChains(effectChains);
10649 // Effect chains will be actually deleted here if they were removed from
10650 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010651 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010653 mThreadloopExecutor.process(); // process any remaining deferred actions.
10654 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010655
10656 threadLoop_exit();
10657
10658 if (!mStandby) {
10659 threadLoop_standby();
10660 mStandby = true;
10661 }
10662
Eric Laurent6acd1d42017-01-04 14:23:29 -080010663 ALOGV("Thread %p type %d exiting", this, mType);
10664 return false;
10665}
10666
Andy Hungc5007f82023-08-29 14:26:09 -070010667// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010668bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 status_t& status)
10670{
10671 AudioParameter param = AudioParameter(keyValuePair);
10672 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010673 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010674 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010675 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010676 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010677 if (sendToHal) {
10678 status = mHalStream->setParameters(keyValuePair);
10679 } else {
10680 status = NO_ERROR;
10681 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010682
10683 return false;
10684}
10685
Andy Hungee58e4a2023-07-07 13:47:37 -070010686String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010687{
Andy Hung972bec12023-08-31 16:13:39 -070010688 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010689 String8 out_s8;
10690 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10691 return out_s8;
10692 }
Andy Hung920f6572022-10-06 12:09:49 -070010693 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010694}
10695
Andy Hungab65b182023-09-06 19:41:47 -070010696void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010697 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010698 sp<AudioIoDescriptor> desc;
10699 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700 switch (event) {
10701 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010702 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010703 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010704 isInput = true;
10705 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010707 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010708 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010709 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10710 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010712 case AUDIO_INPUT_CLOSED:
10713 case AUDIO_OUTPUT_CLOSED:
10714 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010715 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010716 break;
10717 }
Andy Hungab65b182023-09-06 19:41:47 -070010718 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719}
10720
Andy Hungee58e4a2023-07-07 13:47:37 -070010721status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010723NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010724{
10725 status_t status = NO_ERROR;
10726
10727 // store new device and send to effects
10728 audio_devices_t type = AUDIO_DEVICE_NONE;
10729 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010730 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10731 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10732 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010733 if (isOutput()) {
10734 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010735 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10736 && !mAudioHwDev->supportsAudioPatches(),
10737 "Enumerated device type(%#x) must not be used "
10738 "as it does not support audio patches",
10739 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010740 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010741 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10742 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010743 }
10744 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010745 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746 } else {
10747 type = patch->sources[0].ext.device.type;
10748 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010749 numDevices = mPatch.num_sources;
10750 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010751 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010752 }
10753
10754 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010755 if (isOutput()) {
10756 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10757 } else {
10758 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10759 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010760 }
10761
jiabinc52b1ff2019-10-31 17:20:42 -070010762 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763 // store new source and send to effects
10764 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10765 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10766 for (size_t i = 0; i < mEffectChains.size(); i++) {
10767 mEffectChains[i]->setAudioSource_l(mAudioSource);
10768 }
10769 }
10770 }
10771
jiabin78b86f22024-02-22 00:39:29 +000010772 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10773 // okay to notify the client earlier before the new patch creation.
10774 if (mDeviceId != deviceId) {
10775 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10776 // The aaudioservice handle the routing changed event asynchronously. In that case,
10777 // it is safe to hold the lock here.
10778 callback->onRoutingChanged(deviceId);
10779 }
10780 }
10781
Eric Laurent6acd1d42017-01-04 14:23:29 -080010782 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010783 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10784 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010785 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010786 audio_port_config port;
10787 std::optional<audio_source_t> source;
10788 if (isOutput()) {
10789 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010791 port = patch->sources[0];
10792 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010794 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795 *handle = AUDIO_PATCH_HANDLE_NONE;
10796 }
10797
jiabinc52b1ff2019-10-31 17:20:42 -070010798 if (numDevices == 0 || mDeviceId != deviceId) {
10799 if (isOutput()) {
10800 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10801 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010802 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010803 } else {
10804 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10805 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10806 }
jiabinc52b1ff2019-10-31 17:20:42 -070010807 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010808 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010809 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010810 // Force meteadata update after a route change
10811 mActiveTracks.setHasChanged();
10812
Eric Laurent6acd1d42017-01-04 14:23:29 -080010813 return status;
10814}
10815
Andy Hungee58e4a2023-07-07 13:47:37 -070010816status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010817{
10818 status_t status = NO_ERROR;
10819
jiabinc52b1ff2019-10-31 17:20:42 -070010820 mPatch = audio_patch{};
10821 mOutDeviceTypeAddrs.clear();
10822 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823
10824 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10825 supportsAudioPatches : false;
10826
10827 if (supportsAudioPatches) {
10828 status = mHalDevice->releaseAudioPatch(handle);
10829 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010830 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010831 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010832 // Force meteadata update after a route change
10833 mActiveTracks.setHasChanged();
10834
Eric Laurent6acd1d42017-01-04 14:23:29 -080010835 return status;
10836}
10837
Andy Hungee58e4a2023-07-07 13:47:37 -070010838void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010839NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010840{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010841 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842 if (isOutput()) {
10843 config->role = AUDIO_PORT_ROLE_SOURCE;
10844 config->ext.mix.hw_module = mAudioHwDev->handle();
10845 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10846 } else {
10847 config->role = AUDIO_PORT_ROLE_SINK;
10848 config->ext.mix.hw_module = mAudioHwDev->handle();
10849 config->ext.mix.usecase.source = mAudioSource;
10850 }
10851}
10852
Andy Hungee58e4a2023-07-07 13:47:37 -070010853status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010854{
10855 audio_session_t session = chain->sessionId();
10856
10857 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10858 // Attach all tracks with same session ID to this chain.
10859 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010860 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861 if (session == track->sessionId()) {
10862 chain->incTrackCnt();
10863 chain->incActiveTrackCnt();
10864 }
10865 }
10866
10867 chain->setThread(this);
10868 chain->setInBuffer(nullptr);
10869 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010870 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010871
10872 mEffectChains.add(chain);
10873 checkSuspendOnAddEffectChain_l(chain);
10874 return NO_ERROR;
10875}
10876
Andy Hungee58e4a2023-07-07 13:47:37 -070010877size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010878{
10879 audio_session_t session = chain->sessionId();
10880
10881 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10882
10883 for (size_t i = 0; i < mEffectChains.size(); i++) {
10884 if (chain == mEffectChains[i]) {
10885 mEffectChains.removeAt(i);
10886 // detach all active tracks from the chain
10887 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010888 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010889 if (session == track->sessionId()) {
10890 chain->decActiveTrackCnt();
10891 chain->decTrackCnt();
10892 }
10893 }
10894 break;
10895 }
10896 }
10897 return mEffectChains.size();
10898}
10899
Andy Hungee58e4a2023-07-07 13:47:37 -070010900void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010901{
10902 mHalStream->standby();
10903}
10904
Andy Hungee58e4a2023-07-07 13:47:37 -070010905void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010906{
Phil Burk7dce7282017-09-27 13:51:41 -070010907 // Do not call callback->onTearDown() because it is redundant for thread exit
10908 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010909}
10910
Andy Hungee58e4a2023-07-07 13:47:37 -070010911status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010912{
10913 return BAD_VALUE;
10914}
10915
Andy Hungee58e4a2023-07-07 13:47:37 -070010916bool MmapThread::isValidSyncEvent(
10917 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010918{
10919 return false;
10920}
10921
Andy Hungee58e4a2023-07-07 13:47:37 -070010922status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923 const effect_descriptor_t *desc, audio_session_t sessionId)
10924{
10925 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010926 if (audio_is_global_session(sessionId)) {
10927 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928 desc->name, mThreadName);
10929 return BAD_VALUE;
10930 }
10931
10932 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10933 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10934 desc->name);
10935 return BAD_VALUE;
10936 }
10937 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010938 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10939 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010940 return BAD_VALUE;
10941 }
10942
10943 // Only allow effects without processing load or latency
10944 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10945 return BAD_VALUE;
10946 }
10947
Andy Hung116bc262023-06-20 18:56:17 -070010948 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010949 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10950 return BAD_VALUE;
10951 }
10952
Eric Laurent6acd1d42017-01-04 14:23:29 -080010953 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954}
10955
Andy Hungee58e4a2023-07-07 13:47:37 -070010956void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010957{
Andy Hung8d31fd22023-06-26 19:20:57 -070010958 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010960 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10961 // The aaudioservice handle the routing changed event asynchronously. In that case,
10962 // it is safe to hold the lock here.
10963 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10964 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010965 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10966 mNoCallbackWarningCount++;
10967 }
10968 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969 }
10970 }
10971}
10972
Andy Hungee58e4a2023-07-07 13:47:37 -070010973void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010974{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10976 mAttr.content_type, mAttr.usage, mAttr.source);
10977 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010978 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010979 dprintf(fd, " No active clients\n");
10980 }
10981}
10982
Andy Hungee58e4a2023-07-07 13:47:37 -070010983void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010984{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010985 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010986 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010987 dprintf(fd, " %zu Tracks\n", numtracks);
10988 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010989 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010990 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010991 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010992 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010993 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010994 result.append(prefix);
10995 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010996 }
10997 } else {
10998 dprintf(fd, "\n");
10999 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011000 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011001}
11002
Andy Hungee58e4a2023-07-07 13:47:37 -070011003/* static */
11004sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011005 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011006 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011007 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011008}
11009
11010MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011011 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011012 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011013 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011014 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011015 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011016{
11017 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11018 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011019 mMasterVolume = afThreadCallback->masterVolume_l();
11020 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent277a37e2024-07-29 18:37:52 +000011021
11022 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11023 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11024 mStreamTypes[stream].volume = 0.0f;
11025 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011026 }
Eric Laurent277a37e2024-07-29 18:37:52 +000011027 // Audio patch and call assistant volume are always max
11028 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11029 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11030 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11031 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
11032
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033 if (mAudioHwDev) {
11034 if (mAudioHwDev->canSetMasterVolume()) {
11035 mMasterVolume = 1.0;
11036 }
11037
11038 if (mAudioHwDev->canSetMasterMute()) {
11039 mMasterMute = false;
11040 }
11041 }
11042}
11043
Andy Hungee58e4a2023-07-07 13:47:37 -070011044void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045 audio_stream_type_t streamType,
11046 audio_session_t sessionId,
11047 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011048 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011049 audio_port_handle_t portId)
11050{
Andy Hung8d672e02023-09-15 18:19:28 -070011051 audio_utils::lock_guard l(mutex());
11052 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011053 mStreamType = streamType;
11054}
11055
Andy Hungee58e4a2023-07-07 13:47:37 -070011056AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011057{
Andy Hung972bec12023-08-31 16:13:39 -070011058 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 AudioStreamOut *output = mOutput;
11060 mOutput = NULL;
11061 return output;
11062}
11063
Andy Hungee58e4a2023-07-07 13:47:37 -070011064void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011065{
Andy Hung972bec12023-08-31 16:13:39 -070011066 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011067 // Don't apply master volume in SW if our HAL can do it for us.
11068 if (mAudioHwDev &&
11069 mAudioHwDev->canSetMasterVolume()) {
11070 mMasterVolume = 1.0;
11071 } else {
11072 mMasterVolume = value;
11073 }
11074}
11075
Andy Hungee58e4a2023-07-07 13:47:37 -070011076void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077{
Andy Hung972bec12023-08-31 16:13:39 -070011078 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011079 // Don't apply master mute in SW if our HAL can do it for us.
11080 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11081 mMasterMute = false;
11082 } else {
11083 mMasterMute = muted;
11084 }
11085}
11086
Andy Hungee58e4a2023-07-07 13:47:37 -070011087void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011088{
Andy Hung972bec12023-08-31 16:13:39 -070011089 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011090 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011091 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092 broadcast_l();
11093 }
11094}
11095
Andy Hungee58e4a2023-07-07 13:47:37 -070011096float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011097{
Andy Hung972bec12023-08-31 16:13:39 -070011098 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011099 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011100}
11101
Andy Hungee58e4a2023-07-07 13:47:37 -070011102void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011103{
Andy Hung972bec12023-08-31 16:13:39 -070011104 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011105 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011106 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011107 broadcast_l();
11108 }
11109}
11110
Andy Hungee58e4a2023-07-07 13:47:37 -070011111void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011112{
Andy Hung972bec12023-08-31 16:13:39 -070011113 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011114 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011115 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011116 track->invalidate();
11117 }
11118 broadcast_l();
11119 }
11120}
11121
Andy Hungee58e4a2023-07-07 13:47:37 -070011122void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011123{
Andy Hung972bec12023-08-31 16:13:39 -070011124 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011125 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011126 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011127 if (portIds.find(track->portId()) != portIds.end()) {
11128 track->invalidate();
11129 trackMatch = true;
11130 portIds.erase(track->portId());
11131 }
11132 if (portIds.empty()) {
11133 break;
11134 }
11135 }
11136 if (trackMatch) {
11137 broadcast_l();
11138 }
11139}
11140
Andy Hungee58e4a2023-07-07 13:47:37 -070011141void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011142NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011143{
Eric Laurent277a37e2024-07-29 18:37:52 +000011144 float volume;
11145
11146 if (mMasterMute || streamMuted_l()) {
11147 volume = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011148 } else {
Eric Laurent277a37e2024-07-29 18:37:52 +000011149 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011150 }
Eric Laurent277a37e2024-07-29 18:37:52 +000011151
Eric Laurent6acd1d42017-01-04 14:23:29 -080011152 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011153 // Convert volumes from float to 8.24
11154 uint32_t vol = (uint32_t)(volume * (1 << 24));
11155
11156 // Delegate volume control to effect in track effect chain if needed
11157 // only one effect chain can be present on DirectOutputThread, so if
11158 // there is one, the track is connected to it
11159 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011160 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011161 volume = (float)vol / (1 << 24);
11162 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011163 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011164 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11165 mHalVolFloat = volume; // HW volume control worked, so update value.
11166 mNoCallbackWarningCount = 0;
11167 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011168 sp<MmapStreamCallback> callback = mCallback.promote();
11169 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011170 mHalVolFloat = volume; // SW volume control worked, so update value.
11171 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011172 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011173 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011174 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011175 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011176 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11177 ALOGW("Could not set MMAP stream volume: no volume callback!");
11178 mNoCallbackWarningCount++;
11179 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011180 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011181 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011182 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011183 track->setMetadataHasChanged();
Eric Laurent277a37e2024-07-29 18:37:52 +000011184 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11185 /*muteState=*/{mMasterMute,
11186 streamVolume_l() == 0.f,
11187 streamMuted_l(),
11188 // TODO(b/241533526): adjust logic to include mute from AppOps
11189 false /*muteFromPlaybackRestricted*/,
11190 false /*muteFromClientVolume*/,
11191 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011192 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011193 }
11194}
11195
Andy Hungee58e4a2023-07-07 13:47:37 -070011196ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011197{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011198 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011199 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011200 }
11201 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011202 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011203 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011204 playback_track_metadata_v7_t trackMetadata;
11205 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011206 .usage = track->attributes().usage,
11207 .content_type = track->attributes().content_type,
11208 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011209 };
11210 trackMetadata.channel_mask = track->channelMask(),
11211 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11212 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011213 }
11214 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011215
11216 MetadataUpdate change;
11217 change.playbackMetadataUpdate = metadata.tracks;
11218 return change;
11219};
Kevin Rocard069c2712018-03-29 19:09:14 -070011220
Andy Hungee58e4a2023-07-07 13:47:37 -070011221void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011222{
11223 if (!mMasterMute) {
11224 char value[PROPERTY_VALUE_MAX];
11225 if (property_get("ro.audio.silent", value, "0") > 0) {
11226 char *endptr;
11227 unsigned long ul = strtoul(value, &endptr, 0);
11228 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011229 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011230 // The setprop command will not allow a property to be changed after
11231 // the first time it is set, so we don't have to worry about un-muting.
11232 setMasterMute_l(true);
11233 }
11234 }
11235 }
11236}
11237
Andy Hungee58e4a2023-07-07 13:47:37 -070011238void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011239{
11240 MmapThread::toAudioPortConfig(config);
11241 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11242 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11243 config->flags.output = mOutput->flags;
11244 }
11245}
11246
Andy Hungee58e4a2023-07-07 13:47:37 -070011247status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011248 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011249{
11250 if (mOutput == nullptr) {
11251 return NO_INIT;
11252 }
11253 struct timespec timestamp;
11254 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11255 if (status == NO_ERROR) {
11256 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11257 }
11258 return status;
11259}
11260
Andy Hungee58e4a2023-07-07 13:47:37 -070011261status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011262 // Send to MelProcessor for sound dose measurement.
11263 auto processor = mMelProcessor.load();
11264 if (processor) {
11265 processor->process(buffer, frameCount * mFrameSize);
11266 }
11267
jiabinfc791ee2023-02-15 19:43:40 +000011268 return NO_ERROR;
11269}
11270
Andy Hungc5007f82023-08-29 14:26:09 -070011271// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011272void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011273 const sp<audio_utils::MelProcessor>& processor)
11274{
11275 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011276 mMelProcessor.store(processor);
11277 if (processor) {
11278 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011279 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011280
11281 // no need to update output format for MMapPlaybackThread since it is
11282 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011283}
11284
Andy Hungc5007f82023-08-29 14:26:09 -070011285// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011286void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011287{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011288 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11289 auto melProcessor = mMelProcessor.load();
11290 if (melProcessor != nullptr) {
11291 melProcessor->pause();
11292 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011293}
11294
Andy Hungee58e4a2023-07-07 13:47:37 -070011295void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011296{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011297 MmapThread::dumpInternals_l(fd, args);
Eric Laurent277a37e2024-07-29 18:37:52 +000011298
11299 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
11300 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011301 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11302}
11303
Andy Hungee58e4a2023-07-07 13:47:37 -070011304/* static */
11305sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011306 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011307 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011308 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011309}
11310
11311MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011312 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011313 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011314 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011315 mInput(input)
11316{
11317 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11318 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11319}
11320
Andy Hungee58e4a2023-07-07 13:47:37 -070011321status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011322{
Phil Burkf054fc32018-12-06 09:45:59 -080011323 {
11324 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011325 if (mInput != nullptr && mInput->stream != nullptr) {
11326 mInput->stream->setGain(1.0f);
11327 }
11328 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011329 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011330}
11331
Andy Hungee58e4a2023-07-07 13:47:37 -070011332AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011333{
Andy Hung972bec12023-08-31 16:13:39 -070011334 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011335 AudioStreamIn *input = mInput;
11336 mInput = NULL;
11337 return input;
11338}
Kevin Rocard069c2712018-03-29 19:09:14 -070011339
Andy Hungee58e4a2023-07-07 13:47:37 -070011340void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011341{
11342 bool changed = false;
11343 bool silenced = false;
11344
11345 sp<MmapStreamCallback> callback = mCallback.promote();
11346 if (callback == 0) {
11347 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11348 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11349 mNoCallbackWarningCount++;
11350 }
11351 }
11352
11353 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11354 // track is silenced and unmute otherwise
11355 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11356 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11357 changed = true;
11358 silenced = mActiveTracks[i]->isSilenced_l();
11359 }
11360 }
11361
11362 if (changed) {
11363 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11364 }
11365}
11366
Andy Hungee58e4a2023-07-07 13:47:37 -070011367ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011368{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011369 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011370 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011371 }
11372 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011373 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011374 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011375 record_track_metadata_v7_t trackMetadata;
11376 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011377 .source = track->attributes().source,
11378 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011379 };
11380 trackMetadata.channel_mask = track->channelMask(),
11381 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11382 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011383 }
11384 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011385 MetadataUpdate change;
11386 change.recordMetadataUpdate = metadata.tracks;
11387 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011388}
11389
Andy Hungee58e4a2023-07-07 13:47:37 -070011390void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011391{
Andy Hung972bec12023-08-31 16:13:39 -070011392 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011393 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011394 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011395 mActiveTracks[i]->setSilenced_l(silenced);
11396 broadcast_l();
11397 }
11398 }
jiabin09609032022-06-15 19:26:01 +000011399 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011400}
11401
Andy Hungee58e4a2023-07-07 13:47:37 -070011402void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011403{
11404 MmapThread::toAudioPortConfig(config);
11405 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11406 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11407 config->flags.input = mInput->flags;
11408 }
11409}
11410
Andy Hungee58e4a2023-07-07 13:47:37 -070011411status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011412 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011413{
11414 if (mInput == nullptr) {
11415 return NO_INIT;
11416 }
11417 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11418}
11419
jiabinc658e452022-10-21 20:52:21 +000011420// ----------------------------------------------------------------------------
11421
Andy Hungee58e4a2023-07-07 13:47:37 -070011422/* static */
11423sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011424 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011425 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011426 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011427}
11428
Andy Hung583043b2023-07-17 17:05:00 -070011429BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011430 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011431 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011432
Andy Hungee58e4a2023-07-07 13:47:37 -070011433PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011434 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011435 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11436 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011437 float volumeLeft = 1.0f;
11438 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011439 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11440 bitPerfectTrack != nullptr) {
11441 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011442 mAudioMixer->setParameter(
11443 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11444 mAudioMixer->setParameter(
11445 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11446 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011447 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011448 mIsBitPerfect = true;
11449 } else {
11450 mIsBitPerfect = false;
11451 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11452 // active.
11453 for (const auto& track : mActiveTracks) {
11454 const int trackId = track->id();
11455 mAudioMixer->setParameter(
11456 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11457 }
11458 }
jiabin76d94692022-12-15 21:51:21 +000011459 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11460 mVolumeLeft = volumeLeft;
11461 mVolumeRight = volumeRight;
11462 setVolumeForOutput_l(volumeLeft, volumeRight);
11463 }
jiabinc658e452022-10-21 20:52:21 +000011464 return result;
11465}
11466
Andy Hungee58e4a2023-07-07 13:47:37 -070011467void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011468 MixerThread::threadLoop_mix();
11469 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11470}
11471
jiabin220eea12024-05-17 17:55:20 +000011472void BitPerfectThread::setTracksInternalMute(
11473 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11474 for (auto& track : mTracks) {
11475 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11476 track->setInternalMute(it->second);
11477 tracksInternalMute->erase(it);
11478 }
11479 }
11480}
11481
11482sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11483 if (com::android::media::audioserver::
11484 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11485 sp<IAfTrack> bitPerfectTrack = nullptr;
11486 bool allOtherTracksMuted = true;
11487 // Return the bit perfect track if all other tracks are muted
11488 for (const auto& track : mActiveTracks) {
11489 if (track->isBitPerfect()) {
11490 bitPerfectTrack = track;
11491 } else if (track->getFinalVolume() != 0.f) {
11492 allOtherTracksMuted = false;
11493 if (bitPerfectTrack != nullptr) {
11494 break;
11495 }
11496 }
11497 }
11498 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11499 } else {
11500 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11501 return mActiveTracks[0];
11502 }
11503 }
11504 return nullptr;
11505}
11506
Glenn Kasten63238ef2015-03-02 15:50:29 -080011507} // namespace android