blob: 76e47124d941215a05e69110f8ace57e24f2f23d [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung25a80ac2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
jiabin220eea12024-05-17 17:55:20 +000036#include <com_android_media_audioserver.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070037#ifdef DEBUG_CPU_USAGE
38#include <audio_utils/Statistics.h>
39#include <cpustats/ThreadCpuUsage.h>
40#endif
41#include <audio_utils/channels.h>
42#include <audio_utils/format.h>
43#include <audio_utils/minifloat.h>
44#include <audio_utils/mono_blend.h>
45#include <audio_utils/primitives.h>
46#include <audio_utils/safe_math.h>
47#include <audiomanager/AudioManager.h>
48#include <binder/IPCThreadState.h>
49#include <binder/IServiceManager.h>
50#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010051#include <com_android_media_audio.h>
Andy Hung6b137d12024-08-27 22:35:17 +000052#include <com_android_media_audioserver.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070053#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080054#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070055#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070056#include <media/AudioContainers.h>
57#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070058#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070059#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070060#ifdef ADD_BATTERY_DATA
61#include <media/IMediaPlayerService.h>
62#include <media/IMediaDeathNotifier.h>
63#endif
64#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080065#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070066#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070067#include <media/audiohal/EffectsFactoryHalInterface.h>
68#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070069#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070#include <media/nbaio/AudioStreamOutSink.h>
71#include <media/nbaio/MonoPipe.h>
72#include <media/nbaio/MonoPipeReader.h>
73#include <media/nbaio/Pipe.h>
74#include <media/nbaio/PipeReader.h>
75#include <media/nbaio/SourceAudioBufferProvider.h>
Atneya Nair5997a652024-06-14 17:24:45 -070076#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080077#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070078#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070079#include <mediautils/SchedulingPolicyService.h>
80#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070081#include <powermanager/PowerManager.h>
82#include <private/android_filesystem_config.h>
83#include <private/media/AudioTrackShared.h>
84#include <system/audio_effects/effect_aec.h>
85#include <system/audio_effects/effect_downmix.h>
86#include <system/audio_effects/effect_ns.h>
87#include <system/audio_effects/effect_spatializer.h>
88#include <utils/Log.h>
89#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080090
Andy Hung25a80ac2023-07-19 12:47:35 -070091#include <fcntl.h>
92#include <linux/futex.h>
93#include <math.h>
94#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080095#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070096#include <sstream>
97#include <string>
98#include <sys/stat.h>
99#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800100
Eric Laurent81784c32012-11-19 14:55:58 -0800101// ----------------------------------------------------------------------------
102
103// Note: the following macro is used for extremely verbose logging message. In
104// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
105// 0; but one side effect of this is to turn all LOGV's as well. Some messages
106// are so verbose that we want to suppress them even when we have ALOG_ASSERT
107// turned on. Do not uncomment the #def below unless you really know what you
108// are doing and want to see all of the extremely verbose messages.
109//#define VERY_VERY_VERBOSE_LOGGING
110#ifdef VERY_VERY_VERBOSE_LOGGING
111#define ALOGVV ALOGV
112#else
113#define ALOGVV(a...) do { } while(0)
114#endif
115
Andy Hung6770c6f2015-04-07 13:43:36 -0700116// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700117#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700118
Andy Hung6770c6f2015-04-07 13:43:36 -0700119template <typename T>
120static inline T min(const T& a, const T& b)
121{
122 return a < b ? a : b;
123}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700124
Atneya Nair5997a652024-06-14 17:24:45 -0700125using com::android::media::permission::ValidatedAttributionSourceState;
Andy Hung6b137d12024-08-27 22:35:17 +0000126namespace audioserver_flags = com::android::media::audioserver;
Atneya Nair5997a652024-06-14 17:24:45 -0700127
Eric Laurent81784c32012-11-19 14:55:58 -0800128namespace android {
129
Andy Hungee58e4a2023-07-07 13:47:37 -0700130using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000132using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700133
Andy Hung25a80ac2023-07-19 12:47:35 -0700134// Keep in sync with java definition in media/java/android/media/AudioRecord.java
135static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
136
Eric Laurent81784c32012-11-19 14:55:58 -0800137// retry counts for buffer fill timeout
138// 50 * ~20msecs = 1 second
139static const int8_t kMaxTrackRetries = 50;
140static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700141
Eric Laurent81784c32012-11-19 14:55:58 -0800142// allow less retry attempts on direct output thread.
143// direct outputs can be a scarce resource in audio hardware and should
144// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700145// Notes:
146// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
147// in case the data write is bursty for the AudioTrack. The application
148// should endeavor to write at least once every kMaxTrackRetriesDirectMs
149// to prevent an underrun situation. If the data is bursty, then
150// the application can also throttle the data sent to be even.
151// 2) For compressed audio data, any data present in the AudioTrack buffer
152// will be sent and reset the retry count. This delivers data as
153// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
154// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
155// of data to be available, then any remaining data is delivered.
156// This is required to ensure the last bit of data is delivered before underrun.
157//
158// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
159// or the size of the HAL period for proportional / linear PCM tracks.
160static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800161
162// don't warn about blocked writes or record buffer overflows more often than this
163static const nsecs_t kWarningThrottleNs = seconds(5);
164
165// RecordThread loop sleep time upon application overrun or audio HAL read error
166static const int kRecordThreadSleepUs = 5000;
167
Eric Laurent10351942014-05-08 18:49:52 -0700168// maximum time to wait in sendConfigEvent_l() for a status to be received
169static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent3fddffe2024-07-31 14:18:34 +0000170// longer timeout for create audio patch to account for specific scenarii
171// with Bluetooth devices
172static const nsecs_t kCreatePatchEventTimeoutNs = seconds(4);
Eric Laurent81784c32012-11-19 14:55:58 -0800173
174// minimum sleep time for the mixer thread loop when tracks are active but in underrun
175static const uint32_t kMinThreadSleepTimeUs = 5000;
176// maximum divider applied to the active sleep time in the mixer thread loop
177static const uint32_t kMaxThreadSleepTimeShift = 2;
178
Andy Hung09a50072014-02-27 14:30:47 -0800179// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700180// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800181static const uint32_t kMinNormalSinkBufferSizeMs = 20;
182// maximum normal sink buffer size
183static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800184
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700185// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
186// FIXME This should be based on experimentally observed scheduling jitter
187static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
188
Eric Laurent972a1732013-09-04 09:42:59 -0700189// Offloaded output thread standby delay: allows track transition without going to standby
190static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
191
Eric Laurent51716182016-02-29 18:00:56 -0800192// Direct output thread minimum sleep time in idle or active(underrun) state
193static const nsecs_t kDirectMinSleepTimeUs = 10000;
194
Brian Lindahl65e90012022-07-27 18:01:07 +0200195// Minimum amount of time between checking to see if the timestamp is advancing
196// for underrun detection. If we check too frequently, we may not detect a
197// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800198static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200199
Glenn Kasten1b291842016-07-18 14:55:21 -0700200// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
201// balance between power consumption and latency, and allows threads to be scheduled reliably
202// by the CFS scheduler.
203// FIXME Express other hardcoded references to 20ms with references to this constant and move
204// it appropriately.
205#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800206
Eric Laurent81784c32012-11-19 14:55:58 -0800207// Whether to use fast mixer
208static const enum {
209 FastMixer_Never, // never initialize or use: for debugging only
210 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
211 // normal mixer multiplier is 1
212 FastMixer_Static, // initialize if needed, then use all the time if initialized,
213 // multiplier is calculated based on min & max normal mixer buffer size
214 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
215 // multiplier is calculated based on min & max normal mixer buffer size
216 // FIXME for FastMixer_Dynamic:
217 // Supporting this option will require fixing HALs that can't handle large writes.
218 // For example, one HAL implementation returns an error from a large write,
219 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
220 // We could either fix the HAL implementations, or provide a wrapper that breaks
221 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
222} kUseFastMixer = FastMixer_Static;
223
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700224// Whether to use fast capture
225static const enum {
226 FastCapture_Never, // never initialize or use: for debugging only
227 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
228 FastCapture_Static, // initialize if needed, then use all the time if initialized
229} kUseFastCapture = FastCapture_Static;
230
Eric Laurent81784c32012-11-19 14:55:58 -0800231// Priorities for requestPriority
232static const int kPriorityAudioApp = 2;
233static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700234static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000235// Request real-time priority for PlaybackThread in ARC
236static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800237
Glenn Kastenea38ee72016-04-18 11:08:01 -0700238// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
239// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
240// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700241
242// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800243static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800244
Glenn Kasten03490092014-05-27 12:30:54 -0700245// The minimum and maximum allowed values
246static const int kFastTrackMultiplierMin = 1;
247static const int kFastTrackMultiplierMax = 2;
248
249// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
250static int sFastTrackMultiplier = kFastTrackMultiplier;
251
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700252// See Thread::readOnlyHeap().
253// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
254// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
255// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700256static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700257
Andy Hung25a80ac2023-07-19 12:47:35 -0700258static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700259
260static nsecs_t getStandbyTimeInNanos() {
261 static nsecs_t standbyTimeInNanos = []() {
262 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
263 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
264 ALOGI("%s: Using %d ms as standby time", __func__, ms);
265 return milliseconds(ms);
266 }();
267 return standbyTimeInNanos;
268}
269
Andy Hung81994d62023-07-20 21:44:14 -0700270// Set kEnableExtendedChannels to true to enable greater than stereo output
271// for the MixerThread and device sink. Number of channels allowed is
272// FCC_2 <= channels <= FCC_LIMIT.
273constexpr bool kEnableExtendedChannels = true;
274
275// Returns true if channel mask is permitted for the PCM sink in the MixerThread
276/* static */
277bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
278 switch (audio_channel_mask_get_representation(channelMask)) {
279 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
280 // Haptic channel mask is only applicable for channel position mask.
281 const uint32_t channelCount = audio_channel_count_from_out_mask(
282 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
283 const uint32_t maxChannelCount = kEnableExtendedChannels
284 ? FCC_LIMIT : FCC_2;
285 if (channelCount < FCC_2 // mono is not supported at this time
286 || channelCount > maxChannelCount) {
287 return false;
288 }
289 // check that channelMask is the "canonical" one we expect for the channelCount.
290 return audio_channel_position_mask_is_out_canonical(channelMask);
291 }
292 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
293 if (kEnableExtendedChannels) {
294 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
295 if (channelCount >= FCC_2 // mono is not supported at this time
296 && channelCount <= FCC_LIMIT) {
297 return true;
298 }
299 }
300 return false;
301 default:
302 return false;
303 }
304}
305
306// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
307constexpr bool kEnableExtendedPrecision = true;
308
309// Returns true if format is permitted for the PCM sink in the MixerThread
310/* static */
311bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
312 switch (format) {
313 case AUDIO_FORMAT_PCM_16_BIT:
314 return true;
315 case AUDIO_FORMAT_PCM_FLOAT:
316 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
317 case AUDIO_FORMAT_PCM_32_BIT:
318 case AUDIO_FORMAT_PCM_8_24_BIT:
319 return kEnableExtendedPrecision;
320 default:
321 return false;
322 }
323}
324
Eric Laurent81784c32012-11-19 14:55:58 -0800325// ----------------------------------------------------------------------------
326
Andy Hung25a80ac2023-07-19 12:47:35 -0700327// formatToString() needs to be exact for MediaMetrics purposes.
328// Do not use media/TypeConverter.h toString().
329/* static */
330std::string IAfThreadBase::formatToString(audio_format_t format) {
331 std::string result;
332 FormatConverter::toString(format, result);
333 return result;
334}
335
Andy Hungb68f5eb2019-12-03 16:49:17 -0800336// TODO: move all toString helpers to audio.h
337// under #ifdef __cplusplus #endif
338static std::string patchSinksToString(const struct audio_patch *patch)
339{
340 std::stringstream ss;
341 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700342 if (i > 0) {
343 ss << "|";
344 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800345 ss << "(" << toString(patch->sinks[i].ext.device.type)
346 << ", " << patch->sinks[i].ext.device.address << ")";
347 }
348 return ss.str();
349}
350
351static std::string patchSourcesToString(const struct audio_patch *patch)
352{
353 std::stringstream ss;
354 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700355 if (i > 0) {
356 ss << "|";
357 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800358 ss << "(" << toString(patch->sources[i].ext.device.type)
359 << ", " << patch->sources[i].ext.device.address << ")";
360 }
361 return ss.str();
362}
363
Andy Hung4bd53e72022-11-17 17:21:45 -0800364static std::string toString(audio_latency_mode_t mode) {
365 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000366 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
367 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800368}
369
370// Could be made a template, but other toString overloads for std::vector are confused.
371static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
372 std::string s("{ ");
373 for (const auto& e : elements) {
374 s.append(toString(e));
375 s.append(" ");
376 }
377 s.append("}");
378 return s;
379}
380
Glenn Kasten03490092014-05-27 12:30:54 -0700381static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
382
383static void sFastTrackMultiplierInit()
384{
385 char value[PROPERTY_VALUE_MAX];
386 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
387 char *endptr;
388 unsigned long ul = strtoul(value, &endptr, 0);
389 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
390 sFastTrackMultiplier = (int) ul;
391 }
392 }
393}
394
395// ----------------------------------------------------------------------------
396
Eric Laurent81784c32012-11-19 14:55:58 -0800397#ifdef ADD_BATTERY_DATA
398// To collect the amplifier usage
399static void addBatteryData(uint32_t params) {
400 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
401 if (service == NULL) {
402 // it already logged
403 return;
404 }
405
406 service->addBatteryData(params);
407}
408#endif
409
Andy Hung3f0c9022016-01-15 17:49:46 -0800410// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
411struct {
412 // call when you acquire a partial wakelock
413 void acquire(const sp<IBinder> &wakeLockToken) {
414 pthread_mutex_lock(&mLock);
415 if (wakeLockToken.get() == nullptr) {
416 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
417 } else {
418 if (mCount == 0) {
419 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
420 }
421 ++mCount;
422 }
423 pthread_mutex_unlock(&mLock);
424 }
425
426 // call when you release a partial wakelock.
427 void release(const sp<IBinder> &wakeLockToken) {
428 if (wakeLockToken.get() == nullptr) {
429 return;
430 }
431 pthread_mutex_lock(&mLock);
432 if (--mCount < 0) {
433 ALOGE("negative wakelock count");
434 mCount = 0;
435 }
436 pthread_mutex_unlock(&mLock);
437 }
438
439 // retrieves the boottime timebase offset from monotonic.
440 int64_t getBoottimeOffset() {
441 pthread_mutex_lock(&mLock);
442 int64_t boottimeOffset = mBoottimeOffset;
443 pthread_mutex_unlock(&mLock);
444 return boottimeOffset;
445 }
446
447 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
448 // and the selected timebase.
449 // Currently only TIMEBASE_BOOTTIME is allowed.
450 //
451 // This only needs to be called upon acquiring the first partial wakelock
452 // after all other partial wakelocks are released.
453 //
454 // We do an empirical measurement of the offset rather than parsing
455 // /proc/timer_list since the latter is not a formal kernel ABI.
456 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
457 int clockbase;
458 switch (timebase) {
459 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
460 clockbase = SYSTEM_TIME_BOOTTIME;
461 break;
462 default:
463 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
464 break;
465 }
466 // try three times to get the clock offset, choose the one
467 // with the minimum gap in measurements.
468 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700469 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800470 for (int i = 0; i < tries; ++i) {
471 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
472 const nsecs_t tbase = systemTime(clockbase);
473 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
474 const nsecs_t gap = tmono2 - tmono;
475 if (i == 0 || gap < bestGap) {
476 bestGap = gap;
477 measured = tbase - ((tmono + tmono2) >> 1);
478 }
479 }
480
481 // to avoid micro-adjusting, we don't change the timebase
482 // unless it is significantly different.
483 //
484 // Assumption: It probably takes more than toleranceNs to
485 // suspend and resume the device.
486 static int64_t toleranceNs = 10000; // 10 us
487 if (llabs(*offset - measured) > toleranceNs) {
488 ALOGV("Adjusting timebase offset old: %lld new: %lld",
489 (long long)*offset, (long long)measured);
490 *offset = measured;
491 }
492 }
493
494 pthread_mutex_t mLock;
495 int32_t mCount;
496 int64_t mBoottimeOffset;
497} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800498
499// ----------------------------------------------------------------------------
500// CPU Stats
501// ----------------------------------------------------------------------------
502
503class CpuStats {
504public:
505 CpuStats();
506 void sample(const String8 &title);
507#ifdef DEBUG_CPU_USAGE
508private:
509 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700510 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800511
Andy Hung16698b82018-08-01 10:48:38 -0700512 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800513
514 int mCpuNum; // thread's current CPU number
515 int mCpukHz; // frequency of thread's current CPU in kHz
516#endif
517};
518
519CpuStats::CpuStats()
520#ifdef DEBUG_CPU_USAGE
521 : mCpuNum(-1), mCpukHz(-1)
522#endif
523{
524}
525
Glenn Kasten0f11b512014-01-31 16:18:54 -0800526void CpuStats::sample(const String8 &title
527#ifndef DEBUG_CPU_USAGE
528 __unused
529#endif
530 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800531#ifdef DEBUG_CPU_USAGE
532 // get current thread's delta CPU time in wall clock ns
533 double wcNs;
534 bool valid = mCpuUsage.sampleAndEnable(wcNs);
535
536 // record sample for wall clock statistics
537 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700538 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800539 }
540
541 // get the current CPU number
542 int cpuNum = sched_getcpu();
543
544 // get the current CPU frequency in kHz
545 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
546
547 // check if either CPU number or frequency changed
548 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
549 mCpuNum = cpuNum;
550 mCpukHz = cpukHz;
551 // ignore sample for purposes of cycles
552 valid = false;
553 }
554
555 // if no change in CPU number or frequency, then record sample for cycle statistics
556 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700557 const double cycles = wcNs * cpukHz * 0.000001;
558 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800559 }
560
Eric Tan5b13ff82018-07-27 11:20:17 -0700561 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800562 // mCpuUsage.elapsed() is expensive, so don't call it every loop
563 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700564 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800565 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700566 const double perLoop = elapsed / (double) n;
567 const double perLoop100 = perLoop * 0.01;
568 const double perLoop1k = perLoop * 0.001;
569 const double mean = mWcStats.getMean();
570 const double stddev = mWcStats.getStdDev();
571 const double minimum = mWcStats.getMin();
572 const double maximum = mWcStats.getMax();
573 const double meanCycles = mHzStats.getMean();
574 const double stddevCycles = mHzStats.getStdDev();
575 const double minCycles = mHzStats.getMin();
576 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800577 mCpuUsage.resetElapsed();
578 mWcStats.reset();
579 mHzStats.reset();
580 ALOGD("CPU usage for %s over past %.1f secs\n"
581 " (%u mixer loops at %.1f mean ms per loop):\n"
582 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
583 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
584 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000585 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800586 elapsed * .000000001, n, perLoop * .000001,
587 mean * .001,
588 stddev * .001,
589 minimum * .001,
590 maximum * .001,
591 mean / perLoop100,
592 stddev / perLoop100,
593 minimum / perLoop100,
594 maximum / perLoop100,
595 meanCycles / perLoop1k,
596 stddevCycles / perLoop1k,
597 minCycles / perLoop1k,
598 maxCycles / perLoop1k);
599
600 }
601 }
602#endif
603};
604
605// ----------------------------------------------------------------------------
606// ThreadBase
607// ----------------------------------------------------------------------------
608
Glenn Kasten97b7b752014-09-28 13:04:24 -0700609// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700610const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700611{
612 switch (type) {
613 case MIXER:
614 return "MIXER";
615 case DIRECT:
616 return "DIRECT";
617 case DUPLICATING:
618 return "DUPLICATING";
619 case RECORD:
620 return "RECORD";
621 case OFFLOAD:
622 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700623 case MMAP_PLAYBACK:
624 return "MMAP_PLAYBACK";
625 case MMAP_CAPTURE:
626 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200627 case SPATIALIZER:
628 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000629 case BIT_PERFECT:
630 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700631 default:
632 return "unknown";
633 }
634}
635
Andy Hung583043b2023-07-17 17:05:00 -0700636ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700637 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800638 : Thread(false /*canCallJava*/),
639 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700640 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700641 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
642 isOut),
643 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700644 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800645 // are set by PlaybackThread::readOutputParameters_l() or
646 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700647 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700648 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700649 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800650 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700651 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800652 mSystemReady(systemReady),
653 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800654{
Andy Hungcf10d742020-04-28 15:38:24 -0700655 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700656 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800657}
658
Andy Hungee58e4a2023-07-07 13:47:37 -0700659ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800660{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700661 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700662 mConfigEvents.clear();
663
Eric Laurent81784c32012-11-19 14:55:58 -0800664 // do not lock the mutex in destructor
665 releaseWakeLock_l();
666 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800667 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800668 binder->unlinkToDeath(mDeathRecipient);
669 }
Andy Hungd0979812019-02-21 15:51:44 -0800670
671 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800672}
673
Andy Hungee58e4a2023-07-07 13:47:37 -0700674status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700675{
676 status_t status = initCheck();
677 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800678 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700679 } else {
680 ALOGE("No working audio driver found.");
681 }
682 return status;
683}
684
Andy Hungee58e4a2023-07-07 13:47:37 -0700685void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800686{
687 ALOGV("ThreadBase::exit");
688 // do any cleanup required for exit to succeed
689 preExit();
690 {
691 // This lock prevents the following race in thread (uniprocessor for illustration):
692 // if (!exitPending()) {
693 // // context switch from here to exit()
694 // // exit() calls requestExit(), what exitPending() observes
695 // // exit() calls signal(), which is dropped since no waiters
696 // // context switch back from exit() to here
697 // mWaitWorkCV.wait(...);
698 // // now thread is hung
699 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700700 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800701 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700702 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800703 }
704 // When Thread::requestExitAndWait is made virtual and this method is renamed to
705 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700706
707 // For TimeCheck: track waiting on the thread join of getTid().
708 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
709
Eric Laurent81784c32012-11-19 14:55:58 -0800710 requestExitAndWait();
711}
712
Andy Hungee58e4a2023-07-07 13:47:37 -0700713status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800714{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000715 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700716 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800717
Eric Laurent10351942014-05-08 18:49:52 -0700718 return sendSetParameterConfigEvent_l(keyValuePairs);
719}
720
721// sendConfigEvent_l() must be called with ThreadBase::mLock held
722// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700723status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700724NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700725{
726 status_t status = NO_ERROR;
727
Eric Laurent72e3f392015-05-20 14:43:50 -0700728 if (event->mRequiresSystemReady && !mSystemReady) {
729 event->mWaitStatus = false;
730 mPendingConfigEvents.add(event);
731 return status;
732 }
Eric Laurent10351942014-05-08 18:49:52 -0700733 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700734 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700735 mWaitWorkCV.notify_one();
736 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700737 {
Andy Hungc5007f82023-08-29 14:26:09 -0700738 audio_utils::unique_lock _l(event->mutex());
Eric Laurent3fddffe2024-07-31 14:18:34 +0000739 nsecs_t timeoutNs = event->mType == CFG_EVENT_CREATE_AUDIO_PATCH ?
740 kCreatePatchEventTimeoutNs : kConfigEventTimeoutNs;
Eric Laurent10351942014-05-08 18:49:52 -0700741 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800742 if (event->mCondition.wait_for(
Eric Laurent3fddffe2024-07-31 14:18:34 +0000743 _l, std::chrono::nanoseconds(timeoutNs), getTid())
Andy Hung02ea2a02024-01-25 17:02:30 -0800744 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700745 event->mStatus = TIMED_OUT;
746 event->mWaitStatus = false;
747 }
748 }
749 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800750 }
Andy Hungc5007f82023-08-29 14:26:09 -0700751 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800752 return status;
753}
754
Andy Hungee58e4a2023-07-07 13:47:37 -0700755void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700756 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800757{
Andy Hung972bec12023-08-31 16:13:39 -0700758 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700759 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800760}
761
Andy Hungc5007f82023-08-29 14:26:09 -0700762// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700763void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700764 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800765{
Andy Hungd0979812019-02-21 15:51:44 -0800766 // The audio statistics history is exponentially weighted to forget events
767 // about five or more seconds in the past. In order to have
768 // crisper statistics for mediametrics, we reset the statistics on
769 // an IoConfigEvent, to reflect different properties for a new device.
770 mIoJitterMs.reset();
771 mLatencyMs.reset();
772 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000773 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100774 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800775
Eric Laurent09f1ed22019-04-24 17:45:17 -0700776 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700777 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800778}
779
Andy Hungee58e4a2023-07-07 13:47:37 -0700780void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700781{
Andy Hung972bec12023-08-31 16:13:39 -0700782 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800783 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700784}
785
Andy Hungc5007f82023-08-29 14:26:09 -0700786// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700787void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800788 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800789{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800790 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700791 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800792}
793
Andy Hungc5007f82023-08-29 14:26:09 -0700794// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700795status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800796{
Andy Hung2ddee192015-12-18 17:34:44 -0800797 sp<ConfigEvent> configEvent;
798 AudioParameter param(keyValuePair);
799 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700800 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800801 setMasterMono_l(value != 0);
802 if (param.size() == 1) {
803 return NO_ERROR; // should be a solo parameter - we don't pass down
804 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700805 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800806 configEvent = new SetParameterConfigEvent(param.toString());
807 } else {
808 configEvent = new SetParameterConfigEvent(keyValuePair);
809 }
Eric Laurent10351942014-05-08 18:49:52 -0700810 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700811}
812
Andy Hungee58e4a2023-07-07 13:47:37 -0700813status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700814 const struct audio_patch *patch,
815 audio_patch_handle_t *handle)
816{
Andy Hung972bec12023-08-31 16:13:39 -0700817 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700818 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
819 status_t status = sendConfigEvent_l(configEvent);
820 if (status == NO_ERROR) {
821 CreateAudioPatchConfigEventData *data =
822 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
823 *handle = data->mHandle;
824 }
825 return status;
826}
827
Andy Hungee58e4a2023-07-07 13:47:37 -0700828status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700829 const audio_patch_handle_t handle)
830{
Andy Hung972bec12023-08-31 16:13:39 -0700831 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700832 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
833 return sendConfigEvent_l(configEvent);
834}
835
Andy Hungee58e4a2023-07-07 13:47:37 -0700836status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700837 const DeviceDescriptorBaseVector& outDevices)
838{
839 if (type() != RECORD) {
840 // The update out device operation is only for record thread.
841 return INVALID_OPERATION;
842 }
Andy Hung972bec12023-08-31 16:13:39 -0700843 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700844 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
845 return sendConfigEvent_l(configEvent);
846}
847
Andy Hungee58e4a2023-07-07 13:47:37 -0700848void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200849{
850 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
851 sp<ConfigEvent> configEvent =
852 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
853 sendConfigEvent_l(configEvent);
854}
Eric Laurent1c333e22014-05-20 10:48:17 -0700855
Andy Hungee58e4a2023-07-07 13:47:37 -0700856void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200857{
Andy Hung972bec12023-08-31 16:13:39 -0700858 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200859 sendCheckOutputStageEffectsEvent_l();
860}
861
Andy Hungee58e4a2023-07-07 13:47:37 -0700862void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200863{
864 sp<ConfigEvent> configEvent =
865 (ConfigEvent *)new CheckOutputStageEffectsEvent();
866 sendConfigEvent_l(configEvent);
867}
868
Andy Hungee58e4a2023-07-07 13:47:37 -0700869void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200870{
871 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
872 sendConfigEvent_l(configEvent);
873}
874
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700875// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700876void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700877{
Eric Laurent10351942014-05-08 18:49:52 -0700878 bool configChanged = false;
879
Eric Laurent81784c32012-11-19 14:55:58 -0800880 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700881 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700882 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800883 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700884 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700885 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700886 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
887 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800888 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700889 true /*asynchronous*/);
890 if (err != 0) {
891 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700892 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700893 }
894 } break;
895 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700896 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700897 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700898 } break;
899 case CFG_EVENT_SET_PARAMETER: {
900 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
901 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
902 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700903 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000904 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700905 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700906 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700907 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700908 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700909 CreateAudioPatchConfigEventData *data =
910 (CreateAudioPatchConfigEventData *)event->mData.get();
911 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700912 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200913 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700914 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
915 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
916 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700917 } break;
918 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700919 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700920 ReleaseAudioPatchConfigEventData *data =
921 (ReleaseAudioPatchConfigEventData *)event->mData.get();
922 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700923 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200924 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700925 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
926 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
927 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
928 } break;
929 case CFG_EVENT_UPDATE_OUT_DEVICE: {
930 UpdateOutDevicesConfigEventData *data =
931 (UpdateOutDevicesConfigEventData *)event->mData.get();
932 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700933 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200934 case CFG_EVENT_RESIZE_BUFFER: {
935 ResizeBufferConfigEventData *data =
936 (ResizeBufferConfigEventData *)event->mData.get();
937 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
938 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200939
940 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
941 setCheckOutputStageEffects();
942 } break;
943
Eric Laurent68a40a82022-05-03 18:15:04 +0200944 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
945 onHalLatencyModesChanged_l();
946 } break;
947
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700948 default:
Eric Laurent10351942014-05-08 18:49:52 -0700949 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700950 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800951 }
Eric Laurent10351942014-05-08 18:49:52 -0700952 {
Andy Hung972bec12023-08-31 16:13:39 -0700953 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700954 if (event->mWaitStatus) {
955 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700956 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700957 }
958 }
959 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
960 }
961
962 if (configChanged) {
963 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800964 }
Eric Laurent81784c32012-11-19 14:55:58 -0800965}
966
Marco Nelissenb2208842014-02-07 14:00:50 -0800967String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
968 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700969 const audio_channel_representation_t representation =
970 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700971
972 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800973 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700974 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
975 if (output) {
976 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
977 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
978 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700979 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700980 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
981 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
982 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
983 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
984 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
985 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
986 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
987 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
988 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
989 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
990 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
991 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700992 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
993 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
994 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
995 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
996 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
997 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
998 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700999 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001000 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
1001 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001002 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
1003 } else {
1004 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
1005 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
1006 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1007 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1008 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1009 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1010 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1011 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1012 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1013 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1014 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1015 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001016 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1017 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1018 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001019 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001020 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1021 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001022 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1023 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1024 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1025 }
1026 const int len = s.length();
1027 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001028 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001029 s.unlockBuffer(len - 2); // remove trailing ", "
1030 }
1031 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001032 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001033 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1034 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1035 return s;
1036 default:
1037 s.appendFormat("unknown mask, representation:%d bits:%#x",
1038 representation, audio_channel_mask_get_bits(mask));
1039 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001040 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001041}
1042
Andy Hungee58e4a2023-07-07 13:47:37 -07001043void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001044NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001045{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001046 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1047 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1048
Andy Hungc5007f82023-08-29 14:26:09 -07001049 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001050 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001051 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001052 }
1053
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001054 dumpBase_l(fd, args);
1055 dumpInternals_l(fd, args);
1056 dumpTracks_l(fd, args);
1057 dumpEffectChains_l(fd, args);
1058
1059 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001060 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001061 }
1062
1063 dprintf(fd, " Local log:\n");
1064 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001065
1066 // --all does the statistics
1067 bool dumpAll = false;
1068 for (const auto &arg : args) {
1069 if (arg == String16("--all")) {
1070 dumpAll = true;
1071 }
1072 }
1073 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001074 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001075 if (!sched.empty()) {
1076 (void)write(fd, sched.c_str(), sched.size());
1077 }
1078 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001079}
1080
Andy Hungee58e4a2023-07-07 13:47:37 -07001081void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001082{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001083 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001084 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001085 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001086 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001087 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1088 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001089 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001090 dprintf(fd, " Channel count: %u\n", mChannelCount);
1091 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001092 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001093 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1094 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001095 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001096 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001097 size_t numConfig = mConfigEvents.size();
1098 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001099 const size_t SIZE = 256;
1100 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001101 for (size_t i = 0; i < numConfig; i++) {
1102 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001103 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001104 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001105 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001106 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001107 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001108 }
Andy Hung293558a2017-03-21 12:19:20 -07001109 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001110 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001111 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001112 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001113 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001114 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001115
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001116 // Dump timestamp statistics for the Thread types that support it.
1117 if (mType == RECORD
1118 || mType == MIXER
1119 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001120 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001121 || mType == OFFLOAD
1122 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001123 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001124 dprintf(fd, " Timestamp corrected: %s\n",
1125 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001126 }
1127
Andy Hung446f4df2019-02-21 12:26:41 -08001128 if (mLastIoBeginNs > 0) { // MMAP may not set this
1129 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1130 isOutput() ? "write" : "read",
1131 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1132 }
1133
1134 if (mProcessTimeMs.getN() > 0) {
1135 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1136 }
1137
1138 if (mIoJitterMs.getN() > 0) {
1139 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1140 isOutput() ? "write" : "read",
1141 mIoJitterMs.toString().c_str());
1142 }
1143
Andy Hunge6c37112019-02-26 17:38:10 -08001144 if (mLatencyMs.getN() > 0) {
1145 dprintf(fd, " Threadloop %s latency stats: %s\n",
1146 isOutput() ? "write" : "read",
1147 mLatencyMs.toString().c_str());
1148 }
Robert Wu06db0a32021-08-10 19:05:34 +00001149
1150 if (mMonopipePipeDepthStats.getN() > 0) {
1151 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1152 isOutput() ? "write" : "read",
1153 mMonopipePipeDepthStats.toString().c_str());
1154 }
Eric Laurent81784c32012-11-19 14:55:58 -08001155}
1156
Andy Hungee58e4a2023-07-07 13:47:37 -07001157void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001158{
1159 const size_t SIZE = 256;
1160 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001161
Marco Nelissenb2208842014-02-07 14:00:50 -08001162 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001163 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001164 write(fd, buffer, strlen(buffer));
1165
Marco Nelissenb2208842014-02-07 14:00:50 -08001166 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001167 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001168 if (chain != 0) {
1169 chain->dump(fd, args);
1170 }
1171 }
1172}
1173
Andy Hungee58e4a2023-07-07 13:47:37 -07001174void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001175{
Andy Hung972bec12023-08-31 16:13:39 -07001176 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001177 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001178}
1179
Andy Hungee58e4a2023-07-07 13:47:37 -07001180String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001181{
1182 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001183 case MIXER:
1184 return String16("AudioMix");
1185 case DIRECT:
1186 return String16("AudioDirectOut");
1187 case DUPLICATING:
1188 return String16("AudioDup");
1189 case RECORD:
1190 return String16("AudioIn");
1191 case OFFLOAD:
1192 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001193 case MMAP_PLAYBACK:
1194 return String16("MmapPlayback");
1195 case MMAP_CAPTURE:
1196 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001197 case SPATIALIZER:
1198 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001199 default:
1200 ALOG_ASSERT(false);
1201 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001202 }
1203}
1204
Andy Hungee58e4a2023-07-07 13:47:37 -07001205void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001206{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001207 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001208 if (mPowerManager != 0) {
1209 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001210 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001211 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1212 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001213 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001214 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001215 {} /* workSource */,
1216 {} /* historyTag */);
1217 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001218 mWakeLockToken = binder;
1219 }
Chris Ye6597d732020-02-28 22:38:25 -08001220 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001221 }
Wei Jia3f273d12015-11-24 09:06:49 -08001222
Andy Hung3f0c9022016-01-15 17:49:46 -08001223 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001224 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1225 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001226}
1227
Andy Hungee58e4a2023-07-07 13:47:37 -07001228void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001229{
Andy Hung972bec12023-08-31 16:13:39 -07001230 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001231 releaseWakeLock_l();
1232}
1233
Andy Hungee58e4a2023-07-07 13:47:37 -07001234void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001235{
Andy Hung3f0c9022016-01-15 17:49:46 -08001236 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001237 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001238 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001239 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001240 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001241 }
1242 mWakeLockToken.clear();
1243 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001244}
1245
Andy Hungee58e4a2023-07-07 13:47:37 -07001246void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001247 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001248 // use checkService() to avoid blocking if power service is not up yet
1249 sp<IBinder> binder =
1250 defaultServiceManager()->checkService(String16("power"));
1251 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001252 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001253 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001254 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001255 binder->linkToDeath(mDeathRecipient);
1256 }
1257 }
1258}
1259
Andy Hungee58e4a2023-07-07 13:47:37 -07001260void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001261 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001262
1263#if !LOG_NDEBUG
1264 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001265 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001266 s << uid << " ";
1267 }
1268 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1269#endif
1270
Andy Hung438e7572015-12-14 15:51:17 -08001271 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1272 if (mSystemReady) {
1273 ALOGE("no wake lock to update, but system ready!");
1274 } else {
1275 ALOGW("no wake lock to update, system not ready yet");
1276 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001277 return;
1278 }
1279 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001280 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001281 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1282 mWakeLockToken, uidsAsInt);
1283 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001284 }
1285}
1286
Andy Hungee58e4a2023-07-07 13:47:37 -07001287void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001288{
Andy Hung972bec12023-08-31 16:13:39 -07001289 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001290 releaseWakeLock_l();
1291 mPowerManager.clear();
1292}
1293
Andy Hungee58e4a2023-07-07 13:47:37 -07001294void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001295 const DeviceDescriptorBaseVector& outDevices __unused)
1296{
1297 ALOGE("%s should only be called in RecordThread", __func__);
1298}
1299
Andy Hungee58e4a2023-07-07 13:47:37 -07001300void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001301{
1302 ALOGE("%s should only be called in RecordThread", __func__);
1303}
1304
Andy Hungee58e4a2023-07-07 13:47:37 -07001305void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001306{
1307 sp<ThreadBase> thread = mThread.promote();
1308 if (thread != 0) {
1309 thread->clearPowerManager();
1310 }
1311 ALOGW("power manager service died !!!");
1312}
1313
Andy Hungee58e4a2023-07-07 13:47:37 -07001314void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001315 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001316{
Andy Hung116bc262023-06-20 18:56:17 -07001317 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001318 if (chain != 0) {
1319 if (type != NULL) {
1320 chain->setEffectSuspended_l(type, suspend);
1321 } else {
1322 chain->setEffectSuspendedAll_l(suspend);
1323 }
1324 }
1325
1326 updateSuspendedSessions_l(type, suspend, sessionId);
1327}
1328
Andy Hungee58e4a2023-07-07 13:47:37 -07001329void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001330{
1331 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1332 if (index < 0) {
1333 return;
1334 }
1335
1336 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1337 mSuspendedSessions.valueAt(index);
1338
1339 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001340 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001341 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001342 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001343 chain->setEffectSuspendedAll_l(true);
1344 } else {
1345 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1346 desc->mType.timeLow);
1347 chain->setEffectSuspended_l(&desc->mType, true);
1348 }
1349 }
1350 }
1351}
1352
Andy Hungee58e4a2023-07-07 13:47:37 -07001353void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001354 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001355 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001356{
1357 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1358
1359 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1360
1361 if (suspend) {
1362 if (index >= 0) {
1363 sessionEffects = mSuspendedSessions.valueAt(index);
1364 } else {
1365 mSuspendedSessions.add(sessionId, sessionEffects);
1366 }
1367 } else {
1368 if (index < 0) {
1369 return;
1370 }
1371 sessionEffects = mSuspendedSessions.valueAt(index);
1372 }
1373
1374
Andy Hung116bc262023-06-20 18:56:17 -07001375 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001376 if (type != NULL) {
1377 key = type->timeLow;
1378 }
1379 index = sessionEffects.indexOfKey(key);
1380
1381 sp<SuspendedSessionDesc> desc;
1382 if (suspend) {
1383 if (index >= 0) {
1384 desc = sessionEffects.valueAt(index);
1385 } else {
1386 desc = new SuspendedSessionDesc();
1387 if (type != NULL) {
1388 desc->mType = *type;
1389 }
1390 sessionEffects.add(key, desc);
1391 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1392 }
1393 desc->mRefCount++;
1394 } else {
1395 if (index < 0) {
1396 return;
1397 }
1398 desc = sessionEffects.valueAt(index);
1399 if (--desc->mRefCount == 0) {
1400 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1401 sessionEffects.removeItemsAt(index);
1402 if (sessionEffects.isEmpty()) {
1403 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1404 sessionId);
1405 mSuspendedSessions.removeItem(sessionId);
1406 }
1407 }
1408 }
1409 if (!sessionEffects.isEmpty()) {
1410 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1411 }
1412}
1413
Andy Hungee58e4a2023-07-07 13:47:37 -07001414void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001415 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001416 bool threadLocked)
1417NO_THREAD_SAFETY_ANALYSIS // manual locking
1418{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001419 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001420 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001421 }
Eric Laurent81784c32012-11-19 14:55:58 -08001422
Eric Laurent81784c32012-11-19 14:55:58 -08001423 if (mType != RECORD) {
1424 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1425 // another session. This gives the priority to well behaved effect control panels
1426 // and applications not using global effects.
1427 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1428 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001429 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001430 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1431 }
1432 }
1433
Eric Laurent6b446ce2019-12-13 10:56:31 -08001434 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001435 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001436 }
1437}
1438
Andy Hungc5007f82023-08-29 14:26:09 -07001439// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001440status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001441 const effect_descriptor_t *desc, audio_session_t sessionId)
1442{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001443 // No global output effect sessions on record threads
1444 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1445 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001446 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1447 desc->name, mThreadName);
1448 return BAD_VALUE;
1449 }
1450 // only pre processing effects on record thread
1451 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1452 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1453 desc->name, mThreadName);
1454 return BAD_VALUE;
1455 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001456
1457 // always allow effects without processing load or latency
1458 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1459 return NO_ERROR;
1460 }
1461
Eric Laurent4c415062016-06-17 16:14:16 -07001462 audio_input_flags_t flags = mInput->flags;
1463 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1464 if (flags & AUDIO_INPUT_FLAG_RAW) {
1465 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1466 desc->name, mThreadName);
1467 return BAD_VALUE;
1468 }
1469 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1470 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1471 desc->name, mThreadName);
1472 return BAD_VALUE;
1473 }
1474 }
jiabineb3bda02020-06-30 14:07:03 -07001475
Andy Hung116bc262023-06-20 18:56:17 -07001476 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001477 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1478 return BAD_VALUE;
1479 }
Eric Laurent4c415062016-06-17 16:14:16 -07001480 return NO_ERROR;
1481}
1482
Andy Hungc5007f82023-08-29 14:26:09 -07001483// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001484status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001485 const effect_descriptor_t *desc, audio_session_t sessionId)
1486{
1487 // no preprocessing on playback threads
1488 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001489 ALOGW("%s: pre processing effect %s created on playback"
1490 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001491 return BAD_VALUE;
1492 }
1493
Eric Laurent3e4de772017-07-16 16:55:08 -07001494 // always allow effects without processing load or latency
1495 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1496 return NO_ERROR;
1497 }
1498
Andy Hung116bc262023-06-20 18:56:17 -07001499 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001500 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1501 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001502 return BAD_VALUE;
1503 }
1504
Eric Laurent4eb45d02023-12-20 12:07:17 +01001505 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001506 && mType != SPATIALIZER) {
1507 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1508 __func__, mType);
1509 return BAD_VALUE;
1510 }
1511
Eric Laurent4c415062016-06-17 16:14:16 -07001512 switch (mType) {
1513 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001514 audio_output_flags_t flags = mOutput->flags;
1515 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1516 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1517 // global effects are applied only to non fast tracks if they are SW
1518 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1519 break;
1520 }
1521 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1522 // only post processing on output stage session
1523 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001524 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1525 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001526 return BAD_VALUE;
1527 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001528 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1529 // only post processing on output stage session
1530 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001531 ALOGW("%s: non post processing effect %s not allowed on device session",
1532 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001533 return BAD_VALUE;
1534 }
Eric Laurent4c415062016-06-17 16:14:16 -07001535 } else {
1536 // no restriction on effects applied on non fast tracks
1537 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1538 break;
1539 }
1540 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001541
Eric Laurent4c415062016-06-17 16:14:16 -07001542 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001543 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001544 return BAD_VALUE;
1545 }
1546 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001547 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1548 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001549 return BAD_VALUE;
1550 }
1551 }
1552 } break;
1553 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001554 // nothing actionable on offload threads, if the effect:
1555 // - is offloadable: the effect can be created
1556 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1557 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001558 break;
1559 case DIRECT:
1560 // Reject any effect on Direct output threads for now, since the format of
1561 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001562 ALOGW("%s: effect %s on DIRECT output thread %s",
1563 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001564 return BAD_VALUE;
1565 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001566 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001567 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1568 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001569 return BAD_VALUE;
1570 }
1571 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001572 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1573 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001574 return BAD_VALUE;
1575 }
1576 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001577 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1578 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001579 return BAD_VALUE;
1580 }
1581 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001582 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001583 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1584 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1585 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1586 // are supported and added after the spatializer.
1587 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1588 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1589 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001590 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001591 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1592 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001593 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001594 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1595 break;
1596 }
1597 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1598 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1599 __func__, desc->name);
1600 return BAD_VALUE;
1601 }
1602 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1603 // only post processing on output stage session
1604 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1605 ALOGW("%s: non post processing effect %s not allowed on device session",
1606 __func__, desc->name);
1607 return BAD_VALUE;
1608 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001609 }
1610 break;
jiabinc658e452022-10-21 20:52:21 +00001611 case BIT_PERFECT:
1612 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1613 // Allow HW accelerated effects of tunnel type
1614 break;
1615 }
1616 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1617 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1618 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1619 // 3) there is any bit-perfect track with the given session id.
1620 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1621 sessionId == AUDIO_SESSION_DEVICE) {
1622 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1623 __func__, desc->name, mThreadName);
1624 return BAD_VALUE;
1625 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1626 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1627 __func__, desc->name, sessionId);
1628 return BAD_VALUE;
1629 }
1630 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001631 default:
1632 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1633 }
1634
1635 return NO_ERROR;
1636}
1637
Andy Hungc5007f82023-08-29 14:26:09 -07001638// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001639sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001640 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001641 const sp<IEffectClient>& effectClient,
1642 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001643 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001644 effect_descriptor_t *desc,
1645 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001646 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001647 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001648 bool probe,
1649 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001650{
Andy Hung116bc262023-06-20 18:56:17 -07001651 sp<IAfEffectModule> effect;
1652 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001653 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001654 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001655 bool chainCreated = false;
1656 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001657 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001658
1659 lStatus = initCheck();
1660 if (lStatus != NO_ERROR) {
1661 ALOGW("createEffect_l() Audio driver not initialized.");
1662 goto Exit;
1663 }
1664
Eric Laurent81784c32012-11-19 14:55:58 -08001665 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1666
Andy Hungc5007f82023-08-29 14:26:09 -07001667 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001668 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001669
Eric Laurent4c415062016-06-17 16:14:16 -07001670 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001671 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001672 goto Exit;
1673 }
1674
Eric Laurent81784c32012-11-19 14:55:58 -08001675 // check for existing effect chain with the requested audio session
1676 chain = getEffectChain_l(sessionId);
1677 if (chain == 0) {
1678 // create a new chain for this session
1679 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001680 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001681 addEffectChain_l(chain);
1682 chain->setStrategy(getStrategyForSession_l(sessionId));
1683 chainCreated = true;
1684 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001685 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001686 }
1687
1688 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1689
1690 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001691 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001692 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001693 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001694 if (lStatus != NO_ERROR) {
1695 goto Exit;
1696 }
1697 effectCreated = true;
1698
jiabinc52b1ff2019-10-31 17:20:42 -07001699 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001700 effect->setDevices(outDeviceTypeAddrs());
1701 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001702 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001703 effect->setAudioSource(mAudioSource);
1704 }
jiabin1319f5a2021-03-30 22:21:24 +00001705 if (effect->isHapticGenerator()) {
1706 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1707 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001708 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001709 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001710 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001711 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001712 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001713 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001714 }
1715 }
Eric Laurent81784c32012-11-19 14:55:58 -08001716 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001717 handle = IAfEffectHandle::create(
1718 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001719 lStatus = handle->initCheck();
1720 if (lStatus == OK) {
1721 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001722 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001723 }
Eric Laurent81784c32012-11-19 14:55:58 -08001724 if (enabled != NULL) {
1725 *enabled = (int)effect->isEnabled();
1726 }
1727 }
1728
1729Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001730 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001731 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001732 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001733 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001734 }
Eric Laurent81784c32012-11-19 14:55:58 -08001735 if (chainCreated) {
1736 removeEffectChain_l(chain);
1737 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001738 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001739 }
1740
Glenn Kasten9156ef32013-08-06 15:39:08 -07001741 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001742 return handle;
1743}
1744
Andy Hungee58e4a2023-07-07 13:47:37 -07001745void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001746 bool unpinIfLast)
1747{
1748 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001749 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 {
Andy Hung972bec12023-08-31 16:13:39 -07001751 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001752 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001753 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001754 return;
1755 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001756 effect = effectBase->asEffectModule();
1757 if (effect == nullptr) {
1758 return;
1759 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001760 // restore suspended effects if the disconnected handle was enabled and the last one.
1761 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1762 if (remove) {
1763 removeEffect_l(effect, true);
1764 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001765 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001766 }
1767 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001768 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001769 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001770 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001771 }
1772 }
1773}
1774
Andy Hungee58e4a2023-07-07 13:47:37 -07001775void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001776 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001777 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001778 broadcast_l();
1779 }
1780 if (!effect->isOffloadable()) {
1781 if (mType == ThreadBase::OFFLOAD) {
1782 PlaybackThread *t = (PlaybackThread *)this;
1783 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1784 }
1785 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001786 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001787 }
1788 }
1789}
1790
Andy Hungee58e4a2023-07-07 13:47:37 -07001791void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001792 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001793 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001794 broadcast_l();
1795 }
1796}
1797
Andy Hungee58e4a2023-07-07 13:47:37 -07001798sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001799 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001800{
Andy Hung972bec12023-08-31 16:13:39 -07001801 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001802 return getEffect_l(sessionId, effectId);
1803}
1804
Andy Hungee58e4a2023-07-07 13:47:37 -07001805sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001806 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001807{
Andy Hung116bc262023-06-20 18:56:17 -07001808 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001809 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1810}
1811
Andy Hungee58e4a2023-07-07 13:47:37 -07001812std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001813{
Andy Hung116bc262023-06-20 18:56:17 -07001814 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001815 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001816}
1817
Andy Hung972bec12023-08-31 16:13:39 -07001818// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1819// ThreadBase::mutex() held
1820status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001821{
1822 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001823 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001824 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001825 bool chainCreated = false;
1826
Eric Laurent5baf2af2013-09-12 17:37:00 -07001827 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001828 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1829 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001830
Eric Laurent81784c32012-11-19 14:55:58 -08001831 if (chain == 0) {
1832 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001833 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001834 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001835 addEffectChain_l(chain);
1836 chain->setStrategy(getStrategyForSession_l(sessionId));
1837 chainCreated = true;
1838 }
Andy Hung972bec12023-08-31 16:13:39 -07001839 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001840
1841 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001842 ALOGW("%s: %p effect %s already present in chain %p",
1843 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001844 return BAD_VALUE;
1845 }
1846
Shunkai Yaod125e402024-01-20 03:19:06 +00001847 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001848
Shunkai Yao29d10572024-03-19 04:31:47 +00001849 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001850 if (status != NO_ERROR) {
1851 if (chainCreated) {
1852 removeEffectChain_l(chain);
1853 }
1854 return status;
1855 }
1856
jiabin8f278ee2019-11-11 12:16:27 -08001857 effect->setDevices(outDeviceTypeAddrs());
1858 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001859 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001860 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001861
Eric Laurent81784c32012-11-19 14:55:58 -08001862 return NO_ERROR;
1863}
1864
Andy Hungee58e4a2023-07-07 13:47:37 -07001865void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001866
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001867 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001868 effect_descriptor_t desc = effect->desc();
1869 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1870 detachAuxEffect_l(effect->id());
1871 }
1872
Andy Hung116bc262023-06-20 18:56:17 -07001873 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001874 if (chain != 0) {
1875 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001876 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001877 removeEffectChain_l(chain);
1878 }
1879 } else {
1880 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1881 }
1882}
1883
Shunkai Yaof4847652024-01-12 00:25:20 +00001884void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1885 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001886{
1887 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001888 for (const auto& effectChain : effectChains) {
1889 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001890 }
1891}
1892
Shunkai Yaof4847652024-01-12 00:25:20 +00001893void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1894 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001895{
Shunkai Yaof4847652024-01-12 00:25:20 +00001896 for (const auto& effectChain : effectChains) {
1897 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001898 }
1899}
1900
Andy Hungee58e4a2023-07-07 13:47:37 -07001901sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001902{
Andy Hung972bec12023-08-31 16:13:39 -07001903 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001904 return getEffectChain_l(sessionId);
1905}
1906
Andy Hungee58e4a2023-07-07 13:47:37 -07001907sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001908 const
Eric Laurent81784c32012-11-19 14:55:58 -08001909{
1910 size_t size = mEffectChains.size();
1911 for (size_t i = 0; i < size; i++) {
1912 if (mEffectChains[i]->sessionId() == sessionId) {
1913 return mEffectChains[i];
1914 }
1915 }
1916 return 0;
1917}
1918
Andy Hungee58e4a2023-07-07 13:47:37 -07001919void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001920{
Andy Hung972bec12023-08-31 16:13:39 -07001921 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001922 size_t size = mEffectChains.size();
1923 for (size_t i = 0; i < size; i++) {
1924 mEffectChains[i]->setMode_l(mode);
1925 }
1926}
1927
Andy Hungee58e4a2023-07-07 13:47:37 -07001928void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001929{
1930 config->type = AUDIO_PORT_TYPE_MIX;
1931 config->ext.mix.handle = mId;
1932 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001933 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001934 config->channel_mask = mChannelMask;
1935 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1936 AUDIO_PORT_CONFIG_FORMAT;
1937}
1938
Andy Hungee58e4a2023-07-07 13:47:37 -07001939void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001940{
Andy Hung972bec12023-08-31 16:13:39 -07001941 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001942 if (mSystemReady) {
1943 return;
1944 }
1945 mSystemReady = true;
1946
1947 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1948 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1949 }
1950 mPendingConfigEvents.clear();
1951}
1952
Andy Hungdae27702016-10-31 14:01:16 -07001953template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001954ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001955 ssize_t index = mActiveTracks.indexOf(track);
1956 if (index >= 0) {
1957 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1958 return index;
1959 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001960 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001961 mActiveTracksGeneration++;
1962 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001963 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001964 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001965 return mActiveTracks.add(track);
1966}
1967
1968template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001969ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001970 ssize_t index = mActiveTracks.remove(track);
1971 if (index < 0) {
1972 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1973 return index;
1974 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001975 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001976 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001977 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001978 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001979 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001980#ifdef TEE_SINK
1981 track->dumpTee(-1 /* fd */, "_REMOVE");
1982#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001983 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001984 return index;
1985}
1986
1987template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001988void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001989 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001990 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001991 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001992 }
1993 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001994 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001995 mActiveTracks.clear();
1996 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001997}
1998
1999template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07002000void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07002001 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002002 // Updates ActiveTracks client uids to the thread wakelock.
2003 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2004 thread->updateWakeLockUids_l(getWakeLockUids());
2005 mLastActiveTracksGeneration = mActiveTracksGeneration;
2006 }
Andy Hungdae27702016-10-31 14:01:16 -07002007}
Eric Laurent83b88082014-06-20 18:31:16 -07002008
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002009template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002010bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002011 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002012 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002013
2014 for (const sp<T> &track : mActiveTracks) {
2015 // Do not short-circuit as all hasChanged states must be reset
2016 // as all the metadata are going to be sent
2017 hasChanged |= track->readAndClearHasChanged();
2018 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002019 return hasChanged;
2020}
2021
2022template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002023void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002024 const char *funcName, const sp<T> &track) const {
2025 if (mLocalLog != nullptr) {
2026 String8 result;
2027 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002028 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002029 }
2030}
2031
Andy Hungee58e4a2023-07-07 13:47:37 -07002032void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002033{
2034 // Thread could be blocked waiting for async
2035 // so signal it to handle state changes immediately
2036 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2037 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2038 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002039 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002040}
2041
Andy Hungd0979812019-02-21 15:51:44 -08002042// Call only from threadLoop() or when it is idle.
2043// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002044void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002045NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002046{
2047 // Do not log if we have no stats.
2048 // We choose the timestamp verifier because it is the most likely item to be present.
2049 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2050 if (nstats == 0) {
2051 return;
2052 }
2053
2054 // Don't log more frequently than once per 12 hours.
2055 // We use BOOTTIME to include suspend time.
2056 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2057 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2058 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2059 return;
2060 }
2061
2062 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2063 mLastRecordedTimeNs = timeNs;
2064
Ray Essickf27e9872019-12-07 06:28:46 -08002065 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002066
2067#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2068
2069 // thread configuration
2070 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2071 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2072 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2073 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2074 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2075 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2076 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002077 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2078 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002079
2080 // thread statistics
2081 if (mIoJitterMs.getN() > 0) {
2082 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2083 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2084 }
2085 if (mProcessTimeMs.getN() > 0) {
2086 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2087 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2088 }
2089 const auto tsjitter = mTimestampVerifier.getJitterMs();
2090 if (tsjitter.getN() > 0) {
2091 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2092 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2093 }
2094 if (mLatencyMs.getN() > 0) {
2095 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2096 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2097 }
Robert Wu06db0a32021-08-10 19:05:34 +00002098 if (mMonopipePipeDepthStats.getN() > 0) {
2099 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2100 mMonopipePipeDepthStats.getMean());
2101 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2102 mMonopipePipeDepthStats.getStdDev());
2103 }
Andy Hungd0979812019-02-21 15:51:44 -08002104
2105 item->selfrecord();
2106}
2107
Andy Hungee58e4a2023-07-07 13:47:37 -07002108product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002109{
Andy Hung583043b2023-07-17 17:05:00 -07002110 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002111 return PRODUCT_STRATEGY_NONE;
2112 }
2113 return AudioSystem::getStrategyForStream(stream);
2114}
2115
Andy Hungc5007f82023-08-29 14:26:09 -07002116// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002117void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002118 const sp<audio_utils::MelProcessor>& /*processor*/)
2119{
2120 // Do nothing
2121 ALOGW("%s: ThreadBase does not support CSD", __func__);
2122}
2123
Andy Hungc5007f82023-08-29 14:26:09 -07002124// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002125void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002126{
2127 // Do nothing
2128 ALOGW("%s: ThreadBase does not support CSD", __func__);
2129}
2130
Eric Laurent81784c32012-11-19 14:55:58 -08002131// ----------------------------------------------------------------------------
2132// Playback
2133// ----------------------------------------------------------------------------
2134
Andy Hung583043b2023-07-17 17:05:00 -07002135PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002136 AudioStreamOut* output,
2137 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002138 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002139 bool systemReady,
2140 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002141 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002142 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002143 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002144 mMixerBuffer(NULL),
2145 mMixerBufferSize(0),
2146 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2147 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002148 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002149 mEffectBuffer(NULL),
2150 mEffectBufferSize(0),
2151 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2152 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002153 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002154 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002155 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002156 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002157 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002158 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002159 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002160 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002161 mMixerStatus(MIXER_IDLE),
2162 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002163 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002164 mBytesRemaining(0),
2165 mCurrentWriteLength(0),
2166 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002167 mWriteAckSequence(0),
2168 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002169 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002170 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002171 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002172 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002173 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002174 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002175 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002176{
Glenn Kastend7dca052015-03-05 16:05:54 -08002177 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002178 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002179
Andy Hungc5007f82023-08-29 14:26:09 -07002180 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002181 // it would be safer to explicitly pass initial masterVolume/masterMute as
2182 // parameter.
2183 //
2184 // If the HAL we are using has support for master volume or master mute,
2185 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2186 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002187 mMasterVolume = afThreadCallback->masterVolume_l();
2188 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002189 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002190 if (mOutput->audioHwDev->canSetMasterVolume()) {
2191 mMasterVolume = 1.0;
2192 }
2193
2194 if (mOutput->audioHwDev->canSetMasterMute()) {
2195 mMasterMute = false;
2196 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002197 mIsMsdDevice = strcmp(
2198 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002199 }
2200
Eric Laurentf1f22e72021-07-13 14:04:14 +02002201 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2202 mMixerChannelMask = mixerConfig->channel_mask;
2203 }
2204
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002205 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002206
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002207 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002208 && mMixerChannelMask != mChannelMask) {
2209 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2210 mChannelMask, mMixerChannelMask);
2211 }
2212
Andy Hungc8fddf32018-08-08 18:32:37 -07002213 // TODO: We may also match on address as well as device type for
2214 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002215 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002216 // TODO: This property should be ensure that only contains one single device type.
2217 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2218 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002219 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2220 : AUDIO_DEVICE_NONE));
2221 }
Andy Hung6b137d12024-08-27 22:35:17 +00002222 if (!audioserver_flags::portid_volume_management()) {
2223 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2224 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2225 mStreamTypes[stream].volume = 0.0f;
2226 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2227 }
2228 // Audio patch and call assistant volume are always max
2229 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2230 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2231 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2232 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002233 }
Eric Laurent81784c32012-11-19 14:55:58 -08002234}
2235
Andy Hungee58e4a2023-07-07 13:47:37 -07002236PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002237{
Andy Hung583043b2023-07-17 17:05:00 -07002238 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002239 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002240 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002241 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002242 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002245// Thread virtuals
2246
Andy Hungee58e4a2023-07-07 13:47:37 -07002247void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002248{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002249 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002250 ALOGE("The stream is not open yet"); // This should not happen.
2251 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002252 // Callbacks take strong or weak pointers as a parameter.
2253 // Since PlaybackThread passes itself as a callback handler, it can only
2254 // be done outside of the constructor. Creating weak and especially strong
2255 // pointers to a refcounted object in its own constructor is strongly
2256 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2257 // Even if a function takes a weak pointer, it is possible that it will
2258 // need to convert it to a strong pointer down the line.
2259 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2260 mOutput->stream->setCallback(this) == OK) {
2261 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002262 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002263 }
2264
jiabinf6eb4c32020-02-25 14:06:25 -08002265 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002266 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002267 }
2268 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002269 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002270 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002271}
2272
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002273// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002274void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002275{
2276 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002277 status_t result = mOutput->stream->exit();
2278 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002279}
2280
Andy Hungee58e4a2023-07-07 13:47:37 -07002281void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002282{
Eric Laurent81784c32012-11-19 14:55:58 -08002283 String8 result;
Andy Hung6b137d12024-08-27 22:35:17 +00002284 if (!audioserver_flags::portid_volume_management()) {
2285 result.appendFormat(" Stream volumes in dB: ");
2286 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2287 const stream_type_t *st = &mStreamTypes[i];
2288 if (i > 0) {
2289 result.appendFormat(", ");
2290 }
2291 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2292 if (st->mute) {
2293 result.append("M");
2294 }
Eric Laurent81784c32012-11-19 14:55:58 -08002295 }
2296 }
2297 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002298 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002299 result.clear();
2300
Eric Laurent81784c32012-11-19 14:55:58 -08002301 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2302 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002303 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002304 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002305
2306 size_t numtracks = mTracks.size();
2307 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002308 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002309 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002310 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002311 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002312 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002313 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002314 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002315 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002316 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002317 if (track != 0) {
2318 bool active = mActiveTracks.indexOf(track) >= 0;
2319 if (active) {
2320 numactiveseen++;
2321 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002322 result.append(prefix);
2323 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002324 }
2325 }
2326 } else {
2327 result.append("\n");
2328 }
2329 if (numactiveseen != numactive) {
2330 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002331 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002332 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002333 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002334 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002335 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002336 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002337 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002338 result.append(prefix);
2339 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002340 }
2341 }
2342 }
2343
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002344 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002345}
2346
Andy Hungee58e4a2023-07-07 13:47:37 -07002347void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002348{
Andy Hung04cb8f72020-03-20 13:44:33 -07002349 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002350 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002351 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2352 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002353 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2354 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2355 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2356 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002357 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002358 dprintf(fd, " Total writes: %d\n", mNumWrites);
2359 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2360 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002361 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002362 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002363 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002364 AudioStreamOut *output = mOutput;
2365 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002366 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002367 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002368 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2369 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2370 if (mPipeSink.get() != nullptr) {
2371 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2372 }
2373 if (output != nullptr) {
2374 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002375 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002376 }
Eric Laurent81784c32012-11-19 14:55:58 -08002377}
2378
Andy Hungc5007f82023-08-29 14:26:09 -07002379// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002380sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002381 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002382 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002383 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002384 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002385 audio_format_t format,
2386 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002387 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002388 size_t *pNotificationFrameCount,
2389 uint32_t notificationsPerBuffer,
2390 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002391 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002392 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002393 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002394 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002395 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002396 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002397 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002398 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002399 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002400 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002401 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00002402 audio_output_flags_t *afTrackFlags,
2403 float volume)
Eric Laurent81784c32012-11-19 14:55:58 -08002404{
Glenn Kasten74935e42013-12-19 08:56:45 -08002405 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002406 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002407 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002408 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002409 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002410 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002411 uint32_t sampleRate;
2412
2413 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2414 lStatus = BAD_VALUE;
2415 goto Exit;
2416 }
Eric Laurent21da6472017-11-09 16:29:26 -08002417
2418 if (*pSampleRate == 0) {
2419 *pSampleRate = mSampleRate;
2420 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002421 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002422
2423 // special case for FAST flag considered OK if fast mixer is present
2424 if (hasFastMixer()) {
2425 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2426 }
2427
2428 // Check if requested flags are compatible with output stream flags
2429 if ((*flags & outputFlags) != *flags) {
2430 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2431 *flags, outputFlags);
2432 *flags = (audio_output_flags_t)(*flags & outputFlags);
2433 }
Eric Laurent81784c32012-11-19 14:55:58 -08002434
jiabinc658e452022-10-21 20:52:21 +00002435 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002436 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002437 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002438 if (chain.get() != nullptr) {
2439 // Bit-perfect is required according to the configuration and preferred mixer
2440 // attributes, but it is not in the output flag from the client's request. Explicitly
2441 // adding bit-perfect flag to check the compatibility
2442 audio_output_flags_t flagsToCheck =
2443 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2444 chain->checkOutputFlagCompatibility(&flagsToCheck);
2445 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2446 ALOGE("%s cannot create track as there is data-processing effect attached to "
2447 "given session id(%d)", __func__, sessionId);
2448 lStatus = BAD_VALUE;
2449 goto Exit;
2450 }
2451 *flags = flagsToCheck;
2452 }
2453 }
2454
Eric Laurent81784c32012-11-19 14:55:58 -08002455 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002456 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002457 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002458 // PCM data
2459 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002460 // TODO: extract as a data library function that checks that a computationally
2461 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002462 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002463 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2464 (channelMask == AUDIO_CHANNEL_OUT_MONO
2465 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002466 // hardware sample rate
2467 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002468 // normal mixer has an associated fast mixer
2469 hasFastMixer() &&
2470 // there are sufficient fast track slots available
2471 (mFastTrackAvailMask != 0)
2472 // FIXME test that MixerThread for this fast track has a capable output HAL
2473 // FIXME add a permission test also?
2474 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002475 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2476 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002477 // read the fast track multiplier property the first time it is needed
2478 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2479 if (ok != 0) {
2480 ALOGE("%s pthread_once failed: %d", __func__, ok);
2481 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002482 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002483 }
Eric Laurent4c415062016-06-17 16:14:16 -07002484
2485 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002486 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002487 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002488 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002489 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002490 AUDIO_SESSION_OUTPUT_STAGE,
2491 AUDIO_SESSION_OUTPUT_MIX,
2492 sessionId,
2493 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002494 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002495 if (chain.get() != nullptr) {
2496 audio_output_flags_t old = *flags;
2497 chain->checkOutputFlagCompatibility(flags);
2498 if (old != *flags) {
2499 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2500 (int)session, (int)old, (int)*flags);
2501 }
Eric Laurent4c415062016-06-17 16:14:16 -07002502 }
2503 }
2504 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002505 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002506 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2507 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002508 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002509 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002510 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002511 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002512 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002513 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002514 audio_is_linear_pcm(format), channelMask, sampleRate,
2515 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002516 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002517 }
2518 }
Eric Laurent21da6472017-11-09 16:29:26 -08002519
2520 if (!audio_has_proportional_frames(format)) {
2521 if (sharedBuffer != 0) {
2522 // Same comment as below about ignoring frameCount parameter for set()
2523 frameCount = sharedBuffer->size();
2524 } else if (frameCount == 0) {
2525 frameCount = mNormalFrameCount;
2526 }
2527 if (notificationFrameCount != frameCount) {
2528 notificationFrameCount = frameCount;
2529 }
2530 } else if (sharedBuffer != 0) {
2531 // FIXME: Ensure client side memory buffers need
2532 // not have additional alignment beyond sample
2533 // (e.g. 16 bit stereo accessed as 32 bit frame).
2534 size_t alignment = audio_bytes_per_sample(format);
2535 if (alignment & 1) {
2536 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2537 alignment = 1;
2538 }
2539 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2540 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2541 if (channelCount > 1) {
2542 // More than 2 channels does not require stronger alignment than stereo
2543 alignment <<= 1;
2544 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002545 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002546 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002547 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002548 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 goto Exit;
2550 }
Eric Laurent21da6472017-11-09 16:29:26 -08002551
2552 // When initializing a shared buffer AudioTrack via constructors,
2553 // there's no frameCount parameter.
2554 // But when initializing a shared buffer AudioTrack via set(),
2555 // there _is_ a frameCount parameter. We silently ignore it.
2556 frameCount = sharedBuffer->size() / frameSize;
2557 } else {
2558 size_t minFrameCount = 0;
2559 // For fast tracks we try to respect the application's request for notifications per buffer.
2560 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2561 if (notificationsPerBuffer > 0) {
2562 // Avoid possible arithmetic overflow during multiplication.
2563 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2564 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2565 notificationsPerBuffer, mFrameCount);
2566 } else {
2567 minFrameCount = mFrameCount * notificationsPerBuffer;
2568 }
2569 }
2570 } else {
2571 // For normal PCM streaming tracks, update minimum frame count.
2572 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2573 // cover audio hardware latency.
2574 // This is probably too conservative, but legacy application code may depend on it.
2575 // If you change this calculation, also review the start threshold which is related.
2576 uint32_t latencyMs = latency_l();
2577 if (latencyMs == 0) {
2578 ALOGE("Error when retrieving output stream latency");
2579 lStatus = UNKNOWN_ERROR;
2580 goto Exit;
2581 }
2582
2583 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2584 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2585
Eric Laurent81784c32012-11-19 14:55:58 -08002586 }
Eric Laurent21da6472017-11-09 16:29:26 -08002587 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002588 frameCount = minFrameCount;
2589 }
Eric Laurent81784c32012-11-19 14:55:58 -08002590 }
Eric Laurent21da6472017-11-09 16:29:26 -08002591
2592 // Make sure that application is notified with sufficient margin before underrun.
2593 // The client can divide the AudioTrack buffer into sub-buffers,
2594 // and expresses its desire to server as the notification frame count.
2595 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2596 size_t maxNotificationFrames;
2597 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2598 // notify every HAL buffer, regardless of the size of the track buffer
2599 maxNotificationFrames = mFrameCount;
2600 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002601 // Triple buffer the notification period for a triple buffered mixer period;
2602 // otherwise, double buffering for the notification period is fine.
2603 //
2604 // TODO: This should be moved to AudioTrack to modify the notification period
2605 // on AudioTrack::setBufferSizeInFrames() changes.
2606 const int nBuffering =
2607 (uint64_t{frameCount} * mSampleRate)
2608 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2609
Eric Laurent21da6472017-11-09 16:29:26 -08002610 maxNotificationFrames = frameCount / nBuffering;
2611 // If client requested a fast track but this was denied, then use the smaller maximum.
2612 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2613 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2614 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2615 maxNotificationFrames = maxNotificationFramesFastDenied;
2616 }
2617 }
2618 }
2619 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2620 if (notificationFrameCount == 0) {
2621 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2622 maxNotificationFrames, frameCount);
2623 } else {
2624 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2625 notificationFrameCount, maxNotificationFrames, frameCount);
2626 }
2627 notificationFrameCount = maxNotificationFrames;
2628 }
2629 }
2630
Glenn Kasten74935e42013-12-19 08:56:45 -08002631 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002632 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002633
Glenn Kastenc3df8382014-03-13 15:05:25 -07002634 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002635 case BIT_PERFECT:
2636 if (isBitPerfect) {
2637 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2638 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2639 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2640 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2641 mChannelMask);
2642 lStatus = BAD_VALUE;
2643 goto Exit;
2644 }
2645 }
2646 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002647
2648 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002649 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002650 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002651 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2652 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002653 sampleRate, format, channelMask, mOutput, mFormat);
2654 lStatus = BAD_VALUE;
2655 goto Exit;
2656 }
2657 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002658 break;
2659
2660 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002662 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2663 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 sampleRate, format, channelMask, mOutput, mFormat);
2665 lStatus = BAD_VALUE;
2666 goto Exit;
2667 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002668 break;
2669
2670 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002671 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002672 ALOGE("createTrack_l() Bad parameter: format %#x \""
2673 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 format, mOutput, mFormat);
2675 lStatus = BAD_VALUE;
2676 goto Exit;
2677 }
Andy Hungcd044842014-08-07 11:04:34 -07002678 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002679 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2680 lStatus = BAD_VALUE;
2681 goto Exit;
2682 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002683 break;
2684
Eric Laurent81784c32012-11-19 14:55:58 -08002685 }
2686
2687 lStatus = initCheck();
2688 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002689 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002690 goto Exit;
2691 }
2692
Andy Hungc5007f82023-08-29 14:26:09 -07002693 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002694 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002695
2696 // all tracks in same audio session must share the same routing strategy otherwise
2697 // conflicts will happen when tracks are moved from one output to another by audio policy
2698 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002699 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002700 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002701 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002702 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002703 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002704 if (sessionId == t->sessionId() && strategy != actual) {
2705 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2706 strategy, actual);
2707 lStatus = BAD_VALUE;
2708 goto Exit;
2709 }
2710 }
2711 }
2712
Deeraj Soman2b515232024-05-14 12:58:24 +05302713 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2714 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002715 // dynamic audio policy.
2716 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302717 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002718 audio_output_flags_t trackFlags = *flags;
2719 if (mType == DIRECT) {
2720 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302721 } else if (mType == OFFLOAD) {
2722 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2723 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002724 }
jiabin94ed47c2023-07-27 23:34:20 +00002725 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002726
Andy Hung8d31fd22023-06-26 19:20:57 -07002727 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002728 channelMask, frameCount,
2729 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002730 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002731 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Andy Hung6b137d12024-08-27 22:35:17 +00002732 speed, isSpatialized, isBitPerfect, volume);
Glenn Kasten03003332013-08-06 15:40:54 -07002733
Glenn Kasten03003332013-08-06 15:40:54 -07002734 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2735 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002736 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002737 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002738 goto Exit;
2739 }
2740 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002741 {
Andy Hung972bec12023-08-31 16:13:39 -07002742 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002743 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002744 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002745 }
2746 }
Eric Laurent81784c32012-11-19 14:55:58 -08002747
Andy Hung116bc262023-06-20 18:56:17 -07002748 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002749 if (chain != 0) {
2750 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2751 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002752 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002753 chain->incTrackCnt();
2754 }
2755
Eric Laurent05067782016-06-01 18:27:28 -07002756 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002757 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2758 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2759 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002760 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002761 }
2762 }
2763
2764 lStatus = NO_ERROR;
2765
2766Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002767 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002768 return track;
2769}
2770
Andy Hung1bc088a2018-02-09 15:57:31 -08002771template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002772ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002773{
Andy Hungc0691382018-09-12 18:01:57 -07002774 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002775 const ssize_t index = mTracks.remove(track);
2776 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002777 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002778 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002779 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002780 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002781 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002782 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002783 }
2784 return index;
2785}
2786
Andy Hungee58e4a2023-07-07 13:47:37 -07002787uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002788{
2789 return latency;
2790}
2791
Andy Hungee58e4a2023-07-07 13:47:37 -07002792uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002793{
Andy Hung972bec12023-08-31 16:13:39 -07002794 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002795 return latency_l();
2796}
Andy Hungee58e4a2023-07-07 13:47:37 -07002797uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002798NO_THREAD_SAFETY_ANALYSIS
2799// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002800{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002801 uint32_t latency;
2802 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2803 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002804 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002805 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002806}
2807
Andy Hungee58e4a2023-07-07 13:47:37 -07002808void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002809{
Andy Hung972bec12023-08-31 16:13:39 -07002810 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002811 // Don't apply master volume in SW if our HAL can do it for us.
2812 if (mOutput && mOutput->audioHwDev &&
2813 mOutput->audioHwDev->canSetMasterVolume()) {
2814 mMasterVolume = 1.0;
2815 } else {
2816 mMasterVolume = value;
2817 }
2818}
2819
Andy Hungee58e4a2023-07-07 13:47:37 -07002820void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002821{
2822 mMasterBalance.store(balance);
2823}
2824
Andy Hungee58e4a2023-07-07 13:47:37 -07002825void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002826{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002827 if (isDuplicating()) {
2828 return;
2829 }
Andy Hung972bec12023-08-31 16:13:39 -07002830 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002831 // Don't apply master mute in SW if our HAL can do it for us.
2832 if (mOutput && mOutput->audioHwDev &&
2833 mOutput->audioHwDev->canSetMasterMute()) {
2834 mMasterMute = false;
2835 } else {
2836 mMasterMute = muted;
2837 }
2838}
2839
Andy Hungee58e4a2023-07-07 13:47:37 -07002840void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002841{
Andy Hung972bec12023-08-31 16:13:39 -07002842 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002843 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002844 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002845}
2846
Andy Hungee58e4a2023-07-07 13:47:37 -07002847void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002848{
Andy Hung972bec12023-08-31 16:13:39 -07002849 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002850 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002851 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002852}
2853
Andy Hungee58e4a2023-07-07 13:47:37 -07002854float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002855{
Andy Hung972bec12023-08-31 16:13:39 -07002856 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002857 return mStreamTypes[stream].volume;
2858}
2859
Andy Hung6b137d12024-08-27 22:35:17 +00002860status_t PlaybackThread::setPortsVolume(
2861 const std::vector<audio_port_handle_t>& portIds, float volume) {
2862 audio_utils::lock_guard _l(mutex());
2863 for (const auto& portId : portIds) {
2864 for (size_t i = 0; i < mTracks.size(); i++) {
2865 sp<IAfTrack> track = mTracks[i].get();
2866 if (portId == track->portId()) {
2867 track->setPortVolume(volume);
2868 break;
2869 }
2870 }
2871 }
2872 broadcast_l();
2873 return NO_ERROR;
2874}
2875
Andy Hungee58e4a2023-07-07 13:47:37 -07002876void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002877{
2878 mOutput->stream->setVolume(left, right);
2879}
2880
Andy Hungc5007f82023-08-29 14:26:09 -07002881// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002882status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002883{
2884 status_t status = ALREADY_EXISTS;
2885
Eric Laurent81784c32012-11-19 14:55:58 -08002886 if (mActiveTracks.indexOf(track) < 0) {
2887 // the track is newly added, make sure it fills up all its
2888 // buffers before playing. This is to ensure the client will
2889 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002890 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002891 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002892 // Because the track is not on the ActiveTracks,
2893 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002894 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002895 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002896 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002897 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002898 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002900 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002901 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002902 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002903 }
2904 return INVALID_OPERATION;
2905 }
2906 // abort if start is rejected by audio policy manager
2907 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002908 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2909 // current playback thread is reopened, which may happen when clients set preferred
2910 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2911 // immediately.
2912 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002913 }
2914#ifdef ADD_BATTERY_DATA
2915 // to track the speaker usage
2916 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2917#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002918 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002919 }
2920
Eric Laurent51716182016-02-29 18:00:56 -08002921 // set retry count for buffer fill
2922 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002923 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002924 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002925 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002926 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002927 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002928 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002929 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002930 track->retryCount() = kMaxTrackStartupRetries;
2931 track->fillingStatus() =
2932 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002933 }
2934
Andy Hung116bc262023-06-20 18:56:17 -07002935 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002936 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2937 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002938 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002939 // Unlock due to VibratorService will lock for this call and will
2940 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002941 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002942 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002943 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002944 std::optional<media::AudioVibratorInfo> vibratorInfo;
2945 {
2946 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2947 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002948 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002949 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002950 }
Andy Hungc5007f82023-08-29 14:26:09 -07002951 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002952 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002953 if (vibratorInfo) {
2954 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2955 }
2956
jiabin57303cc2018-12-18 15:45:57 -08002957 // Haptic playback should be enabled by vibrator service.
2958 if (track->getHapticPlaybackEnabled()) {
2959 // Disable haptic playback of all active track to ensure only
2960 // one track playing haptic if current track should play haptic.
2961 for (const auto &t : mActiveTracks) {
2962 t->setHapticPlaybackEnabled(false);
2963 }
jiabin245cdd92018-12-07 17:55:15 -08002964 }
jiabine70bc7f2020-06-30 22:07:55 -07002965
2966 // Set haptic intensity for effect
2967 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002968 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002969 }
jiabin245cdd92018-12-07 17:55:15 -08002970 }
2971
Andy Hung8d31fd22023-06-26 19:20:57 -07002972 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002973 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002974
2975 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2976 // all key changes are complete. It is possible that the threadLoop will begin
2977 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002978 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002979
Eric Laurentd0107bc2013-06-11 14:38:48 -07002980 if (chain != 0) {
2981 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2982 track->sessionId());
2983 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002984 }
2985
Andy Hungc2b11cb2020-04-22 09:04:01 -07002986 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002987 status = NO_ERROR;
2988 }
2989
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002990 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002991 return status;
2992}
2993
Andy Hungee58e4a2023-07-07 13:47:37 -07002994bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002995{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002996 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002997 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002999 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003000 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08003001 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07003002 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07003003 if (track->isPausePending()) {
3004 track->pauseAck();
3005 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003006 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003007 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003008
3009 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003010}
3011
Andy Hungee58e4a2023-07-07 13:47:37 -07003012void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003013{
3014 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003015
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003016 String8 result;
3017 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003018 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003019
Eric Laurent81784c32012-11-19 14:55:58 -08003020 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003021 {
Andy Hung972bec12023-08-31 16:13:39 -07003022 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003023 mAudioTrackCallbacks.erase(track);
3024 }
Eric Laurent81784c32012-11-19 14:55:58 -08003025 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003026 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003027 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003028 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3029 mFastTrackAvailMask |= 1 << index;
3030 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003031 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003032 }
Andy Hung116bc262023-06-20 18:56:17 -07003033 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003034 if (chain != 0) {
3035 chain->decTrackCnt();
3036 }
3037}
3038
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003039std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3040{
3041 std::set<int32_t> result;
3042 for (const auto& t : mTracks) {
3043 if (t->isExternalTrack()) {
3044 result.insert(t->portId());
3045 }
3046 }
3047 return result;
3048}
3049
3050std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3051{
3052 audio_utils::lock_guard _l(mutex());
3053 return getTrackPortIds_l();
3054}
3055
Andy Hungee58e4a2023-07-07 13:47:37 -07003056String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003057{
Andy Hung972bec12023-08-31 16:13:39 -07003058 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003059 String8 out_s8;
3060 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3061 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003062 }
Andy Hung920f6572022-10-06 12:09:49 -07003063 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003064}
3065
Andy Hungee58e4a2023-07-07 13:47:37 -07003066status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003067 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003068 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003069 return NO_INIT;
3070 }
3071 return mOutput->stream->selectPresentation(presentationId, programId);
3072}
3073
Andy Hungab65b182023-09-06 19:41:47 -07003074void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003075 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003076 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003077 sp<AudioIoDescriptor> desc;
3078 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003079 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003080 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003081 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003082 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003083 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3084 mSampleRate, mFormat, mChannelMask,
3085 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3086 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003087 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003088 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003089 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003090 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003091 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003092 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003093 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003094 break;
3095 }
Andy Hungab65b182023-09-06 19:41:47 -07003096 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003097}
3098
Andy Hungee58e4a2023-07-07 13:47:37 -07003099void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003100{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003101 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102}
3103
Andy Hungee58e4a2023-07-07 13:47:37 -07003104void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003105{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003106 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107}
3108
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003109void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003110{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003111 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003112}
3113
Andy Hungee58e4a2023-07-07 13:47:37 -07003114void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003115 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003116{
Andy Hungee58e4a2023-07-07 13:47:37 -07003117 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003118 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003119 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003120 if (playbackThread == nullptr) {
3121 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3122 return;
3123 }
3124
jiabinf6eb4c32020-02-25 14:06:25 -08003125 audio_utils::metadata::Data metadata =
3126 audio_utils::metadata::dataFromByteString(metadataBs);
3127 if (metadata.empty()) {
3128 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3129 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3130 (int)metadataBs.size());
3131 return;
3132 }
3133
3134 audio_utils::metadata::ByteString metaDataStr =
3135 audio_utils::metadata::byteStringFromData(metadata);
3136 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003137 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003138 for (const auto& callbackPair : mAudioTrackCallbacks) {
3139 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003140 }
3141 }).detach();
3142}
3143
Andy Hungee58e4a2023-07-07 13:47:37 -07003144void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003145{
Andy Hung972bec12023-08-31 16:13:39 -07003146 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003147 // reject out of sequence requests
3148 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3149 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003150 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003151 }
3152}
3153
Andy Hungee58e4a2023-07-07 13:47:37 -07003154void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003155{
Andy Hung972bec12023-08-31 16:13:39 -07003156 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003157 // reject out of sequence requests
3158 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003159 // Register discontinuity when HW drain is completed because that can cause
3160 // the timestamp frame position to reset to 0 for direct and offload threads.
3161 // (Out of sequence requests are ignored, since the discontinuity would be handled
3162 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003163 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003164 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003165 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003166 }
3167}
3168
Andy Hungee58e4a2023-07-07 13:47:37 -07003169void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003170NO_THREAD_SAFETY_ANALYSIS
3171// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003172{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003173 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003174 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3175 mSampleRate = audioConfig.sample_rate;
3176 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003177 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003178 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003179 }
Andy Hung81994d62023-07-20 21:44:14 -07003180 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003181 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3182 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003183 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003184
3185 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3186 mMixerChannelMask = mChannelMask;
3187 }
3188
Andy Hunge5412692014-05-16 11:25:07 -07003189 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003190 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003191
Eric Laurentf1f22e72021-07-13 14:04:14 +02003192 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3193
Phil Burkca5e6142015-07-14 09:42:29 -07003194 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003195 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003196 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003197 // Get format from the shim, which will be different than the HAL format
3198 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003199 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003200 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003201 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003202 }
Andy Hung81994d62023-07-20 21:44:14 -07003203 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003204 LOG_FATAL("HAL format %#x not supported for mixed output",
3205 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003206 }
Phil Burk062e67a2015-02-11 13:40:50 -08003207 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003208 result = mOutput->stream->getBufferSize(&mBufferSize);
3209 LOG_ALWAYS_FATAL_IF(result != OK,
3210 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003211 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003212 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003213 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003214 mFrameCount);
3215 }
3216
Eric Laurentd1f69b02014-12-15 14:33:13 -08003217 mHwSupportsPause = false;
3218 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003219 bool supportsPause = false, supportsResume = false;
3220 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3221 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003222 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003223 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003224 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003225 } else if (supportsResume) {
3226 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003227 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003228 }
3229 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003230 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3231 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3232 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003233
Andy Hungfbfc3952015-01-15 13:33:51 -08003234 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3235 // For best precision, we use float instead of the associated output
3236 // device format (typically PCM 16 bit).
3237
3238 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3239 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3240 mBufferSize = mFrameSize * mFrameCount;
3241
3242 // TODO: We currently use the associated output device channel mask and sample rate.
3243 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3244 // (if a valid mask) to avoid premature downmix.
3245 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3246 // instead of the output device sample rate to avoid loss of high frequency information.
3247 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3248 }
3249
Andy Hung09a50072014-02-27 14:30:47 -08003250 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003251 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003252 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003253 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3254 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003255 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3256 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003257
Eric Laurent81784c32012-11-19 14:55:58 -08003258 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3259 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3260 maxNormalFrameCount = maxNormalFrameCount & ~15;
3261 if (maxNormalFrameCount < minNormalFrameCount) {
3262 maxNormalFrameCount = minNormalFrameCount;
3263 }
3264 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3265 if (multiplier <= 1.0) {
3266 multiplier = 1.0;
3267 } else if (multiplier <= 2.0) {
3268 if (2 * mFrameCount <= maxNormalFrameCount) {
3269 multiplier = 2.0;
3270 } else {
3271 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3272 }
3273 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003274 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003275 }
3276 }
3277 mNormalFrameCount = multiplier * mFrameCount;
3278 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003279 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003280 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3281 }
Andy Hungab65b182023-09-06 19:41:47 -07003282 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3283 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003284
Andy Hung08fb1742015-05-31 23:22:10 -07003285 // Check if we want to throttle the processing to no more than 2x normal rate
3286 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003287 mThreadThrottleTimeMs = 0;
3288 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003289 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3290
Andy Hung010a1a12014-03-13 13:57:33 -07003291 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3292 // Originally this was int16_t[] array, need to remove legacy implications.
3293 free(mSinkBuffer);
3294 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003295
Andy Hung5b10a202014-03-13 13:59:29 -07003296 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3297 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3298 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003299 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003300
Andy Hung69aed5f2014-02-25 17:24:40 -08003301 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3302 // drives the output.
3303 free(mMixerBuffer);
3304 mMixerBuffer = NULL;
3305 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003306 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003307 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003308 * audio_bytes_per_sample(mMixerBufferFormat);
3309 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3310 }
Andy Hung98ef9782014-03-04 14:46:50 -08003311 free(mEffectBuffer);
3312 mEffectBuffer = NULL;
3313 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003314 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003315 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003316 * audio_bytes_per_sample(mEffectBufferFormat);
3317 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3318 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003319
Eric Laurentb62d0362021-10-26 17:40:18 +02003320 if (mType == SPATIALIZER) {
3321 free(mPostSpatializerBuffer);
3322 mPostSpatializerBuffer = nullptr;
3323 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3324 * audio_bytes_per_sample(mEffectBufferFormat);
3325 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3326 }
3327
Mikhail Naganov55773032020-10-01 15:08:13 -07003328 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3329 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003330 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3331 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003332 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003333
Eric Laurent81784c32012-11-19 14:55:58 -08003334 // force reconfiguration of effect chains and engines to take new buffer size and audio
3335 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003336 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003337 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3338 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003339 // create a copy of mEffectChains as calling moveEffectChain_ll()
3340 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003341 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003342 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003343 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003344 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003345 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003346
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003347 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003348 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003349 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003350 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003351 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3352 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3353 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3354 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3355 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3356 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3357 (int32_t)mHapticChannelMask)
3358 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3359 (int32_t)mHapticChannelCount)
3360 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003361 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003362 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3363 (int32_t)mFrameCount) // sic - added HAL
3364 ;
3365 uint32_t latencyMs;
3366 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3367 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3368 }
3369 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003370}
3371
Andy Hungee58e4a2023-07-07 13:47:37 -07003372ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003373{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003374 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003375 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003376 }
3377 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003378 static const bool stereo_spatialization_property =
3379 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3380 const bool stereo_spatialization_enabled =
3381 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3382 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003383 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3384 for (const sp<IAfTrack>& track : mActiveTracks) {
3385 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3386 allSessionsMetadata[track->sessionId()];
3387 auto backInserter = std::back_inserter(sessionMetadata);
3388 // No track is invalid as this is called after prepareTrack_l in the same
3389 // critical section
3390 track->copyMetadataTo(backInserter);
3391 }
3392 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3393 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3394 metadata.tracks.insert(metadata.tracks.end(),
3395 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3396 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3397 chain->sendMetadata_l(sessionTrackMetadata, {});
3398 }
3399 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3400 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3401 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3402 }
3403 }
3404 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3405 chain->sendMetadata_l(metadata.tracks, {});
3406 }
3407 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3408 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3409 }
3410 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3411 chain->sendMetadata_l(metadata.tracks, {});
3412 }
3413 } else {
3414 auto backInserter = std::back_inserter(metadata.tracks);
3415 for (const sp<IAfTrack>& track : mActiveTracks) {
3416 // No track is invalid as this is called after prepareTrack_l in the same
3417 // critical section
3418 track->copyMetadataTo(backInserter);
3419 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003420 }
Kevin Rocard12381092018-04-11 09:19:59 -07003421 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003422 MetadataUpdate change;
3423 change.playbackMetadataUpdate = metadata.tracks;
3424 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003425}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003426
Andy Hungee58e4a2023-07-07 13:47:37 -07003427void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003428 const StreamOutHalInterface::SourceMetadata& metadata)
3429{
3430 mOutput->stream->updateSourceMetadata(metadata);
3431};
3432
Andy Hungee58e4a2023-07-07 13:47:37 -07003433status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003434 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003435{
3436 if (halFrames == NULL || dspFrames == NULL) {
3437 return BAD_VALUE;
3438 }
Andy Hung972bec12023-08-31 16:13:39 -07003439 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003440 if (initCheck() != NO_ERROR) {
3441 return INVALID_OPERATION;
3442 }
Andy Hung818e7a32016-02-16 18:08:07 -08003443 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003444 *halFrames = framesWritten;
3445
3446 if (isSuspended()) {
3447 // return an estimation of rendered frames when the output is suspended
3448 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003449 *dspFrames = (uint32_t)
3450 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003451 return NO_ERROR;
3452 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003453 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003454 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003455 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003456 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003457 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003458 }
3459}
3460
Andy Hungee58e4a2023-07-07 13:47:37 -07003461product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003462{
3463 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3464 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3465 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003466 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003467 }
3468 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003469 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003470 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003471 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003472 }
3473 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003474 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003475}
3476
3477
Andy Hungee58e4a2023-07-07 13:47:37 -07003478AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003479{
Andy Hung972bec12023-08-31 16:13:39 -07003480 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003481 return mOutput;
3482}
3483
Andy Hungee58e4a2023-07-07 13:47:37 -07003484AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003485{
Andy Hung972bec12023-08-31 16:13:39 -07003486 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003487 AudioStreamOut *output = mOutput;
3488 mOutput = NULL;
3489 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3490 // must push a NULL and wait for ack
3491 mOutputSink.clear();
3492 mPipeSink.clear();
3493 mNormalSink.clear();
3494 return output;
3495}
3496
Andy Hungc5007f82023-08-29 14:26:09 -07003497// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003498sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003499{
3500 if (mOutput == NULL) {
3501 return NULL;
3502 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003503 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003504}
3505
Andy Hungee58e4a2023-07-07 13:47:37 -07003506uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003507{
3508 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3509}
3510
Andy Hungee58e4a2023-07-07 13:47:37 -07003511status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003512{
3513 if (!isValidSyncEvent(event)) {
3514 return BAD_VALUE;
3515 }
3516
Andy Hung972bec12023-08-31 16:13:39 -07003517 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003518
3519 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003520 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003521 if (event->triggerSession() == track->sessionId()) {
3522 (void) track->setSyncEvent(event);
3523 return NO_ERROR;
3524 }
3525 }
3526
3527 return NAME_NOT_FOUND;
3528}
3529
Andy Hungee58e4a2023-07-07 13:47:37 -07003530bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003531{
3532 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3533}
3534
Andy Hungee58e4a2023-07-07 13:47:37 -07003535void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003536 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003537{
Andy Hungfe726a62018-09-27 15:17:25 -07003538 // Miscellaneous track cleanup when removed from the active list,
3539 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003540#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003541 for (const auto& track : tracksToRemove) {
3542 if (track->isExternalTrack()) {
3543 // to track the speaker usage
3544 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003545 }
3546 }
Andy Hungfe726a62018-09-27 15:17:25 -07003547#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003548}
3549
Andy Hungee58e4a2023-07-07 13:47:37 -07003550void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003551{
3552 if (!mMasterMute) {
3553 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003554 if (mOutDeviceTypeAddrs.empty()) {
3555 ALOGD("ro.audio.silent is ignored since no output device is set");
3556 return;
3557 }
Andy Hungab65b182023-09-06 19:41:47 -07003558 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003559 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3560 return;
3561 }
Eric Laurent81784c32012-11-19 14:55:58 -08003562 if (property_get("ro.audio.silent", value, "0") > 0) {
3563 char *endptr;
3564 unsigned long ul = strtoul(value, &endptr, 0);
3565 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003566 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003567 // The setprop command will not allow a property to be changed after
3568 // the first time it is set, so we don't have to worry about un-muting.
3569 setMasterMute_l(true);
3570 }
3571 }
3572 }
3573}
3574
3575// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003576ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003577{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003578 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003579 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003581 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003582
3583 // If an NBAIO sink is present, use it to write the normal mixer's submix
3584 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003585
Andy Hung010a1a12014-03-13 13:57:33 -07003586 const size_t count = mBytesRemaining / mFrameSize;
3587
Simon Wilson2d590962012-11-29 15:18:50 -08003588 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003589 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003590 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003591 if (screenState != mScreenState) {
3592 mScreenState = screenState;
3593 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3594 if (pipe != NULL) {
3595 pipe->setAvgFrames((mScreenState & 1) ?
3596 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3597 }
3598 }
Andy Hung010a1a12014-03-13 13:57:33 -07003599 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003600 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003601
Eric Laurent81784c32012-11-19 14:55:58 -08003602 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003603 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003604
Andy Hung8946a282018-04-19 20:04:56 -07003605#ifdef TEE_SINK
3606 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3607#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003608 } else {
3609 bytesWritten = framesWritten;
3610 }
3611 // otherwise use the HAL / AudioStreamOut directly
3612 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003613 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003614
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003616 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3617 mWriteAckSequence += 2;
3618 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003619 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003620 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003621 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003622 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003623 // FIXME We should have an implementation of timestamps for direct output threads.
3624 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003625 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003626 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003627
Eric Laurentbfb1b832013-01-07 09:53:42 -08003628 if (mUseAsyncWrite &&
3629 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3630 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003631 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003632 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003633 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003634 }
Eric Laurent81784c32012-11-19 14:55:58 -08003635 }
3636
Eric Laurent81784c32012-11-19 14:55:58 -08003637 mNumWrites++;
3638 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003639 if (mStandby) {
3640 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003641 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003642 mStandby = false;
3643 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 return bytesWritten;
3645}
3646
Andy Hungc5007f82023-08-29 14:26:09 -07003647// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003648void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003649 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003650{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003651 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003652 if (outputSink != nullptr) {
3653 outputSink->startMelComputation(processor);
3654 }
Vlad Popab042ee62022-10-20 18:05:00 +02003655}
3656
Andy Hungc5007f82023-08-29 14:26:09 -07003657// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003658void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003659{
3660 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003661 if (outputSink != nullptr) {
3662 outputSink->stopMelComputation();
3663 }
Vlad Popab042ee62022-10-20 18:05:00 +02003664}
3665
Andy Hungee58e4a2023-07-07 13:47:37 -07003666void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003667{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003668 bool supportsDrain = false;
3669 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003670 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3671 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003672 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3673 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003674 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003675 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003676 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003677 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003678 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003679 }
3680}
3681
Andy Hungee58e4a2023-07-07 13:47:37 -07003682void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003683{
Eric Laurent275e8e92014-11-30 15:14:47 -08003684 {
Andy Hung972bec12023-08-31 16:13:39 -07003685 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003686 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003687 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003688 track->invalidate();
3689 }
Andy Hungdae27702016-10-31 14:01:16 -07003690 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3691 // After we exit there are no more track changes sent to BatteryNotifier
3692 // because that requires an active threadLoop.
3693 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3694 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003695 }
Eric Laurent81784c32012-11-19 14:55:58 -08003696}
3697
3698/*
3699The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003700 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003701 - mActiveSleepTimeUs from activeSleepTimeUs()
3702 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003703 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3704 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003705 - maxPeriod from frame count and sample rate (MIXER only)
3706
3707The parameters that affect these derived values are:
3708 - frame count
3709 - frame size
3710 - sample rate
3711 - device type: A2DP or not
3712 - device latency
3713 - format: PCM or not
3714 - active sleep time
3715 - idle sleep time
3716*/
3717
Andy Hungee58e4a2023-07-07 13:47:37 -07003718void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003719{
Andy Hung25c2dac2014-02-27 14:56:00 -08003720 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003721 mActiveSleepTimeUs = activeSleepTimeUs();
3722 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003723
Andy Hung8fe87eb2023-07-20 21:31:38 -07003724 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003725
Eric Laurent42537be2016-01-08 17:16:42 -08003726 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3727 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003728 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003729 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3730 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3731 }
3732 }
Eric Laurent81784c32012-11-19 14:55:58 -08003733}
3734
Andy Hungee58e4a2023-07-07 13:47:37 -07003735bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003736{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003737 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003738 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003739 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003740 size_t size = mTracks.size();
3741 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003742 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003743 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003744 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003745 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003746 }
3747 }
Eric Laurent13084622016-05-17 10:51:49 -07003748 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003749}
3750
Andy Hungee58e4a2023-07-07 13:47:37 -07003751void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003752{
Andy Hung972bec12023-08-31 16:13:39 -07003753 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003754 invalidateTracks_l(streamType);
3755}
3756
Andy Hungee58e4a2023-07-07 13:47:37 -07003757void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003758 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003759 invalidateTracks_l(portIds);
3760}
3761
Andy Hungee58e4a2023-07-07 13:47:37 -07003762bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003763 bool trackMatch = false;
3764 const size_t size = mTracks.size();
3765 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003766 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003767 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3768 t->invalidate();
3769 portIds.erase(t->portId());
3770 trackMatch = true;
3771 }
3772 if (portIds.empty()) {
3773 break;
3774 }
3775 }
3776 return trackMatch;
3777}
3778
jiabinf042b9b2021-05-07 23:46:28 +00003779// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003780IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003781 audio_port_handle_t trackPortId) {
3782 for (size_t i = 0; i < mTracks.size(); i++) {
3783 if (mTracks[i]->portId() == trackPortId) {
3784 return mTracks[i].get();
3785 }
3786 }
3787 return nullptr;
3788}
3789
Andy Hungee58e4a2023-07-07 13:47:37 -07003790status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003791{
Glenn Kastend848eb42016-03-08 13:42:11 -08003792 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003793 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003794 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003795
Andy Hungd3639922022-04-28 18:00:49 -07003796 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003797 if (!audio_is_global_session(session)) {
3798 // player sessions on a spatializer output will use a dedicated input buffer and
3799 // will either output multi channel to mEffectBuffer if the track is spatilaized
3800 // or stereo to mPostSpatializerBuffer if not spatialized.
3801 uint32_t channelMask;
3802 bool isSessionSpatialized =
3803 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3804 if (isSessionSpatialized) {
3805 channelMask = mMixerChannelMask;
3806 } else {
3807 channelMask = mChannelMask;
3808 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003809 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003810 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003811 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003812 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003813 &halInBuffer);
3814 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003815
Andy Hung583043b2023-07-17 17:05:00 -07003816 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003817 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3818 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3819 &halOutBuffer);
3820 if (result != OK) return result;
3821
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003822 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003823
Mikhail Naganov022b9952017-01-04 16:36:51 -08003824 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3825 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003826 } else {
3827 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3828 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3829 // mPostSpatializerBuffer as output buffer
3830 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003831 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003832 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3833 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003834 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003835 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3836 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003837
Eric Laurentb62d0362021-10-26 17:40:18 +02003838 if (session == AUDIO_SESSION_DEVICE) {
3839 halInBuffer = halOutBuffer;
3840 }
3841 }
3842 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003843 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003844 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3845 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3846 &halInBuffer);
3847 if (result != OK) return result;
3848 halOutBuffer = halInBuffer;
3849 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3850 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003851 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003852 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003853 // Only one effect chain can be present in direct output thread and it uses
3854 // the sink buffer as input
3855 if (mType != DIRECT) {
3856 size_t numSamples = mNormalFrameCount
3857 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3858 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003859 const status_t allocateStatus =
3860 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003861 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003862 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003863 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003864
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003865 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003866 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3867 buffer, session);
3868 }
3869 }
3870 }
3871
3872 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003873 // Attach all tracks with same session ID to this chain.
3874 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003875 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003876 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003877 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3878 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003879 track->setMainBuffer(buffer);
3880 chain->incTrackCnt();
3881 }
3882 }
3883
3884 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003885 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003886 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003887 ALOGV("addEffectChain_l() activating track %p on session %d",
3888 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003889 chain->incActiveTrackCnt();
3890 }
3891 }
3892 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003893
Eric Laurentaaa44472014-09-12 17:41:50 -07003894 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003895 chain->setInBuffer(halInBuffer);
3896 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003897 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3898 // chains list in order to be processed last as it contains output device effects.
3899 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3900 // processing effects specific to an output stream before effects applied to all streams
3901 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003902 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3903 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003904 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003905 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003906 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003907 // Effect chain for other sessions are inserted at beginning of effect
3908 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003909 // sessions is not important.
3910 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003911 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3912 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003913 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003914 size_t size = mEffectChains.size();
3915 size_t i = 0;
3916 for (i = 0; i < size; i++) {
3917 if (mEffectChains[i]->sessionId() < session) {
3918 break;
3919 }
3920 }
3921 mEffectChains.insertAt(chain, i);
3922 checkSuspendOnAddEffectChain_l(chain);
3923
3924 return NO_ERROR;
3925}
3926
Andy Hungee58e4a2023-07-07 13:47:37 -07003927size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003928{
Glenn Kastend848eb42016-03-08 13:42:11 -08003929 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003930
3931 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3932
3933 for (size_t i = 0; i < mEffectChains.size(); i++) {
3934 if (chain == mEffectChains[i]) {
3935 mEffectChains.removeAt(i);
3936 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003937 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003938 if (session == track->sessionId()) {
3939 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3940 chain.get(), session);
3941 chain->decActiveTrackCnt();
3942 }
3943 }
3944
3945 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003946 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003947 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003948 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003949 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003950 chain->decTrackCnt();
3951 }
3952 }
3953 break;
3954 }
3955 }
3956 return mEffectChains.size();
3957}
3958
Andy Hungee58e4a2023-07-07 13:47:37 -07003959status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003960 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003961{
Andy Hung972bec12023-08-31 16:13:39 -07003962 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003963 return attachAuxEffect_l(track, EffectId);
3964}
3965
Andy Hungee58e4a2023-07-07 13:47:37 -07003966status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003967 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003968{
3969 status_t status = NO_ERROR;
3970
3971 if (EffectId == 0) {
3972 track->setAuxBuffer(0, NULL);
3973 } else {
3974 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003975 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003976 if (effect != 0) {
3977 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3978 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3979 } else {
3980 status = INVALID_OPERATION;
3981 }
3982 } else {
3983 status = BAD_VALUE;
3984 }
3985 }
3986 return status;
3987}
3988
Andy Hungee58e4a2023-07-07 13:47:37 -07003989void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003990{
3991 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003992 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003993 if (track->auxEffectId() == effectId) {
3994 attachAuxEffect_l(track, 0);
3995 }
3996 }
3997}
3998
Andy Hungee58e4a2023-07-07 13:47:37 -07003999bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07004000NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08004001{
Andy Hung78d8d952023-05-30 18:10:23 -07004002 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08004003
Andy Hung077d62e2023-10-03 10:49:34 -07004004 if (mType == SPATIALIZER) {
4005 const pid_t tid = getTid();
4006 if (tid == -1) { // odd: we are here, we must be a running thread.
4007 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4008 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004009 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4010 if (priorityBoost > 0) {
4011 stream()->setHalThreadPriority(priorityBoost);
4012 }
Andy Hung077d62e2023-10-03 10:49:34 -07004013 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004014 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4015 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4016 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4017 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4018 // only on ARC.
4019 const pid_t tid = getTid();
4020 if (tid == -1) {
4021 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4022 } else {
4023 const status_t status = requestPriority(getpid(),
4024 tid,
4025 kPriorityPlaybackThreadArc,
4026 false /* isForApp */,
4027 true /* asynchronous */);
4028 if (status != OK) {
4029 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4030 status);
4031 } else {
4032 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4033 }
4034 }
Andy Hung077d62e2023-10-03 10:49:34 -07004035 }
4036
Andy Hung8d31fd22023-06-26 19:20:57 -07004037 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004038
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004039 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004040 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004041
4042 // MIXER
4043 nsecs_t lastWarning = 0;
4044
4045 // DUPLICATING
4046 // FIXME could this be made local to while loop?
4047 writeFrames = 0;
4048
4049 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004050 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004051
Andy Hungd3639922022-04-28 18:00:49 -07004052 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004053 sleepTimeShift = 0;
4054 }
4055
4056 CpuStats cpuStats;
4057 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4058
4059 acquireWakeLock();
4060
Glenn Kasteneef598c2017-04-03 14:41:13 -07004061 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4062 // thread associated with this PlaybackThread.
4063 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4064 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004065 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4066 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004067 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004068 const char *logString = NULL;
4069
rago1bb90822017-05-02 18:31:48 -07004070 // Estimated time for next buffer to be written to hal. This is used only on
4071 // suspended mode (for now) to help schedule the wait time until next iteration.
4072 nsecs_t timeLoopNextNs = 0;
4073
Eric Laurent664539d2013-09-23 18:24:31 -07004074 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004075
Andy Hung2dbffc22018-08-08 18:50:41 -07004076 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004077
Eric Laurentb3f315a2021-07-13 15:09:05 +02004078 sendCheckOutputStageEffectsEvent();
4079
Andy Hung446f4df2019-02-21 12:26:41 -08004080 // loopCount is used for statistics and diagnostics.
4081 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004082 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004083 // Log merge requests are performed during AudioFlinger binder transactions, but
4084 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004085 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004086
Eric Laurent81784c32012-11-19 14:55:58 -08004087 cpuStats.sample(myName);
4088
Andy Hung116bc262023-06-20 18:56:17 -07004089 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004090 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004091 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004092 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004093
Andy Hung2dbffc22018-08-08 18:50:41 -07004094 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4095 //
Andy Hungc5007f82023-08-29 14:26:09 -07004096 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004097 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004098 // Here, we try for the AF lock, but do not block on it as the latency
4099 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004100 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004101 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004102 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004103 status_t status = INVALID_OPERATION;
4104 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004105 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004106 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004107 && swPatches.size() > 0) {
4108 status = swPatches[0].getLatencyMs_l(&latencyMs);
4109 downstreamPatchHandle = swPatches[0].getPatchHandle();
4110 }
4111 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004112 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004113 lastDownstreamPatchHandle = downstreamPatchHandle;
4114 }
4115 if (status == OK) {
4116 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004117 // latency of 5 seconds).
4118 const double minLatency = 0., maxLatency = 5000.;
4119 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004120 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004121 } else {
4122 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004123 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004124 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004125 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004126 }
Andy Hung583043b2023-07-17 17:05:00 -07004127 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004128 }
4129 } else {
4130 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4131 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004132 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004133 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4134 }
4135 }
4136
Eric Laurentb3f315a2021-07-13 15:09:05 +02004137 if (mCheckOutputStageEffects.exchange(false)) {
4138 checkOutputStageEffects();
4139 }
4140
Vlad Popa7e81cea2023-01-19 16:34:16 +01004141 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004142 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004143
Andy Hungc5007f82023-08-29 14:26:09 -07004144 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004145
Eric Laurent021cf962014-05-13 10:18:14 -07004146 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004147 if (mCheckOutputStageEffects.load()) {
4148 continue;
4149 }
Eric Laurent10351942014-05-08 18:49:52 -07004150
Andy Hungc5007f82023-08-29 14:26:09 -07004151 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004152 if (logString != NULL) {
4153 mNBLogWriter->logTimestamp();
4154 mNBLogWriter->log(logString);
4155 logString = NULL;
4156 }
4157
Dean Wheatley12473e92021-03-18 23:00:55 +11004158 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004159
Eric Laurent81784c32012-11-19 14:55:58 -08004160 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004161 if (mSignalPending) {
4162 // A signal was raised while we were unlocked
4163 mSignalPending = false;
4164 } else if (waitingAsyncCallback_l()) {
4165 if (exitPending()) {
4166 break;
4167 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004168 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004169 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004170 releaseWakeLock_l();
4171 released = true;
4172 }
Andy Hung10cbff12017-02-21 17:30:14 -08004173
4174 const int64_t waitNs = computeWaitTimeNs_l();
4175 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004176 std::cv_status cvstatus =
4177 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4178 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004179 mSignalPending = true; // if timeout recheck everything
4180 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004181 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004182 if (released) {
4183 acquireWakeLock_l();
4184 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004185 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4186 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004187
4188 continue;
4189 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004190 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004191 isSuspended()) {
4192 // put audio hardware into standby after short delay
4193 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004194
4195 threadLoop_standby();
4196
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004197 // This is where we go into standby
4198 if (!mStandby) {
4199 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004200 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004201 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004202 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004203 }
Andy Hungd0979812019-02-21 15:51:44 -08004204 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004205 }
4206
Eric Tan39ec8d62018-07-24 09:49:29 -07004207 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004208 // we're about to wait, flush the binder command buffer
4209 IPCThreadState::self()->flushCommands();
4210
4211 clearOutputTracks();
4212
4213 if (exitPending()) {
4214 break;
4215 }
4216
4217 releaseWakeLock_l();
4218 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004219 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004220 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004221 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004222 acquireWakeLock_l();
4223
4224 mMixerStatus = MIXER_IDLE;
4225 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4226 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004227 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004228 checkSilentMode_l();
4229
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004230 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4231 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004232 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004233 sleepTimeShift = 0;
4234 }
4235
4236 continue;
4237 }
4238 }
Eric Laurent81784c32012-11-19 14:55:58 -08004239 // mMixerStatusIgnoringFastTracks is also updated internally
4240 mMixerStatus = prepareTracks_l(&tracksToRemove);
4241
Andy Hungab65b182023-09-06 19:41:47 -07004242 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004243
Vlad Popa7e81cea2023-01-19 16:34:16 +01004244 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004245
Andy Hungf302e812024-01-26 11:55:15 -08004246 // Acquire a local copy of active tracks with lock (release w/o lock).
4247 //
4248 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4249 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4250 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4251 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4252
4253 setHalLatencyMode_l();
4254
4255 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4256 // so this is done before we lock our effect chains.
4257 for (const auto& track : mActiveTracks) {
4258 track->updateTeePatches_l();
4259 }
4260
4261 // signal actual start of output stream when the render position reported by
4262 // the kernel starts moving.
4263 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4264 && (mKernelPositionOnStandby
4265 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4266 mHalStarted = true;
4267 mWaitHalStartCV.notify_all();
4268 }
4269
Eric Laurent81784c32012-11-19 14:55:58 -08004270 // prevent any changes in effect chain list and in each effect chain
4271 // during mixing and effect process as the audio buffers could be deleted
4272 // or modified if an effect is created or deleted
4273 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004274
4275 // Determine which session to pick up haptic data.
4276 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004277 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004278 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004279 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004280 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004281 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004282 if (effectChain != nullptr
4283 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004284 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004285 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004286 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004287 break;
4288 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004289 if (activeHapticSessionId == AUDIO_SESSION_NONE
4290 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004291 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004292 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004293 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004294 }
4295 }
4296 }
Andy Hungc5007f82023-08-29 14:26:09 -07004297 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004298
Eric Laurentbfb1b832013-01-07 09:53:42 -08004299 if (mBytesRemaining == 0) {
4300 mCurrentWriteLength = 0;
4301 if (mMixerStatus == MIXER_TRACKS_READY) {
4302 // threadLoop_mix() sets mCurrentWriteLength
4303 threadLoop_mix();
4304 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4305 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004306 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004307 // must be written to HAL
4308 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004309 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004310 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004311
4312 // Tally underrun frames as we are inserting 0s here.
4313 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004314 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004315 && !track->isStopped()
4316 && !track->isPaused()
4317 && !track->isTerminated()) {
4318 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4319 __func__, track->id(), track->getTrackStateAsString(),
4320 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004321 track->audioTrackServerProxy()->tallyUnderrunFrames(
4322 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004323 }
4324 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004325 }
4326 }
Andy Hung98ef9782014-03-04 14:46:50 -08004327 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004328 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004329 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004330 // or mSinkBuffer (if there are no effects and there is no data already copied to
4331 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004332 //
4333 // This is done pre-effects computation; if effects change to
4334 // support higher precision, this needs to move.
4335 //
4336 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004337 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004338 uint32_t mixerChannelCount = mEffectBufferValid ?
4339 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004340 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004341 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4342 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4343
David Li88ee0902022-06-22 10:01:21 +08004344 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4345 // do these processes after effects are applied.
4346 if (!mEffectBufferValid) {
4347 // mono blend occurs for mixer threads only (not direct or offloaded)
4348 // and is handled here if we're going directly to the sink.
4349 if (requireMonoBlend()) {
4350 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4351 mNormalFrameCount, true /*limit*/);
4352 }
Andy Hung2ddee192015-12-18 17:34:44 -08004353
David Li88ee0902022-06-22 10:01:21 +08004354 if (!hasFastMixer()) {
4355 // Balance must take effect after mono conversion.
4356 // We do it here if there is no FastMixer.
4357 // mBalance detects zero balance within the class for speed
4358 // (not needed here).
4359 mBalance.setBalance(mMasterBalance.load());
4360 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4361 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004362 }
4363
Andy Hung98ef9782014-03-04 14:46:50 -08004364 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004365 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004366
4367 // If we're going directly to the sink and there are haptic channels,
4368 // we should adjust channels as the sample data is partially interleaved
4369 // in this case.
4370 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4371 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4372 mChannelCount + mHapticChannelCount,
4373 audio_bytes_per_sample(format),
4374 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4375 }
Andy Hung98ef9782014-03-04 14:46:50 -08004376 }
4377
Eric Laurentbfb1b832013-01-07 09:53:42 -08004378 mBytesRemaining = mCurrentWriteLength;
4379 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004380 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4381 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4382 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4383 mBytesWritten += mBytesRemaining;
4384 mFramesWritten += framesRemaining;
4385 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004386 mBytesRemaining = 0;
4387 }
Eric Laurent81784c32012-11-19 14:55:58 -08004388
Eric Laurentbfb1b832013-01-07 09:53:42 -08004389 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004390 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004391 for (size_t i = 0; i < effectChains.size(); i ++) {
4392 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004393 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004394 if (activeHapticSessionId != AUDIO_SESSION_NONE
4395 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004396 // Haptic data is active in this case, copy it directly from
4397 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004398 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4399 audio_channel_count_from_out_mask(mMixerChannelMask) :
4400 mChannelCount;
4401 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4402 hapticSessionChannelCount = mChannelCount;
4403 }
4404
jiabin47affe52019-04-04 18:02:07 -07004405 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004406 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004407 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004408 memcpy_by_audio_format(
4409 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004410 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004411 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004412 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004413 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004414 }
Eric Laurent81784c32012-11-19 14:55:58 -08004415 }
4416 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004417 // Process effect chains for offloaded thread even if no audio
4418 // was read from audio track: process only updates effect state
4419 // and thus does have to be synchronized with audio writes but may have
4420 // to be called while waiting for async write callback
4421 if (mType == OFFLOAD) {
4422 for (size_t i = 0; i < effectChains.size(); i ++) {
4423 effectChains[i]->process_l();
4424 }
4425 }
Eric Laurent81784c32012-11-19 14:55:58 -08004426
Andy Hung98ef9782014-03-04 14:46:50 -08004427 // Only if the Effects buffer is enabled and there is data in the
4428 // Effects buffer (buffer valid), we need to
4429 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004430 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004431 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004432 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004433 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004434 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004435 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004436 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004437 }
4438
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004439 if (!hasFastMixer()) {
4440 // Balance must take effect after mono conversion.
4441 // We do it here if there is no FastMixer.
4442 // mBalance detects zero balance within the class for speed (not needed here).
4443 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004444 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004445 }
4446
Eric Laurentb62d0362021-10-26 17:40:18 +02004447 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4448 // mPostSpatializerBuffer if the haptics track is spatialized.
4449 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4450 // For other thread types, the haptics channels are already in mEffectBuffer.
4451 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4452 const size_t srcBufferSize = mNormalFrameCount *
4453 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4454 mEffectBufferFormat);
4455 const size_t dstBufferSize = mNormalFrameCount
4456 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4457
4458 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4459 mEffectBufferFormat,
4460 (uint8_t*)mEffectBuffer + srcBufferSize,
4461 mEffectBufferFormat,
4462 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004463 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004464 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4465 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4466 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4467 // Clamp PCM float values more than this distance from 0 to insulate
4468 // a HAL which doesn't handle NaN correctly.
4469 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4470 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4471 static_cast<const float*>(effectBuffer),
4472 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4473 } else {
4474 memcpy_by_audio_format(mSinkBuffer, mFormat,
4475 effectBuffer, mEffectBufferFormat, framesToCopy);
4476 }
jiabin245cdd92018-12-07 17:55:15 -08004477 // The sample data is partially interleaved when haptic channels exist,
4478 // we need to adjust channels here.
4479 if (mHapticChannelCount > 0) {
4480 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4481 mChannelCount + mHapticChannelCount,
4482 audio_bytes_per_sample(mFormat),
4483 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4484 }
Andy Hung98ef9782014-03-04 14:46:50 -08004485 }
4486
Eric Laurent81784c32012-11-19 14:55:58 -08004487 // enable changes in effect chain
4488 unlockEffectChains(effectChains);
4489
Vlad Popafce10862023-02-03 10:37:07 +01004490 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004491 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004492 metadataUpdate.playbackMetadataUpdate);
4493 }
4494
Eric Laurentbfb1b832013-01-07 09:53:42 -08004495 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004496 // mSleepTimeUs == 0 means we must write to audio hardware
4497 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004498 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004499 // writePeriodNs is updated >= 0 when ret > 0.
4500 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004501 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004502 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004503 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004504 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004505 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004506 if (ret < 0) {
4507 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004508 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004509 mBytesWritten += ret;
4510 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004511 const int64_t frames = ret / mFrameSize;
4512 mFramesWritten += frames;
4513
4514 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4515 // process information relating to write time.
4516 if (audio_has_proportional_frames(mFormat)) {
4517 // we are in a continuous mixing cycle
4518 if (mMixerStatus == MIXER_TRACKS_READY &&
4519 loopCount == lastLoopCountWritten + 1) {
4520
4521 const double jitterMs =
4522 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4523 {frames, writePeriodNs},
4524 {0, 0} /* lastTimestamp */, mSampleRate);
4525 const double processMs =
4526 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4527
Andy Hung972bec12023-08-31 16:13:39 -07004528 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004529 mIoJitterMs.add(jitterMs);
4530 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004531
4532 if (mPipeSink.get() != nullptr) {
4533 // Using the Monopipe availableToWrite, we estimate the current
4534 // buffer size.
4535 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4536 const ssize_t
4537 availableToWrite = mPipeSink->availableToWrite();
4538 const size_t pipeFrames = monoPipe->maxFrames();
4539 const size_t
4540 remainingFrames = pipeFrames - max(availableToWrite, 0);
4541 mMonopipePipeDepthStats.add(remainingFrames);
4542 }
Andy Hung446f4df2019-02-21 12:26:41 -08004543 }
4544
4545 // write blocked detection
4546 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004547 if ((mType == MIXER || mType == SPATIALIZER)
4548 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004549 mNumDelayedWrites++;
4550 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4551 ATRACE_NAME("underrun");
4552 ALOGW("write blocked for %lld msecs, "
4553 "%d delayed writes, thread %d",
4554 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4555 mNumDelayedWrites, mId);
4556 lastWarning = lastIoEndNs;
4557 }
4558 }
4559 }
4560 // update timing info.
4561 mLastIoBeginNs = lastIoBeginNs;
4562 mLastIoEndNs = lastIoEndNs;
4563 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004564 }
4565 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4566 (mMixerStatus == MIXER_DRAIN_ALL)) {
4567 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004568 }
Andy Hungd3639922022-04-28 18:00:49 -07004569 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004570
4571 if (mThreadThrottle
4572 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004573 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004574 // Limit MixerThread data processing to no more than twice the
4575 // expected processing rate.
4576 //
4577 // This helps prevent underruns with NuPlayer and other applications
4578 // which may set up buffers that are close to the minimum size, or use
4579 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4580 //
4581 // The throttle smooths out sudden large data drains from the device,
4582 // e.g. when it comes out of standby, which often causes problems with
4583 // (1) mixer threads without a fast mixer (which has its own warm-up)
4584 // (2) minimum buffer sized tracks (even if the track is full,
4585 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004586 //
4587 // Total time spent in last processing cycle equals time spent in
4588 // 1. threadLoop_write, as well as time spent in
4589 // 2. threadLoop_mix (significant for heavy mixing, especially
4590 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004591
Andy Hung446f4df2019-02-21 12:26:41 -08004592 // it's OK if deltaMs is an overestimate.
4593
4594 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004595
Ivan Lozanoea04d392017-11-07 14:37:07 -08004596 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004597 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004598 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004599
Andy Hung08fb1742015-05-31 23:22:10 -07004600 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004601 // notify of throttle start on verbose log
4602 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4603 "mixer(%p) throttle begin:"
4604 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004605 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004606 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004607 // Throttle must be attributed to the previous mixer loop's write time
4608 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004609 // This also ensures proper timing statistics.
4610 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004611 } else {
4612 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4613 if (diff > 0) {
4614 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004615 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004616 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004617 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004618 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004619 outDeviceTypes_l(),
4620 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004621 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004622 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4623 }
Andy Hung08fb1742015-05-31 23:22:10 -07004624 }
4625 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004626 }
Eric Laurent81784c32012-11-19 14:55:58 -08004627
Eric Laurentbfb1b832013-01-07 09:53:42 -08004628 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004629 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004630 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004631 // suspended requires accurate metering of sleep time.
4632 if (isSuspended()) {
4633 // advance by expected sleepTime
4634 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4635 const nsecs_t nowNs = systemTime();
4636
4637 // compute expected next time vs current time.
4638 // (negative deltas are treated as delays).
4639 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4640 if (deltaNs < -kMaxNextBufferDelayNs) {
4641 // Delays longer than the max allowed trigger a reset.
4642 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4643 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4644 timeLoopNextNs = nowNs + deltaNs;
4645 } else if (deltaNs < 0) {
4646 // Delays within the max delay allowed: zero the delta/sleepTime
4647 // to help the system catch up in the next iteration(s)
4648 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4649 deltaNs = 0;
4650 }
4651 // update sleep time (which is >= 0)
4652 mSleepTimeUs = deltaNs / 1000;
4653 }
Eric Laurente93cc032016-05-05 10:15:10 -07004654 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004655 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004656 }
Glenn Kastene7754022014-10-31 12:11:26 -07004657 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004658 }
Eric Laurent81784c32012-11-19 14:55:58 -08004659 }
4660
4661 // Finally let go of removed track(s), without the lock held
4662 // since we can't guarantee the destructors won't acquire that
4663 // same lock. This will also mutate and push a new fast mixer state.
4664 threadLoop_removeTracks(tracksToRemove);
4665 tracksToRemove.clear();
4666
4667 // FIXME I don't understand the need for this here;
4668 // it was in the original code but maybe the
4669 // assignment in saveOutputTracks() makes this unnecessary?
4670 clearOutputTracks();
4671
4672 // Effect chains will be actually deleted here if they were removed from
4673 // mEffectChains list during mixing or effects processing
4674 effectChains.clear();
4675
4676 // FIXME Note that the above .clear() is no longer necessary since effectChains
4677 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004678
4679 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004680 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004681 mThreadloopExecutor.process(); // process any remaining deferred actions.
4682 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004683
Eric Laurentbfb1b832013-01-07 09:53:42 -08004684 threadLoop_exit();
4685
Eric Laurentcf817a22014-08-04 20:36:31 -07004686 if (!mStandby) {
4687 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004688 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004689 }
4690
4691 releaseWakeLock();
4692
4693 ALOGV("Thread %p type %d exiting", this, mType);
4694 return false;
4695}
4696
Andy Hungee58e4a2023-07-07 13:47:37 -07004697void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004698{
Dean Wheatley12473e92021-03-18 23:00:55 +11004699 if (mStandby) {
4700 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4701 return;
4702 } else if (mHwPaused) {
4703 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4704 return;
4705 }
4706
4707 // Gather the framesReleased counters for all active tracks,
4708 // and associate with the sink frames written out. We need
4709 // this to convert the sink timestamp to the track timestamp.
4710 bool kernelLocationUpdate = false;
4711 ExtendedTimestamp timestamp; // use private copy to fetch
4712
4713 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4714 // HAL may be draining some small duration buffered data for fade out.
4715 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4716 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4717 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4718 mSampleRate);
4719
Andy Hungab65b182023-09-06 19:41:47 -07004720 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004721 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4722 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4723 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4724 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4725 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4726 = correctedTimestamp.mFrames;
4727 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4728 = correctedTimestamp.mTimeNs;
4729 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4730 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4731 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4732
4733 // Note: Downstream latency only added if timestamp correction enabled.
4734 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4735 const int64_t newPosition =
4736 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4737 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4738 // prevent retrograde
4739 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4740 newPosition,
4741 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4742 - mSuspendedFrames));
4743 }
4744 }
4745
4746 // We always fetch the timestamp here because often the downstream
4747 // sink will block while writing.
4748
4749 // We keep track of the last valid kernel position in case we are in underrun
4750 // and the normal mixer period is the same as the fast mixer period, or there
4751 // is some error from the HAL.
4752 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4753 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4754 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4755 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4756 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4757
4758 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4759 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4760 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4761 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4762 }
4763
4764 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4765 kernelLocationUpdate = true;
4766 } else {
4767 ALOGVV("getTimestamp error - no valid kernel position");
4768 }
4769
4770 // copy over kernel info
4771 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4772 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4773 + mSuspendedFrames; // add frames discarded when suspended
4774 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4775 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4776 } else {
4777 mTimestampVerifier.error();
4778 }
4779
4780 // mFramesWritten for non-offloaded tracks are contiguous
4781 // even after standby() is called. This is useful for the track frame
4782 // to sink frame mapping.
4783 bool serverLocationUpdate = false;
4784 if (mFramesWritten != mLastFramesWritten) {
4785 serverLocationUpdate = true;
4786 mLastFramesWritten = mFramesWritten;
4787 }
4788 // Only update timestamps if there is a meaningful change.
4789 // Either the kernel timestamp must be valid or we have written something.
4790 if (kernelLocationUpdate || serverLocationUpdate) {
4791 if (serverLocationUpdate) {
4792 // use the time before we called the HAL write - it is a bit more accurate
4793 // to when the server last read data than the current time here.
4794 //
4795 // If we haven't written anything, mLastIoBeginNs will be -1
4796 // and we use systemTime().
4797 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4798 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004799 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004800 }
4801
Andy Hung8d31fd22023-06-26 19:20:57 -07004802 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004803 if (!t->isFastTrack()) {
4804 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004805 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004806 mFramesWritten,
4807 mSampleRate,
4808 mTimestamp);
4809 }
4810 }
4811 }
4812
4813 if (audio_has_proportional_frames(mFormat)) {
4814 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4815 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4816 mLatencyMs.add(latencyMs);
4817 }
4818 }
4819#if 0
4820 // logFormat example
4821 if (z % 100 == 0) {
4822 timespec ts;
4823 clock_gettime(CLOCK_MONOTONIC, &ts);
4824 LOGT("This is an integer %d, this is a float %f, this is my "
4825 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4826 LOGT("A deceptive null-terminated string %\0");
4827 }
4828 ++z;
4829#endif
4830}
4831
Andy Hungc5007f82023-08-29 14:26:09 -07004832// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004833void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004834NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004835{
Andy Hung6c498e92023-12-05 17:28:17 -08004836 if (tracksToRemove.empty()) return;
4837
4838 // Block all incoming TrackHandle requests until we are finished with the release.
4839 setThreadBusy_l(true);
4840
Andy Hungfe726a62018-09-27 15:17:25 -07004841 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004842 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004843 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004844 if (chain != 0) {
4845 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4846 __func__, track->id(), chain.get(), track->sessionId());
4847 chain->decActiveTrackCnt();
4848 }
Andy Hung6c498e92023-12-05 17:28:17 -08004849
Andy Hungfe726a62018-09-27 15:17:25 -07004850 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004851 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004852 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004853 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004854 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004855 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004856 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004857 }
Andy Hung6c498e92023-12-05 17:28:17 -08004858 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004859 }
jiabineb3bda02020-06-30 14:07:03 -07004860 if (mHapticChannelCount > 0 &&
4861 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004862 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004863 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004864 // Unlock due to VibratorService will lock for this call and will
4865 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004866 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004867 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004868
4869 // When the track is stop, set the haptic intensity as MUTE
4870 // for the HapticGenerator effect.
4871 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004872 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004873 }
jiabin245cdd92018-12-07 17:55:15 -08004874 }
Andy Hung6c498e92023-12-05 17:28:17 -08004875
4876 // Under lock, the track is removed from the active tracks list.
4877 //
4878 // Once the track is no longer active, the TrackHandle may directly
4879 // modify it as the threadLoop() is no longer responsible for its maintenance.
4880 // Do not modify the track from threadLoop after the mutex is unlocked
4881 // if it is not active.
4882 mActiveTracks.remove(track);
4883
4884 if (track->isTerminated()) {
4885 // remove from our tracks vector
4886 removeTrack_l(track);
4887 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888 }
Andy Hung6c498e92023-12-05 17:28:17 -08004889
4890 // Allow incoming TrackHandle requests. We still hold the mutex,
4891 // so pending TrackHandle requests will occur after we unlock it.
4892 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004893}
Eric Laurent81784c32012-11-19 14:55:58 -08004894
Andy Hungee58e4a2023-07-07 13:47:37 -07004895status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004896{
4897 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004898 ExtendedTimestamp ets;
4899 status_t status = mNormalSink->getTimestamp(ets);
4900 if (status == NO_ERROR) {
4901 status = ets.getBestTimestamp(&timestamp);
4902 }
4903 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004904 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004905 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004906 collectTimestamps_l();
4907 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4908 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004909 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004910 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4911 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4912 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4913 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4914 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004915 }
4916 return INVALID_OPERATION;
4917}
Eric Laurent1c333e22014-05-20 10:48:17 -07004918
Eric Laurenteab90452019-06-24 15:17:46 -07004919// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4920// still applied by the mixer.
4921// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4922// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4923// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004924status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004925{
4926 status_t result = NO_ERROR;
4927 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4928 if (*volume != mLeftVolFloat) {
4929 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004930 // HAL can return INVALID_OPERATION if operation is not supported.
4931 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004932 "Error when setting output stream volume: %d", result);
4933 if (result == NO_ERROR) {
4934 mLeftVolFloat = *volume;
4935 }
4936 }
4937 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4938 // remove stream volume contribution from software volume.
4939 if (mLeftVolFloat == *volume) {
4940 *volume = 1.0f;
4941 }
4942 }
4943 return result;
4944}
4945
Andy Hungee58e4a2023-07-07 13:47:37 -07004946status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004947 audio_patch_handle_t *handle)
4948{
Andy Hungf60abce2016-08-26 11:37:54 -07004949 status_t status;
4950 if (property_get_bool("af.patch_park", false /* default_value */)) {
4951 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4952 // or if HAL does not properly lock against access.
4953 AutoPark<FastMixer> park(mFastMixer);
4954 status = PlaybackThread::createAudioPatch_l(patch, handle);
4955 } else {
4956 status = PlaybackThread::createAudioPatch_l(patch, handle);
4957 }
Eric Laurentb0463942022-12-20 16:31:10 +01004958
4959 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004960 return status;
4961}
4962
Andy Hungee58e4a2023-07-07 13:47:37 -07004963status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004964 audio_patch_handle_t *handle)
4965{
4966 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004967
4968 // store new device and send to effects
4969 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004970 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004971 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004972 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4973 && !mOutput->audioHwDev->supportsAudioPatches(),
4974 "Enumerated device type(%#x) must not be used "
4975 "as it does not support audio patches",
4976 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004977 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004978 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4979 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004980 }
4981
François Gaffie0c280aa2018-07-25 10:02:15 +02004982 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004983#ifdef ADD_BATTERY_DATA
4984 // when changing the audio output device, call addBatteryData to notify
4985 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004986 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004987 uint32_t params = 0;
4988 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004989 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004990 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004991 }
4992
Eric Laurent054d9d32015-04-24 08:48:48 -07004993 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004994 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004995 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4996 }
4997
4998 if (params != 0) {
4999 addBatteryData(params);
5000 }
5001 }
5002#endif
5003
5004 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08005005 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005006 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005007
jiabinc52b1ff2019-10-31 17:20:42 -07005008 // mPatch.num_sinks is not set when the thread is created so that
5009 // the first patch creation triggers an ioConfigChanged callback
5010 bool configChanged = (mPatch.num_sinks == 0) ||
5011 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005012 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005013 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005014 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005015
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005016 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005017 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5018 status = hwDevice->createAudioPatch(patch->num_sources,
5019 patch->sources,
5020 patch->num_sinks,
5021 patch->sinks,
5022 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005024 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005025 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005026 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005027 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005028
5029 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005030 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005031 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005032 // also dispatch to active AudioTracks for MediaMetrics
5033 for (const auto &track : mActiveTracks) {
5034 track->logEndInterval();
5035 track->logBeginInterval(patchSinksAsString);
5036 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005037
Eric Laurente8726fe2015-06-26 09:39:24 -07005038 if (configChanged) {
5039 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5040 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005041 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005042 mActiveTracks.setHasChanged();
5043
Eric Laurent1c333e22014-05-20 10:48:17 -07005044 return status;
5045}
5046
Andy Hungee58e4a2023-07-07 13:47:37 -07005047status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005048{
Andy Hungf60abce2016-08-26 11:37:54 -07005049 status_t status;
5050 if (property_get_bool("af.patch_park", false /* default_value */)) {
5051 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5052 // or if HAL does not properly lock against access.
5053 AutoPark<FastMixer> park(mFastMixer);
5054 status = PlaybackThread::releaseAudioPatch_l(handle);
5055 } else {
5056 status = PlaybackThread::releaseAudioPatch_l(handle);
5057 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005058 return status;
5059}
5060
Andy Hungee58e4a2023-07-07 13:47:37 -07005061status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005062{
5063 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005064
jiabinc52b1ff2019-10-31 17:20:42 -07005065 mPatch = audio_patch{};
5066 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005067
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005068 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005069 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5070 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005071 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005072 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005073 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005074 // Force meteadata update after a route change
5075 mActiveTracks.setHasChanged();
5076
Eric Laurent1c333e22014-05-20 10:48:17 -07005077 return status;
5078}
5079
Andy Hungee58e4a2023-07-07 13:47:37 -07005080void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005081{
Andy Hung972bec12023-08-31 16:13:39 -07005082 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005083 mTracks.add(track);
5084}
5085
Andy Hungee58e4a2023-07-07 13:47:37 -07005086void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005087{
Andy Hung972bec12023-08-31 16:13:39 -07005088 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005089 destroyTrack_l(track);
5090}
5091
Andy Hungee58e4a2023-07-07 13:47:37 -07005092void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005093{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005094 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005095 config->role = AUDIO_PORT_ROLE_SOURCE;
5096 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5097 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005098 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5099 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5100 config->flags.output = mOutput->flags;
5101 }
Eric Laurent83b88082014-06-20 18:31:16 -07005102}
5103
Eric Laurent81784c32012-11-19 14:55:58 -08005104// ----------------------------------------------------------------------------
5105
Andy Hungee58e4a2023-07-07 13:47:37 -07005106/* static */
5107sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005108 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005109 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005110 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005111}
5112
Andy Hung583043b2023-07-17 17:05:00 -07005113MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005114 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005115 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005116 // mAudioMixer below
5117 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005118 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005119 mFastMixerFutex(0),
5120 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005121 // mOutputSink below
5122 // mPipeSink below
5123 // mNormalSink below
5124{
jiabinc52b1ff2019-10-31 17:20:42 -07005125 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005126 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005127 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005128 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5129 mNormalFrameCount);
5130 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5131
Andy Hungfbfc3952015-01-15 13:33:51 -08005132 if (type == DUPLICATING) {
5133 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5134 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5135 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005136 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5137 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005138 return;
5139 }
Eric Laurent81784c32012-11-19 14:55:58 -08005140 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005141 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005142 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005143 const NBAIO_Format offers[1] = {Format_from_SR_C(
5144 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005145#if !LOG_NDEBUG
5146 ssize_t index =
5147#else
5148 (void)
5149#endif
5150 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005151 ALOG_ASSERT(index == 0);
5152
5153 // initialize fast mixer depending on configuration
5154 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005155 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005156 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005157 } else {
5158 switch (kUseFastMixer) {
5159 case FastMixer_Never:
5160 initFastMixer = false;
5161 break;
5162 case FastMixer_Always:
5163 initFastMixer = true;
5164 break;
5165 case FastMixer_Static:
5166 case FastMixer_Dynamic:
5167 initFastMixer = mFrameCount < mNormalFrameCount;
5168 break;
5169 }
5170 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5171 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5172 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005173 }
5174 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005175 audio_format_t fastMixerFormat;
5176 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5177 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5178 } else {
5179 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5180 }
5181 if (mFormat != fastMixerFormat) {
5182 // change our Sink format to accept our intermediate precision
5183 mFormat = fastMixerFormat;
5184 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005185 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005186 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5187 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5188 }
Eric Laurent81784c32012-11-19 14:55:58 -08005189
5190 // create a MonoPipe to connect our submix to FastMixer
5191 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005192
Andy Hung1258c1a2014-05-23 21:22:17 -07005193 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005194 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005195 format.mFormat = fastMixerFormat;
5196 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5197
Eric Laurent81784c32012-11-19 14:55:58 -08005198 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5199 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5200 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5201 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005202 const NBAIO_Format offersFast[1] = {format};
5203 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005204#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005205 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005206#else
5207 (void)
5208#endif
Andy Hung920f6572022-10-06 12:09:49 -07005209 monoPipe->negotiate(offersFast, std::size(offersFast),
5210 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005211 ALOG_ASSERT(index == 0);
5212 monoPipe->setAvgFrames((mScreenState & 1) ?
5213 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5214 mPipeSink = monoPipe;
5215
Eric Laurent81784c32012-11-19 14:55:58 -08005216 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005217 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005218 FastMixerStateQueue *sq = mFastMixer->sq();
5219#ifdef STATE_QUEUE_DUMP
5220 sq->setObserverDump(&mStateQueueObserverDump);
5221 sq->setMutatorDump(&mStateQueueMutatorDump);
5222#endif
5223 FastMixerState *state = sq->begin();
5224 FastTrack *fastTrack = &state->mFastTracks[0];
5225 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5226 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5227 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005228 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5229 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5230 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005231 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005232 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005233 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005234 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005235 fastTrack->mGeneration++;
5236 state->mFastTracksGen++;
5237 state->mTrackMask = 1;
5238 // fast mixer will use the HAL output sink
5239 state->mOutputSink = mOutputSink.get();
5240 state->mOutputSinkGen++;
5241 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005242 // specify sink channel mask when haptic channel mask present as it can not
5243 // be calculated directly from channel count
5244 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005245 ? AUDIO_CHANNEL_NONE
5246 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005247 state->mCommand = FastMixerState::COLD_IDLE;
5248 // already done in constructor initialization list
5249 //mFastMixerFutex = 0;
5250 state->mColdFutexAddr = &mFastMixerFutex;
5251 state->mColdGen++;
5252 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005253 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005254 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005255 sq->end();
5256 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5257
Eric Tan0513b5d2018-09-17 10:32:48 -07005258 NBLog::thread_info_t info;
5259 info.id = mId;
5260 info.type = NBLog::FASTMIXER;
5261 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5262
Eric Laurent81784c32012-11-19 14:55:58 -08005263 // start the fast mixer
5264 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5265 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005266 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005267 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005268
5269#ifdef AUDIO_WATCHDOG
5270 // create and start the watchdog
5271 mAudioWatchdog = new AudioWatchdog();
5272 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5273 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5274 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005275 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005276#endif
Andy Hung8946a282018-04-19 20:04:56 -07005277 } else {
5278#ifdef TEE_SINK
5279 // Only use the MixerThread tee if there is no FastMixer.
5280 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5281 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5282#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005283 }
5284
5285 switch (kUseFastMixer) {
5286 case FastMixer_Never:
5287 case FastMixer_Dynamic:
5288 mNormalSink = mOutputSink;
5289 break;
5290 case FastMixer_Always:
5291 mNormalSink = mPipeSink;
5292 break;
5293 case FastMixer_Static:
5294 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5295 break;
5296 }
Andy Hung922617c2024-06-25 17:07:58 -07005297 // setMasterBalance needs to be called after the FastMixer
5298 // (if any) is set up, in order to deliver the balance settings to it.
5299 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005300}
5301
Andy Hungee58e4a2023-07-07 13:47:37 -07005302MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005303{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005304 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005305 FastMixerStateQueue *sq = mFastMixer->sq();
5306 FastMixerState *state = sq->begin();
5307 if (state->mCommand == FastMixerState::COLD_IDLE) {
5308 int32_t old = android_atomic_inc(&mFastMixerFutex);
5309 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005310 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005311 }
5312 }
5313 state->mCommand = FastMixerState::EXIT;
5314 sq->end();
5315 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5316 mFastMixer->join();
5317 // Though the fast mixer thread has exited, it's state queue is still valid.
5318 // We'll use that extract the final state which contains one remaining fast track
5319 // corresponding to our sub-mix.
5320 state = sq->begin();
5321 ALOG_ASSERT(state->mTrackMask == 1);
5322 FastTrack *fastTrack = &state->mFastTracks[0];
5323 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5324 delete fastTrack->mBufferProvider;
5325 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005326 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005327#ifdef AUDIO_WATCHDOG
5328 if (mAudioWatchdog != 0) {
5329 mAudioWatchdog->requestExit();
5330 mAudioWatchdog->requestExitAndWait();
5331 mAudioWatchdog.clear();
5332 }
5333#endif
5334 }
Andy Hung583043b2023-07-17 17:05:00 -07005335 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005336 delete mAudioMixer;
5337}
5338
Andy Hungee58e4a2023-07-07 13:47:37 -07005339void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005340 PlaybackThread::onFirstRef();
5341
Andy Hung972bec12023-08-31 16:13:39 -07005342 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005343 if (mOutput != nullptr && mOutput->stream != nullptr) {
5344 status_t status = mOutput->stream->setLatencyModeCallback(this);
5345 if (status != INVALID_OPERATION) {
5346 updateHalSupportedLatencyModes_l();
5347 }
5348 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5349 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5350 mBluetoothLatencyModesEnabled.store(
5351 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5352 }
5353}
Eric Laurent81784c32012-11-19 14:55:58 -08005354
Andy Hungee58e4a2023-07-07 13:47:37 -07005355uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005356{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005357 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005358 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5359 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5360 }
5361 return latency;
5362}
5363
Andy Hungee58e4a2023-07-07 13:47:37 -07005364ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005365{
5366 // FIXME we should only do one push per cycle; confirm this is true
5367 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005368 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005369 FastMixerStateQueue *sq = mFastMixer->sq();
5370 FastMixerState *state = sq->begin();
5371 if (state->mCommand != FastMixerState::MIX_WRITE &&
5372 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5373 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005374
5375 // FIXME workaround for first HAL write being CPU bound on some devices
5376 ATRACE_BEGIN("write");
5377 mOutput->write((char *)mSinkBuffer, 0);
5378 ATRACE_END();
5379
Eric Laurent81784c32012-11-19 14:55:58 -08005380 int32_t old = android_atomic_inc(&mFastMixerFutex);
5381 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005382 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005383 }
5384#ifdef AUDIO_WATCHDOG
5385 if (mAudioWatchdog != 0) {
5386 mAudioWatchdog->resume();
5387 }
5388#endif
5389 }
5390 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005391#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005392 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005393 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005394#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005395 sq->end();
5396 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5397 if (kUseFastMixer == FastMixer_Dynamic) {
5398 mNormalSink = mPipeSink;
5399 }
5400 } else {
5401 sq->end(false /*didModify*/);
5402 }
5403 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005404 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005405}
5406
Andy Hungee58e4a2023-07-07 13:47:37 -07005407void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005408{
5409 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005410 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005411 FastMixerStateQueue *sq = mFastMixer->sq();
5412 FastMixerState *state = sq->begin();
5413 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005414 // Report any frames trapped in the Monopipe
5415 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5416 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5417 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5418 "monoPipeWritten:%lld monoPipeLeft:%lld",
5419 (long long)mFramesWritten, (long long)mSuspendedFrames,
5420 (long long)mPipeSink->framesWritten(), pipeFrames);
5421 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5422
Eric Laurent81784c32012-11-19 14:55:58 -08005423 state->mCommand = FastMixerState::COLD_IDLE;
5424 state->mColdFutexAddr = &mFastMixerFutex;
5425 state->mColdGen++;
5426 mFastMixerFutex = 0;
5427 sq->end();
5428 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5429 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5430 if (kUseFastMixer == FastMixer_Dynamic) {
5431 mNormalSink = mOutputSink;
5432 }
5433#ifdef AUDIO_WATCHDOG
5434 if (mAudioWatchdog != 0) {
5435 mAudioWatchdog->pause();
5436 }
5437#endif
5438 } else {
5439 sq->end(false /*didModify*/);
5440 }
5441 }
5442 PlaybackThread::threadLoop_standby();
5443}
5444
Andy Hungee58e4a2023-07-07 13:47:37 -07005445bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005446{
5447 return false;
5448}
5449
Andy Hungee58e4a2023-07-07 13:47:37 -07005450bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005451{
5452 return !mStandby;
5453}
5454
Andy Hungee58e4a2023-07-07 13:47:37 -07005455bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005456{
Andy Hung972bec12023-08-31 16:13:39 -07005457 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458 return waitingAsyncCallback_l();
5459}
5460
Eric Laurent81784c32012-11-19 14:55:58 -08005461// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005462void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005463{
Andy Hung8d672e02023-09-15 18:19:28 -07005464 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5465 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005466 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005467 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005468 // discard any pending drain or write ack by incrementing sequence
5469 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5470 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005471 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005472 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5473 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005474 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005475 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005476 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005477}
5478
Andy Hungee58e4a2023-07-07 13:47:37 -07005479void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005480{
5481 ALOGV("signal playback thread");
5482 broadcast_l();
5483}
5484
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005485void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005486{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005487 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005488 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5489 invalidateTracks((audio_stream_type_t)i);
5490 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005491 if (isHardError) {
5492 mAfThreadCallback->onHardError(allTrackPortIds);
5493 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005494}
5495
Andy Hungee58e4a2023-07-07 13:47:37 -07005496void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005497{
Eric Laurent81784c32012-11-19 14:55:58 -08005498 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005499 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005500 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005501 // increase sleep time progressively when application underrun condition clears.
5502 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5503 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5504 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005505 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005506 sleepTimeShift--;
5507 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005508 mSleepTimeUs = 0;
5509 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005510 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005511
Eric Laurent81784c32012-11-19 14:55:58 -08005512}
5513
Andy Hungee58e4a2023-07-07 13:47:37 -07005514void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005515{
5516 // If no tracks are ready, sleep once for the duration of an output
5517 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005518 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005519 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005520 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5521 // Using the Monopipe availableToWrite, we estimate the
5522 // sleep time to retry for more data (before we underrun).
5523 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5524 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5525 const size_t pipeFrames = monoPipe->maxFrames();
5526 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5527 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5528 const size_t framesDelay = std::min(
5529 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5530 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5531 pipeFrames, framesLeft, framesDelay);
5532 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5533 } else {
5534 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5535 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5536 mSleepTimeUs = kMinThreadSleepTimeUs;
5537 }
5538 // reduce sleep time in case of consecutive application underruns to avoid
5539 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5540 // duration we would end up writing less data than needed by the audio HAL if
5541 // the condition persists.
5542 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5543 sleepTimeShift++;
5544 }
Eric Laurent81784c32012-11-19 14:55:58 -08005545 }
5546 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005547 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005548 }
5549 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005550 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5551 // before effects processing or output.
5552 if (mMixerBufferValid) {
5553 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005554 if (mType == SPATIALIZER) {
5555 memset(mSinkBuffer, 0, mSinkBufferSize);
5556 }
Andy Hung98ef9782014-03-04 14:46:50 -08005557 } else {
5558 memset(mSinkBuffer, 0, mSinkBufferSize);
5559 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005560 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005561 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5562 "anticipated start");
5563 }
5564 // TODO add standby time extension fct of effect tail
5565}
5566
Andy Hungc5007f82023-08-29 14:26:09 -07005567// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005568PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005569 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005570{
Andy Hungc0691382018-09-12 18:01:57 -07005571 // clean up deleted track ids in AudioMixer before allocating new tracks
5572 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5573 // for each trackId, destroy it in the AudioMixer
5574 if (mAudioMixer->exists(trackId)) {
5575 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005576 }
5577 });
Andy Hungc0691382018-09-12 18:01:57 -07005578 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005579
5580 mixer_state mixerStatus = MIXER_IDLE;
5581 // find out which tracks need to be processed
5582 size_t count = mActiveTracks.size();
5583 size_t mixedTracks = 0;
5584 size_t tracksWithEffect = 0;
5585 // counts only _active_ fast tracks
5586 size_t fastTracks = 0;
5587 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5588
5589 float masterVolume = mMasterVolume;
5590 bool masterMute = mMasterMute;
5591
5592 if (masterMute) {
5593 masterVolume = 0;
5594 }
5595 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005596 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005597 if (chain != 0) {
5598 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005599 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005600 masterVolume = (float)((v + (1 << 23)) >> 24);
5601 chain.clear();
5602 }
5603
5604 // prepare a new state to push
5605 FastMixerStateQueue *sq = NULL;
5606 FastMixerState *state = NULL;
5607 bool didModify = false;
5608 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005609 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005610 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005611 sq = mFastMixer->sq();
5612 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005613 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005614 }
5615
Andy Hung69aed5f2014-02-25 17:24:40 -08005616 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005617 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005618
Andy Hungbd3b2b02018-05-21 10:53:11 -07005619 // DeferredOperations handles statistics after setting mixerStatus.
5620 class DeferredOperations {
5621 public:
Andy Hungea840382020-05-05 21:50:17 -07005622 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5623 : mMixerStatus(mixerStatus)
5624 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005625
5626 // when leaving scope, tally frames properly.
5627 ~DeferredOperations() {
5628 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5629 // because that is when the underrun occurs.
5630 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005631 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005632 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005633 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005634 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005635 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005636 }
5637 }
Andy Hungea840382020-05-05 21:50:17 -07005638 // send the max underrun frames for this mixer period
5639 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005640 }
5641
5642 // tallyUnderrunFrames() is called to update the track counters
5643 // with the number of underrun frames for a particular mixer period.
5644 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005645 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005646 mUnderrunFrames.emplace_back(track, underrunFrames);
5647 }
5648
5649 private:
5650 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005651 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005652 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005653 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005654 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005655
jiabin245cdd92018-12-07 17:55:15 -08005656 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005657 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005658 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005659
5660 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005661 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005662
5663 // process fast tracks
5664 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005665 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5666 "%s(%d): FastTrack(%d) present without FastMixer",
5667 __func__, id(), track->id());
5668
jiabin245cdd92018-12-07 17:55:15 -08005669 if (track->getHapticPlaybackEnabled()) {
5670 noFastHapticTrack = false;
5671 }
Eric Laurent81784c32012-11-19 14:55:58 -08005672
5673 // It's theoretically possible (though unlikely) for a fast track to be created
5674 // and then removed within the same normal mix cycle. This is not a problem, as
5675 // the track never becomes active so it's fast mixer slot is never touched.
5676 // The converse, of removing an (active) track and then creating a new track
5677 // at the identical fast mixer slot within the same normal mix cycle,
5678 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005679 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005680 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005681 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5682 FastTrack *fastTrack = &state->mFastTracks[j];
5683
5684 // Determine whether the track is currently in underrun condition,
5685 // and whether it had a recent underrun.
5686 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5687 FastTrackUnderruns underruns = ftDump->mUnderruns;
5688 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005689 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005690 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005691 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005692 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005693 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005694 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005695 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005696 // don't count underruns that occur while stopping or pausing
5697 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005698 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005699 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5700 recentUnderruns > 0) {
5701 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005702 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005703 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005704 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005705 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005706
5707 // This is similar to the state machine for normal tracks,
5708 // with a few modifications for fast tracks.
5709 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005710 switch (track->state()) {
5711 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005712 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005713 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005714 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005715 }
5716 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005717 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005718 // ramp down is not yet implemented
5719 track->setPaused();
5720 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005721 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005722 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005723 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005724 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005725 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005726 if (recentFull > 0 || recentPartial > 0) {
5727 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005728 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005729 }
5730 if (recentUnderruns == 0) {
5731 // no recent underruns: stay active
5732 break;
5733 }
5734 // there has recently been an underrun of some kind
5735 if (track->sharedBuffer() == 0) {
5736 // were any of the recent underruns "empty" (no frames available)?
5737 if (recentEmpty == 0) {
5738 // no, then ignore the partial underruns as they are allowed indefinitely
5739 break;
5740 }
5741 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005742 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005743 break;
5744 }
5745 // indicate to client process that the track was disabled because of underrun;
5746 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005747 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005748 // remove from active list, but state remains ACTIVE [confusing but true]
5749 isActive = false;
5750 break;
5751 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005752 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005753 case IAfTrackBase::STOPPING_2:
5754 case IAfTrackBase::PAUSED:
5755 case IAfTrackBase::STOPPED:
5756 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005757 // Check for presentation complete if track is inactive
5758 // We have consumed all the buffers of this track.
5759 // This would be incomplete if we auto-paused on underrun
5760 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005761 uint32_t latency = 0;
5762 status_t result = mOutput->stream->getLatency(&latency);
5763 ALOGE_IF(result != OK,
5764 "Error when retrieving output stream latency: %d", result);
5765 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005766 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005767 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5768 // track stays in active list until presentation is complete
5769 break;
5770 }
5771 }
5772 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005773 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005774 }
5775 if (track->isStopped()) {
5776 // Can't reset directly, as fast mixer is still polling this track
5777 // track->reset();
5778 // So instead mark this track as needing to be reset after push with ack
5779 resetMask |= 1 << i;
5780 }
5781 isActive = false;
5782 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005783 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005784 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005785 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005786 }
5787
5788 if (isActive) {
5789 // was it previously inactive?
5790 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005791 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5792 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005793 fastTrack->mBufferProvider = eabp;
5794 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005795 fastTrack->mChannelMask = track->channelMask();
5796 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005797 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005798 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005799 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005800 fastTrack->mGeneration++;
5801 state->mTrackMask |= 1 << j;
5802 didModify = true;
5803 // no acknowledgement required for newly active tracks
5804 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005805 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005806 float volume;
Andy Hung6b137d12024-08-27 22:35:17 +00005807 if (!audioserver_flags::portid_volume_management()) {
5808 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5809 volume = 0.f;
5810 } else {
5811 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5812 }
Eric Laurenteab90452019-06-24 15:17:46 -07005813 } else {
Andy Hung6b137d12024-08-27 22:35:17 +00005814 if (track->isPlaybackRestricted()) {
5815 volume = 0.f;
5816 } else {
5817 volume = masterVolume * track->getPortVolume();
5818 }
Eric Laurenteab90452019-06-24 15:17:46 -07005819 }
Eric Laurenteab90452019-06-24 15:17:46 -07005820 handleVoipVolume_l(&volume);
5821
Eric Laurent81784c32012-11-19 14:55:58 -08005822 // cache the combined master volume and stream type volume for fast mixer; this
5823 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005824 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005825 proxy->framesReleased()).first;
5826 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005827 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005828 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005829 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5830 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Andy Hung6b137d12024-08-27 22:35:17 +00005831 if (!audioserver_flags::portid_volume_management()) {
5832 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5833 /*muteState=*/{masterVolume == 0.f,
5834 mStreamTypes[track->streamType()].volume == 0.f,
5835 mStreamTypes[track->streamType()].mute,
5836 track->isPlaybackRestricted(),
5837 vlf == 0.f && vrf == 0.f,
5838 vh == 0.f});
5839 } else {
5840 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5841 /*muteState=*/{masterVolume == 0.f,
5842 track->getPortVolume() == 0.f,
5843 /* muteFromStreamMuted= */ false,
5844 track->isPlaybackRestricted(),
5845 vlf == 0.f && vrf == 0.f,
5846 vh == 0.f});
5847 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005848 vlf *= volume;
5849 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005850
jiabin220eea12024-05-17 17:55:20 +00005851 if (track->getInternalMute()) {
5852 vlf = 0.f;
5853 vrf = 0.f;
5854 }
5855
jiabin76d94692022-12-15 21:51:21 +00005856 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005857 ++fastTracks;
5858 } else {
5859 // was it previously active?
5860 if (state->mTrackMask & (1 << j)) {
5861 fastTrack->mBufferProvider = NULL;
5862 fastTrack->mGeneration++;
5863 state->mTrackMask &= ~(1 << j);
5864 didModify = true;
5865 // If any fast tracks were removed, we must wait for acknowledgement
5866 // because we're about to decrement the last sp<> on those tracks.
5867 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5868 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005869 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5870 // AudioTrack may start (which may not be with a start() but with a write()
5871 // after underrun) and immediately paused or released. In that case the
5872 // FastTrack state hasn't had time to update.
5873 // TODO Remove the ALOGW when this theory is confirmed.
5874 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005875 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005876 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005877 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005878 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005879 }
5880 tracksToRemove->add(track);
5881 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005882 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005883 }
jiabin245cdd92018-12-07 17:55:15 -08005884 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5885 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5886 didModify = true;
5887 }
Eric Laurent81784c32012-11-19 14:55:58 -08005888 continue;
5889 }
5890
5891 { // local variable scope to avoid goto warning
5892
5893 audio_track_cblk_t* cblk = track->cblk();
5894
5895 // The first time a track is added we wait
5896 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005897 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005898
5899 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005900 // use the trackId as the AudioMixer name.
5901 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005902 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005903 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005904 track->channelMask(),
5905 track->format(),
5906 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005907 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005908 ALOGW("%s(): AudioMixer cannot create track(%d)"
5909 " mask %#x, format %#x, sessionId %d",
5910 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005911 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005912 tracksToRemove->add(track);
5913 track->invalidate(); // consider it dead.
5914 continue;
5915 }
5916 }
5917
Eric Laurent81784c32012-11-19 14:55:58 -08005918 // make sure that we have enough frames to mix one full buffer.
5919 // enforce this condition only once to enable draining the buffer in case the client
5920 // app does not call stop() and relies on underrun to stop:
5921 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5922 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005923 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005924 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5925 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005926
5927 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005928 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005929 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5930 // add frames already consumed but not yet released by the resampler
5931 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005932 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005933
Eric Laurent81784c32012-11-19 14:55:58 -08005934 uint32_t minFrames = 1;
5935 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5936 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005937 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005938 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005939
5940 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005941 if (ATRACE_ENABLED()) {
5942 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005943 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005944 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005945 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005946 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005947 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005948 !track->isPaused() && !track->isTerminated())
5949 {
Andy Hungc0691382018-09-12 18:01:57 -07005950 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005951
5952 mixedTracks++;
5953
Shunkai Yaof4847652024-01-12 00:25:20 +00005954 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005955 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005956 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005957 if (track->mainBuffer() != mSinkBuffer &&
5958 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005959 if (mEffectBufferEnabled) {
5960 mEffectBufferValid = true; // Later can set directly.
5961 }
Eric Laurent81784c32012-11-19 14:55:58 -08005962 chain = getEffectChain_l(track->sessionId());
5963 // Delegate volume control to effect in track effect chain if needed
5964 if (chain != 0) {
5965 tracksWithEffect++;
5966 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005967 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005968 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005969 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005970 }
5971 }
5972
5973
5974 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005975 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005976 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005977 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5978 if (track->state() == IAfTrackBase::RESUMING) {
5979 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005980 // If a new track is paused immediately after start, do not ramp on resume.
5981 if (cblk->mServer != 0) {
5982 param = AudioMixer::RAMP_VOLUME;
5983 }
Eric Laurent81784c32012-11-19 14:55:58 -08005984 }
Andy Hungc0691382018-09-12 18:01:57 -07005985 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005986 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005987 // FIXME should not make a decision based on mServer
5988 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005989 // If the track is stopped before the first frame was mixed,
5990 // do not apply ramp
5991 param = AudioMixer::RAMP_VOLUME;
5992 }
5993
5994 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005995 uint32_t vl, vr; // in U8.24 integer format
5996 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005997 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07005998 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005999 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07006000 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07006001 track->audioTrackServerProxy()->framesReleased()).first;
Andy Hung6b137d12024-08-27 22:35:17 +00006002 float v;
6003 if (!audioserver_flags::portid_volume_management()) {
6004 v = masterVolume * mStreamTypes[track->streamType()].volume;
6005 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6006 v = 0;
6007 }
6008 } else {
6009 v = masterVolume * track->getPortVolume();
6010 if (track->isPlaybackRestricted()) {
6011 v = 0;
6012 }
Eric Laurenteab90452019-06-24 15:17:46 -07006013 }
Eric Laurenteab90452019-06-24 15:17:46 -07006014 handleVoipVolume_l(&v);
6015
6016 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006017 vl = vr = 0;
6018 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006019 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006020 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006021 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006022 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6023 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006024 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006025 if (vlf > GAIN_FLOAT_UNITY) {
6026 ALOGV("Track left volume out of range: %.3g", vlf);
6027 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006028 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006029 if (vrf > GAIN_FLOAT_UNITY) {
6030 ALOGV("Track right volume out of range: %.3g", vrf);
6031 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006032 }
Andy Hung6b137d12024-08-27 22:35:17 +00006033 if (!audioserver_flags::portid_volume_management()) {
6034 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6035 /*muteState=*/{masterVolume == 0.f,
6036 mStreamTypes[track->streamType()].volume == 0.f,
6037 mStreamTypes[track->streamType()].mute,
6038 track->isPlaybackRestricted(),
6039 vlf == 0.f && vrf == 0.f,
6040 vh == 0.f});
6041 } else {
6042 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6043 /*muteState=*/{masterVolume == 0.f,
6044 track->getPortVolume() == 0.f,
6045 /* muteFromStreamMuted= */ false,
6046 track->isPlaybackRestricted(),
6047 vlf == 0.f && vrf == 0.f,
6048 vh == 0.f});
6049 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006050 // now apply the master volume and stream type volume and shaper volume
6051 vlf *= v * vh;
6052 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006053 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006054 // then derive vl and vr as U8.24 versions for the effect chain
6055 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6056 vl = (uint32_t) (scaleto8_24 * vlf);
6057 vr = (uint32_t) (scaleto8_24 * vrf);
6058 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006059 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006060 // send level comes from shared memory and so may be corrupt
6061 if (sendLevel > MAX_GAIN_INT) {
6062 ALOGV("Track send level out of range: %04X", sendLevel);
6063 sendLevel = MAX_GAIN_INT;
6064 }
Andy Hung6be49402014-05-30 10:42:03 -07006065 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6066 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006067 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006068
jiabin220eea12024-05-17 17:55:20 +00006069 if (track->getInternalMute()) {
6070 vrf = 0.f;
6071 vlf = 0.f;
6072 }
6073
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006074 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006075
Eric Laurent81784c32012-11-19 14:55:58 -08006076 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006077 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006078 // Do not ramp volume if volume is controlled by effect
6079 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006080 // Update remaining floating point volume levels
6081 vlf = (float)vl / (1 << 24);
6082 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006083 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006084 } else {
6085 // force no volume ramp when volume controller was just disabled or removed
6086 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006087 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006088 param = AudioMixer::VOLUME;
6089 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006090 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006091 }
6092
Eric Laurent81784c32012-11-19 14:55:58 -08006093 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006094 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006095 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006096
Andy Hungc0691382018-09-12 18:01:57 -07006097 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6098 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6099 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006100 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006101 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006102 AudioMixer::TRACK,
6103 AudioMixer::FORMAT, (void *)track->format());
6104 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006105 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006106 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006107 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006108
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006109 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006110 mAudioMixer->setParameter(
6111 trackId,
6112 AudioMixer::TRACK,
6113 AudioMixer::MIXER_CHANNEL_MASK,
6114 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6115 } else {
6116 mAudioMixer->setParameter(
6117 trackId,
6118 AudioMixer::TRACK,
6119 AudioMixer::MIXER_CHANNEL_MASK,
6120 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6121 }
6122
Glenn Kastene3aa6592012-12-04 12:22:46 -08006123 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006124 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006125 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006126 if (reqSampleRate == 0) {
6127 reqSampleRate = mSampleRate;
6128 } else if (reqSampleRate > maxSampleRate) {
6129 reqSampleRate = maxSampleRate;
6130 }
Eric Laurent81784c32012-11-19 14:55:58 -08006131 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006132 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006133 AudioMixer::RESAMPLE,
6134 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006135 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006136
Andy Hung8edb8dc2015-03-26 19:13:55 -07006137 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006138 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006139 AudioMixer::TIMESTRETCH,
6140 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006141 // cast away constness for this generic API.
6142 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006143
Andy Hung69aed5f2014-02-25 17:24:40 -08006144 /*
6145 * Select the appropriate output buffer for the track.
6146 *
Andy Hung98ef9782014-03-04 14:46:50 -08006147 * Tracks with effects go into their own effects chain buffer
6148 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006149 *
6150 * Other tracks can use mMixerBuffer for higher precision
6151 * channel accumulation. If this buffer is enabled
6152 * (mMixerBufferEnabled true), then selected tracks will accumulate
6153 * into it.
6154 *
6155 */
6156 if (mMixerBufferEnabled
6157 && (track->mainBuffer() == mSinkBuffer
6158 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006159 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006160 mAudioMixer->setParameter(
6161 trackId,
6162 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006163 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006164 mAudioMixer->setParameter(
6165 trackId,
6166 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006167 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006168 } else {
6169 mAudioMixer->setParameter(
6170 trackId,
6171 AudioMixer::TRACK,
6172 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6173 mAudioMixer->setParameter(
6174 trackId,
6175 AudioMixer::TRACK,
6176 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6177 // TODO: override track->mainBuffer()?
6178 mMixerBufferValid = true;
6179 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006180 } else {
6181 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006182 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006183 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006184 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006185 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006186 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006187 AudioMixer::TRACK,
6188 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6189 }
Eric Laurent81784c32012-11-19 14:55:58 -08006190 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006191 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006192 AudioMixer::TRACK,
6193 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006194 mAudioMixer->setParameter(
6195 trackId,
6196 AudioMixer::TRACK,
6197 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006198 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006199 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006200 trackId,
6201 AudioMixer::TRACK,
6202 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006203 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006204 mAudioMixer->setParameter(
6205 trackId,
6206 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006207 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006208
6209 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006210 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006211
6212 // If one track is ready, set the mixer ready if:
6213 // - the mixer was not ready during previous round OR
6214 // - no other track is not ready
6215 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6216 mixerStatus != MIXER_TRACKS_ENABLED) {
6217 mixerStatus = MIXER_TRACKS_READY;
6218 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006219
6220 // Enable the next few lines to instrument a test for underrun log handling.
6221 // TODO: Remove when we have a better way of testing the underrun log.
6222#if 0
6223 static int i;
6224 if ((++i & 0xf) == 0) {
6225 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6226 }
6227#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006228 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006229 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006230 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006231 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6232 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006233 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006234 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006235 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006236
Eric Laurent81784c32012-11-19 14:55:58 -08006237 // clear effect chain input buffer if an active track underruns to avoid sending
6238 // previous audio buffer again to effects
6239 chain = getEffectChain_l(track->sessionId());
6240 if (chain != 0) {
6241 chain->clearInputBuffer();
6242 }
6243
Andy Hungc0691382018-09-12 18:01:57 -07006244 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006245 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6246 track->isStopped() || track->isPaused()) {
6247 // We have consumed all the buffers of this track.
6248 // Remove it from the list of active tracks.
6249 // TODO: use actual buffer filling status instead of latency when available from
6250 // audio HAL
6251 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006252 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006253 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6254 if (track->isStopped()) {
6255 track->reset();
6256 }
6257 tracksToRemove->add(track);
6258 }
6259 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006260 // No buffers for this track. Give it a few chances to
6261 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006262 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006263 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6264 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006265 tracksToRemove->add(track);
6266 // indicate to client process that the track was disabled because of underrun;
6267 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006268 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006269 // If one track is not ready, mark the mixer also not ready if:
6270 // - the mixer was ready during previous round OR
6271 // - no other track is ready
6272 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6273 mixerStatus != MIXER_TRACKS_READY) {
6274 mixerStatus = MIXER_TRACKS_ENABLED;
6275 }
6276 }
Andy Hungc0691382018-09-12 18:01:57 -07006277 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006278 }
6279
6280 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006281
6282 }
6283
jiabin245cdd92018-12-07 17:55:15 -08006284 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6285 // When there is no fast track playing haptic and FastMixer exists,
6286 // enabling the first FastTrack, which provides mixed data from normal
6287 // tracks, to play haptic data.
6288 FastTrack *fastTrack = &state->mFastTracks[0];
6289 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6290 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6291 didModify = true;
6292 }
6293 }
6294
Eric Laurent81784c32012-11-19 14:55:58 -08006295 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006296 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006297 if (didModify) {
6298 state->mFastTracksGen++;
6299 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6300 if (kUseFastMixer == FastMixer_Dynamic &&
6301 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6302 state->mCommand = FastMixerState::COLD_IDLE;
6303 state->mColdFutexAddr = &mFastMixerFutex;
6304 state->mColdGen++;
6305 mFastMixerFutex = 0;
6306 if (kUseFastMixer == FastMixer_Dynamic) {
6307 mNormalSink = mOutputSink;
6308 }
6309 // If we go into cold idle, need to wait for acknowledgement
6310 // so that fast mixer stops doing I/O.
6311 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6312 pauseAudioWatchdog = true;
6313 }
Eric Laurent81784c32012-11-19 14:55:58 -08006314 }
6315 if (sq != NULL) {
6316 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006317 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6318 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6319 // when bringing the output sink into standby.)
6320 //
6321 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6322 //
6323 // This occurs with BT suspend when we idle the FastMixer with
6324 // active tracks, which may be added or removed.
6325 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006326 }
6327#ifdef AUDIO_WATCHDOG
6328 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6329 mAudioWatchdog->pause();
6330 }
6331#endif
6332
6333 // Now perform the deferred reset on fast tracks that have stopped
6334 while (resetMask != 0) {
6335 size_t i = __builtin_ctz(resetMask);
6336 ALOG_ASSERT(i < count);
6337 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006338 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006339 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6340 track->reset();
6341 }
6342
Andy Hung80d03d22018-04-10 10:32:11 -07006343 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6344 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6345 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6346 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6347 // See also the implementation of destroyTrack_l().
6348 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006349 const int trackId = track->id();
6350 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6351 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006352 }
6353 }
6354
Eric Laurent81784c32012-11-19 14:55:58 -08006355 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006356 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006357
Eric Laurentb3f315a2021-07-13 15:09:05 +02006358 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6359 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006360 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006361 }
6362
6363 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006364 // as long as there are effects we should clear the effects buffer, to avoid
6365 // passing a non-clean buffer to the effect chain
6366 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006367 if (mType == SPATIALIZER) {
6368 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6369 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006370 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006371 // sink or mix buffer must be cleared if all tracks are connected to an
6372 // effect chain as in this case the mixer will not write to the sink or mix buffer
6373 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006374 // always clear sink buffer for spatializer output as the output of the spatializer
6375 // effect will be accumulated into it
6376 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6377 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006378 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006379 if (mMixerBufferValid) {
6380 memset(mMixerBuffer, 0, mMixerBufferSize);
6381 // TODO: In testing, mSinkBuffer below need not be cleared because
6382 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6383 // after mixing.
6384 //
6385 // To enforce this guarantee:
6386 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6387 // (mixedTracks == 0 && fastTracks > 0))
6388 // must imply MIXER_TRACKS_READY.
6389 // Later, we may clear buffers regardless, and skip much of this logic.
6390 }
Andy Hung98ef9782014-03-04 14:46:50 -08006391 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006392 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006393 }
6394
6395 // if any fast tracks, then status is ready
6396 mMixerStatusIgnoringFastTracks = mixerStatus;
6397 if (fastTracks > 0) {
6398 mixerStatus = MIXER_TRACKS_READY;
6399 }
6400 return mixerStatus;
6401}
6402
Andy Hungc5007f82023-08-29 14:26:09 -07006403// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006404uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006405{
6406 uint32_t trackCount = 0;
6407 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006408 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006409 trackCount++;
6410 }
6411 }
6412 return trackCount;
6413}
6414
Andy Hungee58e4a2023-07-07 13:47:37 -07006415bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006416{
Brian Lindahl65e90012022-07-27 18:01:07 +02006417 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6418 // could falsely detect that the frame position has stalled due to underrun because we haven't
6419 // given the Audio HAL enough time to update.
6420 const nsecs_t nowNs = systemTime();
6421 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6422 return mLatchedValue;
6423 }
6424 mPreviousNs = nowNs;
6425 mLatchedValue = false;
6426 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006427 uint64_t position = 0;
6428 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006429 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006430 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006431 if (position != mPreviousPosition) {
6432 mPreviousPosition = position;
6433 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006434 }
6435 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006436 return mLatchedValue;
6437}
6438
Andy Hungee58e4a2023-07-07 13:47:37 -07006439void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006440{
6441 mLatchedValue = true;
6442 mPreviousPosition = 0;
6443 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006444}
6445
Andy Hungc5007f82023-08-29 14:26:09 -07006446// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006447bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006448 audio_channel_mask_t channelMask, audio_format_t format,
6449 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006450{
Andy Hung1bc088a2018-02-09 15:57:31 -08006451 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6452 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006453 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006454 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006455 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006456 ALOGW("%s: invalid format: %#x", __func__, format);
6457 return false;
6458 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006459 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006460 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6461 return false;
6462 }
6463 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006464}
6465
Andy Hungc5007f82023-08-29 14:26:09 -07006466// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006467bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006468 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006469{
Eric Laurent81784c32012-11-19 14:55:58 -08006470 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006471 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006472
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006473 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006474
Eric Laurent10351942014-05-08 18:49:52 -07006475 AudioParameter param = AudioParameter(keyValuePair);
6476 int value;
6477 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6478 reconfig = true;
6479 }
6480 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006481 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006482 status = BAD_VALUE;
6483 } else {
6484 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006485 reconfig = true;
6486 }
Eric Laurent10351942014-05-08 18:49:52 -07006487 }
6488 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006489 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006490 status = BAD_VALUE;
6491 } else {
6492 // no need to save value, since it's constant
6493 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006494 }
Eric Laurent10351942014-05-08 18:49:52 -07006495 }
6496 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6497 // do not accept frame count changes if tracks are open as the track buffer
6498 // size depends on frame count and correct behavior would not be guaranteed
6499 // if frame count is changed after track creation
6500 if (!mTracks.isEmpty()) {
6501 status = INVALID_OPERATION;
6502 } else {
6503 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006504 }
Eric Laurent10351942014-05-08 18:49:52 -07006505 }
6506 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006507 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006508 }
Eric Laurent81784c32012-11-19 14:55:58 -08006509
Eric Laurent10351942014-05-08 18:49:52 -07006510 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006511 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006512 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006513 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6514 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006515 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006516 mThreadMetrics.logEndInterval();
6517 mThreadSnapshot.onEnd();
6518 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006519 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006520 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006521 }
Eric Laurent10351942014-05-08 18:49:52 -07006522 if (status == NO_ERROR && reconfig) {
6523 readOutputParameters_l();
6524 delete mAudioMixer;
6525 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006526 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006527 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006528 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006529 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006530 track->channelMask(),
6531 track->format(),
6532 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006533 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006534 "%s(): AudioMixer cannot create track(%d)"
6535 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006536 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006537 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006538 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006539 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006540 }
Eric Laurent81784c32012-11-19 14:55:58 -08006541 }
6542
Dean Wheatley68918102021-03-19 22:09:19 +11006543 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006544}
6545
6546
Andy Hungee58e4a2023-07-07 13:47:37 -07006547void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006548{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006549 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006550 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006551 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006552 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006553 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6554 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6555 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006556 if (hasFastMixer()) {
6557 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6558
6559 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6560 // while we are dumping it. It may be inconsistent, but it won't mutate!
6561 // This is a large object so we place it on the heap.
6562 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006563 const std::unique_ptr<FastMixerDumpState> copy =
6564 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006565 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006566
6567#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006568 // Similar for state queue
6569 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6570 observerCopy.dump(fd);
6571 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6572 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006573#endif
6574
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006575#ifdef AUDIO_WATCHDOG
6576 if (mAudioWatchdog != 0) {
6577 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6578 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6579 wdCopy.dump(fd);
6580 }
6581#endif
6582
6583 } else {
6584 dprintf(fd, " No FastMixer\n");
6585 }
Eric Laurent90cea102023-05-15 15:08:27 +02006586
6587 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6588 mBluetoothLatencyModesEnabled ? "" : "not ");
6589 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6590 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6591 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006592}
6593
Andy Hungee58e4a2023-07-07 13:47:37 -07006594uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006595{
6596 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6597}
6598
Andy Hungee58e4a2023-07-07 13:47:37 -07006599uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006600{
6601 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6602}
6603
Andy Hungee58e4a2023-07-07 13:47:37 -07006604void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006605{
6606 PlaybackThread::cacheParameters_l();
6607
6608 // FIXME: Relaxed timing because of a certain device that can't meet latency
6609 // Should be reduced to 2x after the vendor fixes the driver issue
6610 // increase threshold again due to low power audio mode. The way this warning
6611 // threshold is calculated and its usefulness should be reconsidered anyway.
6612 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6613}
6614
Andy Hungee58e4a2023-07-07 13:47:37 -07006615void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006616 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006617}
6618
Andy Hungee58e4a2023-07-07 13:47:37 -07006619void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006620 // Only handle latency mode if:
6621 // - mBluetoothLatencyModesEnabled is true
6622 // - the HAL supports latency modes
6623 // - the selected device is Bluetooth LE or A2DP
6624 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6625 return;
6626 }
6627 if (mOutDeviceTypeAddrs.size() != 1
6628 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6629 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6630 return;
6631 }
6632
6633 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6634 if (mSupportedLatencyModes.size() == 1) {
6635 // If the HAL only support one latency mode currently, confirm the choice
6636 latencyMode = mSupportedLatencyModes[0];
6637 } else if (mSupportedLatencyModes.size() > 1) {
6638 // Request low latency if:
6639 // - At least one active track is either:
6640 // - a fast track with gaming usage or
6641 // - a track with acessibility usage
6642 for (const auto& track : mActiveTracks) {
6643 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6644 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6645 latencyMode = AUDIO_LATENCY_MODE_LOW;
6646 break;
6647 }
6648 }
6649 }
6650
6651 if (latencyMode != mSetLatencyMode) {
6652 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6653 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6654 __func__, mId, toString(latencyMode).c_str(), status);
6655 if (status == NO_ERROR) {
6656 mSetLatencyMode = latencyMode;
6657 }
6658 }
6659}
6660
Andy Hungee58e4a2023-07-07 13:47:37 -07006661void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006662
6663 if (mOutput == nullptr || mOutput->stream == nullptr) {
6664 return;
6665 }
6666 std::vector<audio_latency_mode_t> latencyModes;
6667 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6668 if (status != NO_ERROR) {
6669 latencyModes.clear();
6670 }
6671 if (latencyModes != mSupportedLatencyModes) {
6672 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6673 __func__, mId, status, toString(latencyModes).c_str());
6674 mSupportedLatencyModes.swap(latencyModes);
6675 sendHalLatencyModesChangedEvent_l();
6676 }
6677}
6678
Andy Hungee58e4a2023-07-07 13:47:37 -07006679status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006680 std::vector<audio_latency_mode_t>* modes) {
6681 if (modes == nullptr) {
6682 return BAD_VALUE;
6683 }
Andy Hung972bec12023-08-31 16:13:39 -07006684 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006685 *modes = mSupportedLatencyModes;
6686 return NO_ERROR;
6687}
6688
Andy Hungee58e4a2023-07-07 13:47:37 -07006689void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006690 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006691 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006692 if (modes != mSupportedLatencyModes) {
6693 ALOGD("%s: thread(%d) supported latency modes: %s",
6694 __func__, mId, toString(modes).c_str());
6695 mSupportedLatencyModes.swap(modes);
6696 sendHalLatencyModesChangedEvent_l();
6697 }
6698}
6699
Andy Hungee58e4a2023-07-07 13:47:37 -07006700status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006701 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6702 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6703 return INVALID_OPERATION;
6704 }
6705 mBluetoothLatencyModesEnabled.store(enabled);
6706 return NO_ERROR;
6707}
6708
Eric Laurent81784c32012-11-19 14:55:58 -08006709// ----------------------------------------------------------------------------
6710
Andy Hungee58e4a2023-07-07 13:47:37 -07006711/* static */
6712sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006713 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006714 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6715 const audio_offload_info_t& offloadInfo) {
6716 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006717 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006718}
6719
Andy Hung583043b2023-07-17 17:05:00 -07006720DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006721 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6722 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006723 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006724 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006725{
Andy Hung583043b2023-07-17 17:05:00 -07006726 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006727}
6728
Andy Hungee58e4a2023-07-07 13:47:37 -07006729DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006730{
6731}
6732
Andy Hungee58e4a2023-07-07 13:47:37 -07006733void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006734{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006735 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006736 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6737 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6738}
6739
Andy Hungee58e4a2023-07-07 13:47:37 -07006740void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006741{
Andy Hung972bec12023-08-31 16:13:39 -07006742 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006743 if (mMasterBalance != balance) {
6744 mMasterBalance.store(balance);
6745 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6746 broadcast_l();
6747 }
6748}
6749
Andy Hungee58e4a2023-07-07 13:47:37 -07006750void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006751{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006752 float left, right;
6753
Andy Hung333ab962019-05-28 20:23:35 -07006754 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006755 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006756
Andy Hung398ffa22022-12-13 19:19:53 -08006757 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6758 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6759
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006760 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6761 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006762
6763 const int64_t volumeShaperFrames =
6764 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6765 const auto [shaperVolume, shaperActive] =
6766 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006767 mVolumeShaperActive = shaperActive;
6768
Vlad Popae2f5aef2022-07-25 16:00:20 +02006769 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6770 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6771 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6772
6773 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6774
Andy Hung6b137d12024-08-27 22:35:17 +00006775 if (!audioserver_flags::portid_volume_management()) {
6776 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6777 track->isPlaybackRestricted()) {
6778 left = right = 0;
6779 } else {
6780 float typeVolume = mStreamTypes[track->streamType()].volume;
6781 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurent277a37e2024-07-29 18:37:52 +00006782
Andy Hung6b137d12024-08-27 22:35:17 +00006783 if (left > GAIN_FLOAT_UNITY) {
6784 left = GAIN_FLOAT_UNITY;
6785 }
6786 if (right > GAIN_FLOAT_UNITY) {
6787 right = GAIN_FLOAT_UNITY;
6788 }
6789 left *= v;
6790 right *= v;
6791 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006792 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Andy Hung6b137d12024-08-27 22:35:17 +00006793 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6794 right *= mMasterBalanceRight;
6795 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006796 }
Andy Hung6b137d12024-08-27 22:35:17 +00006797 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6798 /*muteState=*/{mMasterMute,
6799 mStreamTypes[track->streamType()].volume == 0.f,
6800 mStreamTypes[track->streamType()].mute,
6801 track->isPlaybackRestricted(),
6802 clientVolumeMute,
6803 shaperVolume == 0.f});
6804 } else {
6805 if (mMasterMute || track->isPlaybackRestricted()) {
6806 left = right = 0;
6807 } else {
6808 float typeVolume = track->getPortVolume();
6809 const float v = mMasterVolume * typeVolume * shaperVolume;
Liana Kazanova (xWF)d3e99d22024-08-23 22:15:51 +00006810
Andy Hung6b137d12024-08-27 22:35:17 +00006811 if (left > GAIN_FLOAT_UNITY) {
6812 left = GAIN_FLOAT_UNITY;
6813 }
6814 if (right > GAIN_FLOAT_UNITY) {
6815 right = GAIN_FLOAT_UNITY;
6816 }
6817 left *= v;
6818 right *= v;
6819 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6820 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6821 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6822 right *= mMasterBalanceRight;
6823 }
6824 }
6825 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6826 /*muteState=*/{mMasterMute,
6827 track->getPortVolume() == 0.f,
6828 /* muteFromStreamMuted= */ false,
6829 track->isPlaybackRestricted(),
6830 clientVolumeMute,
6831 shaperVolume == 0.f});
6832 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006833
Eric Laurentbfb1b832013-01-07 09:53:42 -08006834 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006835 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006836 if (left != mLeftVolFloat || right != mRightVolFloat) {
6837 mLeftVolFloat = left;
6838 mRightVolFloat = right;
6839
Eric Laurentbfb1b832013-01-07 09:53:42 -08006840 // Delegate volume control to effect in track effect chain if needed
6841 // only one effect chain can be present on DirectOutputThread, so if
6842 // there is one, the track is connected to it
6843 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006844 // if effect chain exists, volume is handled by it.
6845 // Convert volumes from float to 8.24
6846 uint32_t vl = (uint32_t)(left * (1 << 24));
6847 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006848 // Direct/Offload effect chains set output volume in setVolume().
6849 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006850 } else {
6851 // otherwise we directly set the volume.
6852 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006853 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006854 }
6855 }
6856}
6857
Andy Hungee58e4a2023-07-07 13:47:37 -07006858void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006859{
Andy Hung8d31fd22023-06-26 19:20:57 -07006860 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6861 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006862
Eric Laurent0f0631e2015-07-06 18:01:25 -07006863 if (previousTrack != 0 && latestTrack != 0) {
6864 if (mType == DIRECT) {
6865 if (previousTrack.get() != latestTrack.get()) {
6866 mFlushPending = true;
6867 }
6868 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006869 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6870 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006871 mFlushPending = true;
6872 }
6873 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006874 } else if (previousTrack == 0) {
6875 // there could be an old track added back during track transition for direct
6876 // output, so always issues flush to flush data of the previous track if it
6877 // was already destroyed with HAL paused, then flush can resume the playback
6878 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006879 }
6880 PlaybackThread::onAddNewTrack_l();
6881}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006882
Andy Hungee58e4a2023-07-07 13:47:37 -07006883PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006884 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006885)
6886{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006887 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006888 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006889 bool doHwPause = false;
6890 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006891
6892 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006893 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006894 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006895 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006896 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006897 continue;
6898 }
6899
Andy Hung8d31fd22023-06-26 19:20:57 -07006900 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006901#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006902 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006903#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006904 // Only consider last track started for volume and mixer state control.
6905 // In theory an older track could underrun and restart after the new one starts
6906 // but as we only care about the transition phase between two tracks on a
6907 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006908 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006909 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006910
Kuowei Li23666472021-01-20 10:23:25 +08006911 if (track->isPausePending()) {
6912 track->pauseAck();
6913 // It is possible a track might have been flushed or stopped.
6914 // Other operations such as flush pending might occur on the next prepare.
6915 if (track->isPausing()) {
6916 track->setPaused();
6917 }
6918 // Always perform pause, as an immediate flush will change
6919 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006920 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006921 doHwPause = true;
6922 mHwPaused = true;
6923 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006924 } else if (track->isFlushPending()) {
6925 track->flushAck();
6926 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006927 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006928 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006929 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006930 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006931 if (last) {
6932 mLeftVolFloat = mRightVolFloat = -1.0;
6933 if (mHwPaused) {
6934 doHwResume = true;
6935 mHwPaused = false;
6936 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006937 }
6938 }
6939
Eric Laurent81784c32012-11-19 14:55:58 -08006940 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006941 // for all its buffers to be filled before processing it.
6942 // Allow draining the buffer in case the client
6943 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006944 // hence the test on (track->retryCount() > 1).
6945 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006946 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6947 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006948 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006949
6950 // target retry count that we will use is based on the time we wait for retries.
6951 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6952 // the retry threshold is when we accept any size for PCM data. This is slightly
6953 // smaller than the retry count so we can push small bits of data without a glitch.
6954 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006955 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006956 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006957 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006958 minFrames = mNormalFrameCount;
6959 } else {
6960 minFrames = 1;
6961 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006962
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006963 const size_t framesReady = track->framesReady();
6964 const int trackId = track->id();
6965 if (ATRACE_ENABLED()) {
6966 std::string traceName("nRdy");
6967 traceName += std::to_string(trackId);
6968 ATRACE_INT(traceName.c_str(), framesReady);
6969 }
6970 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006971 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006972 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006973 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006974
Andy Hung8d31fd22023-06-26 19:20:57 -07006975 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6976 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006977 if (last) {
6978 // make sure processVolume_l() will apply new volume even if 0
6979 mLeftVolFloat = mRightVolFloat = -1.0;
6980 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006981 if (!mHwSupportsPause) {
6982 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006983 }
6984 }
6985
6986 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006987 processVolume_l(track, last);
6988 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006989 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006990 if (previousTrack != 0) {
6991 if (track != previousTrack.get()) {
6992 // Flush any data still being written from last track
6993 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006994 // Invalidate previous track to force a seek when resuming.
6995 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006996 }
6997 }
6998 mPreviousTrack = track;
6999
Eric Laurentd595b7c2013-04-03 17:27:56 -07007000 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07007001 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08007002 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07007003 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07007004 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007005 doHwResume = true;
7006 mHwPaused = false;
7007 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007008 }
Eric Laurent81784c32012-11-19 14:55:58 -08007009 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007010 // clear effect chain input buffer if the last active track started underruns
7011 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007012 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007013 mEffectChains[0]->clearInputBuffer();
7014 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007015 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007016 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007017 if (last && mHwPaused) {
7018 doHwResume = true;
7019 mHwPaused = false;
7020 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007021 }
7022 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7023 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007024 // We have consumed all the buffers of this track.
7025 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007026 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007027 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007028 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007029 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007030 if (presComplete) {
7031 mOutput->presentationComplete();
7032 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007033 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007034 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007035 }
Eric Laurent81784c32012-11-19 14:55:58 -08007036 if (track->isStopped()) {
7037 track->reset();
7038 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007039 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007040 }
7041 } else {
7042 // No buffers for this track. Give it a few chances to
7043 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007044 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007045 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007046 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007047 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007048 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007049 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007050 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007051 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7052 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007053 tracksToRemove->add(track);
7054 // indicate to client process that the track was disabled because of
7055 // underrun; it will then automatically call start() when data is available
7056 track->disable();
7057 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7058 // unlike mixerthread, HAL can be paused for direct output
7059 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7060 "minFrames = %u, mFormat = %#x",
7061 framesReady, minFrames, mFormat);
7062 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7063 doHwPause = true;
7064 mHwPaused = true;
7065 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007066 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007067 } else if (last) {
7068 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007069 }
7070 }
7071 }
7072 }
7073
Eric Laurentd1f69b02014-12-15 14:33:13 -08007074 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007075 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007076 for (size_t i = 0; i < mTracks.size(); i++) {
7077 if (mTracks[i]->isFlushPending()) {
7078 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007079 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007080 }
7081 }
7082 }
7083
7084 // make sure the pause/flush/resume sequence is executed in the right order.
7085 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7086 // before flush and then resume HW. This can happen in case of pause/flush/resume
7087 // if resume is received before pause is executed.
7088 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007089 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007090 status_t result = mOutput->stream->pause();
7091 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007092 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007093 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007094 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007095 flushHw_l();
7096 }
7097 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007098 status_t result = mOutput->stream->resume();
7099 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007100 }
Eric Laurent81784c32012-11-19 14:55:58 -08007101 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007102 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007103
7104 return mixerStatus;
7105}
7106
Andy Hungee58e4a2023-07-07 13:47:37 -07007107void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007108{
Eric Laurent81784c32012-11-19 14:55:58 -08007109 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007110 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007111 // output audio to hardware
7112 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007113 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007114 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007115 status_t status = mActiveTrack->getNextBuffer(&buffer);
7116 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007117 // no need to pad with 0 for compressed audio
7118 if (audio_has_proportional_frames(mFormat)) {
7119 memset(curBuf, 0, frameCount * mFrameSize);
7120 }
Eric Laurent81784c32012-11-19 14:55:58 -08007121 break;
7122 }
7123 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7124 frameCount -= buffer.frameCount;
7125 curBuf += buffer.frameCount * mFrameSize;
7126 mActiveTrack->releaseBuffer(&buffer);
7127 }
Andy Hung2098f272014-02-27 14:00:06 -08007128 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007129 mSleepTimeUs = 0;
7130 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007131 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007132}
7133
Andy Hungee58e4a2023-07-07 13:47:37 -07007134void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007135{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007136 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007137 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007138 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007139 return;
7140 }
Andy Hung85ba3332021-04-27 17:40:26 -07007141 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7142 mSleepTimeUs = mActiveSleepTimeUs;
7143 } else {
7144 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007145 }
Andy Hung85ba3332021-04-27 17:40:26 -07007146 // Note: In S or later, we do not write zeroes for
7147 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007148}
7149
Andy Hungee58e4a2023-07-07 13:47:37 -07007150void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007151{
7152 {
Andy Hung972bec12023-08-31 16:13:39 -07007153 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007154 for (size_t i = 0; i < mTracks.size(); i++) {
7155 if (mTracks[i]->isFlushPending()) {
7156 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007157 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007158 }
7159 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007160 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007161 flushHw_l();
7162 }
7163 }
7164 PlaybackThread::threadLoop_exit();
7165}
7166
7167// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007168bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007169{
7170 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007171 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007172 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007173
Eric Laurent022a5132024-04-12 17:02:51 +00007174 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007175 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007176 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007177 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007178 const auto& mainTrack = mTracks[mTracks.size() - 1];
7179
7180 trackPaused = mainTrack->isPaused();
7181 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7182 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007183 }
7184
Eric Laurent022a5132024-04-12 17:02:51 +00007185 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007186}
7187
Andy Hungc5007f82023-08-29 14:26:09 -07007188// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007189bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007190 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007191{
7192 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007193 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007194
Eric Laurent10351942014-05-08 18:49:52 -07007195 AudioParameter param = AudioParameter(keyValuePair);
7196 int value;
7197 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007198 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007199 }
Eric Laurent10351942014-05-08 18:49:52 -07007200 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7201 // do not accept frame count changes if tracks are open as the track buffer
7202 // size depends on frame count and correct behavior would not be garantied
7203 // if frame count is changed after track creation
7204 if (!mTracks.isEmpty()) {
7205 status = INVALID_OPERATION;
7206 } else {
7207 reconfig = true;
7208 }
7209 }
7210 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007211 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007212 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007213 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007214 if (!mStandby) {
7215 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007216 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007217 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007218 }
Eric Laurent10351942014-05-08 18:49:52 -07007219 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007220 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007221 }
7222 if (status == NO_ERROR && reconfig) {
7223 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007224 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007225 }
7226 }
7227
Dean Wheatley68918102021-03-19 22:09:19 +11007228 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007229}
7230
Andy Hungee58e4a2023-07-07 13:47:37 -07007231uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007232{
7233 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007234 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007235 time = PlaybackThread::activeSleepTimeUs();
7236 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007237 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007238 }
7239 return time;
7240}
7241
Andy Hungee58e4a2023-07-07 13:47:37 -07007242uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007243{
7244 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007245 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007246 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7247 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007248 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007249 }
7250 return time;
7251}
7252
Andy Hungee58e4a2023-07-07 13:47:37 -07007253uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007254{
7255 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007256 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007257 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7258 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007259 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007260 }
7261 return time;
7262}
7263
Andy Hungee58e4a2023-07-07 13:47:37 -07007264void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007265{
7266 PlaybackThread::cacheParameters_l();
7267
7268 // use shorter standby delay as on normal output to release
7269 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007270 // no delay on outputs with HW A/V sync
7271 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007272 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007273 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007274 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007275 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007276 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007277 }
Eric Laurent81784c32012-11-19 14:55:58 -08007278}
7279
Andy Hungee58e4a2023-07-07 13:47:37 -07007280void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007281{
ziyangch8f194f12021-12-01 13:48:04 -08007282 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007283 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007284 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007285 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007286 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007287 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007288 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007289}
7290
Andy Hungee58e4a2023-07-07 13:47:37 -07007291int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007292 // If a VolumeShaper is active, we must wake up periodically to update volume.
7293 const int64_t NS_PER_MS = 1000000;
7294 return mVolumeShaperActive ?
7295 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7296}
7297
Eric Laurent81784c32012-11-19 14:55:58 -08007298// ----------------------------------------------------------------------------
7299
Andy Hungee58e4a2023-07-07 13:47:37 -07007300AsyncCallbackThread::AsyncCallbackThread(
7301 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007302 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007303 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007304 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007305 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007306 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007307{
7308}
7309
Andy Hungee58e4a2023-07-07 13:47:37 -07007310void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007311{
7312 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7313}
7314
Andy Hungee58e4a2023-07-07 13:47:37 -07007315bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007316{
7317 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007318 uint32_t writeAckSequence;
7319 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007320 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007321
7322 {
Andy Hungc5007f82023-08-29 14:26:09 -07007323 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007324 while (!((mWriteAckSequence & 1) ||
7325 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007326 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007327 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007328 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007329 }
7330
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 if (exitPending()) {
7332 break;
7333 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007334 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7335 mWriteAckSequence, mDrainSequence);
7336 writeAckSequence = mWriteAckSequence;
7337 mWriteAckSequence &= ~1;
7338 drainSequence = mDrainSequence;
7339 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007340 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007341 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007342 }
7343 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007344 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007345 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007346 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007347 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007349 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007350 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007351 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007352 if (asyncError != ASYNC_ERROR_NONE) {
7353 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007354 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007355 }
7356 }
7357 }
7358 return false;
7359}
7360
Andy Hungee58e4a2023-07-07 13:47:37 -07007361void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007362{
7363 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007364 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007365 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007366 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007367}
7368
Andy Hungee58e4a2023-07-07 13:47:37 -07007369void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007370{
Andy Hung972bec12023-08-31 16:13:39 -07007371 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007372 // bit 0 is cleared
7373 mWriteAckSequence = sequence << 1;
7374}
7375
Andy Hungee58e4a2023-07-07 13:47:37 -07007376void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007377{
Andy Hung972bec12023-08-31 16:13:39 -07007378 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007379 // ignore unexpected callbacks
7380 if (mWriteAckSequence & 2) {
7381 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007382 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007383 }
7384}
7385
Andy Hungee58e4a2023-07-07 13:47:37 -07007386void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007387{
Andy Hung972bec12023-08-31 16:13:39 -07007388 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007389 // bit 0 is cleared
7390 mDrainSequence = sequence << 1;
7391}
7392
Andy Hungee58e4a2023-07-07 13:47:37 -07007393void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007394{
Andy Hung972bec12023-08-31 16:13:39 -07007395 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007396 // ignore unexpected callbacks
7397 if (mDrainSequence & 2) {
7398 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007399 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007400 }
7401}
7402
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007403void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007404{
Andy Hung972bec12023-08-31 16:13:39 -07007405 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007406 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007407 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007408}
7409
Eric Laurentbfb1b832013-01-07 09:53:42 -08007410
7411// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007412
7413/* static */
7414sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007415 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007416 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7417 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007418 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007419}
7420
Andy Hung583043b2023-07-17 17:05:00 -07007421OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007422 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7423 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007424 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007425 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007426{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007427 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007428 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007429 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007430}
7431
Andy Hungee58e4a2023-07-07 13:47:37 -07007432void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007433{
7434 if (mFlushPending || mHwPaused) {
7435 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007436 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007437 flushHw_l();
7438 } else {
7439 mMixerStatus = MIXER_DRAIN_ALL;
7440 threadLoop_drain();
7441 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007442 if (mUseAsyncWrite) {
7443 ALOG_ASSERT(mCallbackThread != 0);
7444 mCallbackThread->exit();
7445 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007446 PlaybackThread::threadLoop_exit();
7447}
7448
Andy Hungee58e4a2023-07-07 13:47:37 -07007449PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007450 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007451)
7452{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007453 size_t count = mActiveTracks.size();
7454
7455 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007456 bool doHwPause = false;
7457 bool doHwResume = false;
7458
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007459 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007460
Eric Laurentbfb1b832013-01-07 09:53:42 -08007461 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007462 for (const sp<IAfTrack>& t : mActiveTracks) {
7463 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007464#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007465 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007466#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007467 // Only consider last track started for volume and mixer state control.
7468 // In theory an older track could underrun and restart after the new one starts
7469 // but as we only care about the transition phase between two tracks on a
7470 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007471 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007472 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007473
Haynes Mathew George7844f672014-01-15 12:32:55 -08007474 if (track->isInvalid()) {
7475 ALOGW("An invalidated track shouldn't be in active list");
7476 tracksToRemove->add(track);
7477 continue;
7478 }
7479
Andy Hung8d31fd22023-06-26 19:20:57 -07007480 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007481 ALOGW("An idle track shouldn't be in active list");
7482 continue;
7483 }
7484
Kuowei Li23666472021-01-20 10:23:25 +08007485 if (track->isPausePending()) {
7486 track->pauseAck();
7487 // It is possible a track might have been flushed or stopped.
7488 // Other operations such as flush pending might occur on the next prepare.
7489 if (track->isPausing()) {
7490 track->setPaused();
7491 }
7492 // Always perform pause if last, as an immediate flush will change
7493 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007494 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007495 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007496 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007497 mHwPaused = true;
7498 }
7499 // If we were part way through writing the mixbuffer to
7500 // the HAL we must save this until we resume
7501 // BUG - this will be wrong if a different track is made active,
7502 // in that case we want to discard the pending data in the
7503 // mixbuffer and tell the client to present it again when the
7504 // track is resumed
7505 mPausedWriteLength = mCurrentWriteLength;
7506 mPausedBytesRemaining = mBytesRemaining;
7507 mBytesRemaining = 0; // stop writing
7508 }
7509 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007510 } else if (track->isFlushPending()) {
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 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007516 track->flushAck();
7517 if (last) {
7518 mFlushPending = true;
7519 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007520 } else if (track->isResumePending()){
7521 track->resumeAck();
7522 if (last) {
7523 if (mPausedBytesRemaining) {
7524 // Need to continue write that was interrupted
7525 mCurrentWriteLength = mPausedWriteLength;
7526 mBytesRemaining = mPausedBytesRemaining;
7527 mPausedBytesRemaining = 0;
7528 }
7529 if (mHwPaused) {
7530 doHwResume = true;
7531 mHwPaused = false;
7532 // threadLoop_mix() will handle the case that we need to
7533 // resume an interrupted write
7534 }
7535 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007536 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007537
Eric Laurent3df841a2016-07-15 15:15:40 -07007538 mLeftVolFloat = mRightVolFloat = -1.0;
7539
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007540 // Do not handle new data in this iteration even if track->framesReady()
7541 mixerStatus = MIXER_TRACKS_ENABLED;
7542 }
7543 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007544 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007545 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007546 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7547 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007548 if (last) {
7549 // make sure processVolume_l() will apply new volume even if 0
7550 mLeftVolFloat = mRightVolFloat = -1.0;
7551 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007552 }
7553
7554 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007555 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007556 if (previousTrack != 0) {
7557 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007558 // Flush any data still being written from last track
7559 mBytesRemaining = 0;
7560 if (mPausedBytesRemaining) {
7561 // Last track was paused so we also need to flush saved
7562 // mixbuffer state and invalidate track so that it will
7563 // re-submit that unwritten data when it is next resumed
7564 mPausedBytesRemaining = 0;
7565 // Invalidate is a bit drastic - would be more efficient
7566 // to have a flag to tell client that some of the
7567 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007568 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007569 }
7570 // flush data already sent to the DSP if changing audio session as audio
7571 // comes from a different source. Also invalidate previous track to force a
7572 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007573 if (previousTrack->sessionId() != track->sessionId()) {
7574 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007575 }
7576 }
7577 }
7578 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007579 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007580 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007581 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007582 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007583 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007584 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007585 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007586 mixerStatus = MIXER_TRACKS_READY;
7587 }
7588 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007589 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007590 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007591 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007592 // Hardware buffer can hold a large amount of audio so we must
7593 // wait for all current track's data to drain before we say
7594 // that the track is stopped.
7595 if (mBytesRemaining == 0) {
7596 // Only start draining when all data in mixbuffer
7597 // has been written
7598 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007599 track->setState(IAfTrackBase::STOPPING_2);
7600 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007601 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7602 if (last && !mStandby) {
7603 // do not modify drain sequence if we are already draining. This happens
7604 // when resuming from pause after drain.
7605 if ((mDrainSequence & 1) == 0) {
7606 mSleepTimeUs = 0;
7607 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7608 mixerStatus = MIXER_DRAIN_TRACK;
7609 mDrainSequence += 2;
7610 }
7611 if (mHwPaused) {
7612 // It is possible to move from PAUSED to STOPPING_1 without
7613 // a resume so we must ensure hardware is running
7614 doHwResume = true;
7615 mHwPaused = false;
7616 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007617 }
7618 }
Eric Laurente93cc032016-05-05 10:15:10 -07007619 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007620 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007621 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007622 }
7623 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007624 // Drain has completed or we are in standby, signal presentation complete
7625 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007626 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007627 mOutput->presentationComplete();
7628 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007629 track->reset();
7630 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007631 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007632 if (!mUseAsyncWrite) {
7633 // If we don't get explicit drain notification we must
7634 // register discontinuity regardless of whether this is
7635 // the previous (!last) or the upcoming (last) track
7636 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007637 mTimestampVerifier.discontinuity(
7638 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007639 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007640 }
7641 } else {
7642 // No buffers for this track. Give it a few chances to
7643 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007644 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007645 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007646 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007647 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007648 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007649 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007650 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7651 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007652 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007653 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007654 // it will then automatically call start() when data is available
7655 track->disable();
7656 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007657 } else if (last){
7658 mixerStatus = MIXER_TRACKS_ENABLED;
7659 }
7660 }
7661 }
7662 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007663 if (track->isReady()) { // check ready to prevent premature start.
7664 processVolume_l(track, last);
7665 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007666 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007667
Eric Laurentea0fade2013-10-04 16:23:48 -07007668 // make sure the pause/flush/resume sequence is executed in the right order.
7669 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7670 // before flush and then resume HW. This can happen in case of pause/flush/resume
7671 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007672 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007673 status_t result = mOutput->stream->pause();
7674 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007675 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007676 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007677 if (mFlushPending) {
7678 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007679 }
Eric Laurentfd477972013-10-25 18:10:40 -07007680 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007681 status_t result = mOutput->stream->resume();
7682 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007683 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007684
Eric Laurentbfb1b832013-01-07 09:53:42 -08007685 // remove all the tracks that need to be...
7686 removeTracks_l(*tracksToRemove);
7687
7688 return mixerStatus;
7689}
7690
Eric Laurentbfb1b832013-01-07 09:53:42 -08007691// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007692bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007693{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007694 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7695 mWriteAckSequence, mDrainSequence);
7696 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007697 return true;
7698 }
7699 return false;
7700}
7701
Andy Hungee58e4a2023-07-07 13:47:37 -07007702bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007703{
Andy Hung972bec12023-08-31 16:13:39 -07007704 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007705 return waitingAsyncCallback_l();
7706}
7707
Andy Hungee58e4a2023-07-07 13:47:37 -07007708void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007709{
Eric Laurente659ef42014-09-29 13:06:46 -07007710 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007711 // Flush anything still waiting in the mixbuffer
7712 mCurrentWriteLength = 0;
7713 mBytesRemaining = 0;
7714 mPausedWriteLength = 0;
7715 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007716 // reset bytes written count to reflect that DSP buffers are empty after flush.
7717 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007718
Eric Laurentbfb1b832013-01-07 09:53:42 -08007719 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007720 // discard any pending drain or write ack by incrementing sequence
7721 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7722 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007723 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007724 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7725 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007726 }
7727}
7728
Andy Hungee58e4a2023-07-07 13:47:37 -07007729void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007730{
Andy Hung972bec12023-08-31 16:13:39 -07007731 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007732 if (PlaybackThread::invalidateTracks_l(streamType)) {
7733 mFlushPending = true;
7734 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007735}
7736
Andy Hungee58e4a2023-07-07 13:47:37 -07007737void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007738 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007739 if (PlaybackThread::invalidateTracks_l(portIds)) {
7740 mFlushPending = true;
7741 }
7742}
7743
Eric Laurentbfb1b832013-01-07 09:53:42 -08007744// ----------------------------------------------------------------------------
7745
Andy Hungee58e4a2023-07-07 13:47:37 -07007746/* static */
7747sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007748 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007749 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007750 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007751}
7752
Andy Hung583043b2023-07-17 17:05:00 -07007753DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007754 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007755 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007756 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007757 mWaitTimeMs(UINT_MAX)
7758{
7759 addOutputTrack(mainThread);
7760}
7761
Andy Hungee58e4a2023-07-07 13:47:37 -07007762DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007763{
7764 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7765 mOutputTracks[i]->destroy();
7766 }
7767}
7768
Andy Hungee58e4a2023-07-07 13:47:37 -07007769void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007770{
7771 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007772 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007773 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007774 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007775 if (mMixerBufferValid) {
7776 memset(mMixerBuffer, 0, mMixerBufferSize);
7777 } else {
7778 memset(mSinkBuffer, 0, mSinkBufferSize);
7779 }
Eric Laurent81784c32012-11-19 14:55:58 -08007780 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007781 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007782 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007783 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007784 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007785}
7786
Andy Hungee58e4a2023-07-07 13:47:37 -07007787void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007788{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007789 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007790 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007791 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007792 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007793 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007794 }
7795 } else if (mBytesWritten != 0) {
7796 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7797 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007798 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007799 } else {
7800 // flush remaining overflow buffers in output tracks
7801 writeFrames = 0;
7802 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007803 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007804 }
7805}
7806
Andy Hungee58e4a2023-07-07 13:47:37 -07007807ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007808{
7809 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007810 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7811
7812 // Consider the first OutputTrack for timestamp and frame counting.
7813
7814 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7815 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7816 // we always claim success.
7817 if (i == 0) {
7818 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7819 ALOGD_IF(correction != 0 && writeFrames != 0,
7820 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7821 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7822 mFramesWritten -= correction;
7823 }
7824
7825 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007826 }
Andy Hungcf10d742020-04-28 15:38:24 -07007827 if (mStandby) {
7828 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007829 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007830 mStandby = false;
7831 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007832 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007833}
7834
Andy Hungee58e4a2023-07-07 13:47:37 -07007835void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007836{
7837 // DuplicatingThread implements standby by stopping all tracks
7838 for (size_t i = 0; i < outputTracks.size(); i++) {
7839 outputTracks[i]->stop();
7840 }
7841}
7842
Andy Hung8a5abfd2023-12-07 19:35:12 -08007843void DuplicatingThread::threadLoop_exit()
7844{
7845 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7846 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7847 // Do so here in the threadLoop_exit().
7848
7849 SortedVector <sp<IAfOutputTrack>> localTracks;
7850 {
7851 audio_utils::lock_guard l(mutex());
7852 localTracks = std::move(mOutputTracks);
7853 mOutputTracks.clear();
7854 }
7855 localTracks.clear();
7856 outputTracks.clear();
7857 PlaybackThread::threadLoop_exit();
7858}
7859
Andy Hungee58e4a2023-07-07 13:47:37 -07007860void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007861{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007862 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007863
7864 std::stringstream ss;
7865 const size_t numTracks = mOutputTracks.size();
7866 ss << " " << numTracks << " OutputTracks";
7867 if (numTracks > 0) {
7868 ss << ":";
7869 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007870 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007871 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007872 if (thread.get() != nullptr) {
7873 ss << thread.get() << ", " << thread->id();
7874 } else {
7875 ss << "null";
7876 }
7877 ss << ")";
7878 }
7879 }
7880 ss << "\n";
7881 std::string result = ss.str();
7882 write(fd, result.c_str(), result.size());
7883}
7884
Andy Hungee58e4a2023-07-07 13:47:37 -07007885void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007886{
7887 outputTracks = mOutputTracks;
7888}
7889
Andy Hungee58e4a2023-07-07 13:47:37 -07007890void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007891{
7892 outputTracks.clear();
7893}
7894
Andy Hungee58e4a2023-07-07 13:47:37 -07007895void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007896{
Andy Hung972bec12023-08-31 16:13:39 -07007897 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007898 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7899 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7900 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7901 const size_t frameCount =
7902 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7903 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7904 // from different OutputTracks and their associated MixerThreads (e.g. one may
7905 // nearly empty and the other may be dropping data).
7906
Svet Ganov33761132021-05-13 22:51:08 +00007907 // TODO b/182392769: use attribution source util, move to server edge
7908 AttributionSourceState attributionSource = AttributionSourceState();
7909 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007910 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007911 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007912 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007913 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007914 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007915 this,
7916 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007917 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007918 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007919 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007920 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007921 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7922 if (status != NO_ERROR) {
7923 ALOGE("addOutputTrack() initCheck failed %d", status);
7924 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007925 }
Andy Hung6b137d12024-08-27 22:35:17 +00007926 if (!audioserver_flags::portid_volume_management()) {
7927 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7928 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007929 mOutputTracks.add(outputTrack);
7930 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7931 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007932}
7933
Andy Hungee58e4a2023-07-07 13:47:37 -07007934void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007935{
Andy Hung972bec12023-08-31 16:13:39 -07007936 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007937 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7938 if (mOutputTracks[i]->thread() == thread) {
7939 mOutputTracks[i]->destroy();
7940 mOutputTracks.removeAt(i);
7941 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007942 // NO_THREAD_SAFETY_ANALYSIS
7943 // Lambda workaround: as thread != this
7944 // we can safely call the remote thread getOutput.
7945 const bool equalOutput =
7946 [&](){ return thread->getOutput() == mOutput; }();
7947 if (equalOutput) {
7948 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007949 }
Eric Laurent81784c32012-11-19 14:55:58 -08007950 return;
7951 }
7952 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007953 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007954}
7955
Andy Hungc5007f82023-08-29 14:26:09 -07007956// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007957void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007958{
7959 mWaitTimeMs = UINT_MAX;
7960 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007961 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007962 if (strong != 0) {
7963 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7964 if (waitTimeMs < mWaitTimeMs) {
7965 mWaitTimeMs = waitTimeMs;
7966 }
7967 }
7968 }
7969}
7970
Andy Hungee58e4a2023-07-07 13:47:37 -07007971bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007972{
7973 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007974 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007975 if (thread == 0) {
7976 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7977 outputTracks[i].get());
7978 return false;
7979 }
Andy Hung87c693c2023-07-06 20:56:16 -07007980 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007981 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007982 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007983 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7984 thread.get());
7985 return false;
7986 }
7987 }
7988 return true;
7989}
7990
Andy Hungee58e4a2023-07-07 13:47:37 -07007991void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007992 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007993{
Kevin Rocard12381092018-04-11 09:19:59 -07007994 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7995 outputTrack->setMetadatas(metadata.tracks);
7996 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007997}
7998
Andy Hungee58e4a2023-07-07 13:47:37 -07007999uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08008000{
Andy Hung7a6a0f02023-11-29 13:42:08 -08008001 // return half the wait time in microseconds.
8002 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08008003}
8004
Andy Hungee58e4a2023-07-07 13:47:37 -07008005void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008006{
8007 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8008 updateWaitTime_l();
8009
8010 MixerThread::cacheParameters_l();
8011}
8012
Eric Laurentb3f315a2021-07-13 15:09:05 +02008013// ----------------------------------------------------------------------------
8014
Andy Hungee58e4a2023-07-07 13:47:37 -07008015/* static */
8016sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008017 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008018 AudioStreamOut* output,
8019 audio_io_handle_t id,
8020 bool systemReady,
8021 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008022 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008023}
8024
Andy Hung583043b2023-07-17 17:05:00 -07008025SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008026 AudioStreamOut* output,
8027 audio_io_handle_t id,
8028 bool systemReady,
8029 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008030 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008031{
8032}
8033
Andy Hungee58e4a2023-07-07 13:47:37 -07008034void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008035 // if mSupportedLatencyModes is empty, the HAL stream does not support
8036 // latency mode control and we can exit.
8037 if (mSupportedLatencyModes.empty()) {
8038 return;
8039 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008040 // Do not update the HAL latency mode if no track is active
8041 if (mActiveTracks.isEmpty()) {
8042 return;
8043 }
8044
Eric Laurent68a40a82022-05-03 18:15:04 +02008045 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8046 if (mSupportedLatencyModes.size() == 1) {
8047 // If the HAL only support one latency mode currently, confirm the choice
8048 latencyMode = mSupportedLatencyModes[0];
8049 } else if (mSupportedLatencyModes.size() > 1) {
8050 // Request low latency if:
8051 // - The low latency mode is requested by the spatializer controller
8052 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8053 // AND
8054 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008055 for (const auto& track : mActiveTracks) {
8056 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008057 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008058 break;
8059 }
8060 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008061 }
8062
8063 if (latencyMode != mSetLatencyMode) {
8064 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008065 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8066 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008067 if (status == NO_ERROR) {
8068 mSetLatencyMode = latencyMode;
8069 }
8070 }
8071}
8072
Andy Hungee58e4a2023-07-07 13:47:37 -07008073status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008074 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008075 return BAD_VALUE;
8076 }
Andy Hung972bec12023-08-31 16:13:39 -07008077 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008078 mRequestedLatencyMode = mode;
8079 return NO_ERROR;
8080}
8081
Andy Hungee58e4a2023-07-07 13:47:37 -07008082void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008083NO_THREAD_SAFETY_ANALYSIS
8084// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008085{
8086 bool hasVirtualizer = false;
8087 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008088 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008089 {
Andy Hung972bec12023-08-31 16:13:39 -07008090 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008091 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008092 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008093 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008094 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8095 }
8096
8097 finalDownMixer = mFinalDownMixer;
8098 mFinalDownMixer.clear();
8099 }
8100
8101 if (hasVirtualizer) {
8102 if (finalDownMixer != nullptr) {
8103 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008104 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008105 }
8106 finalDownMixer.clear();
8107 } else if (!hasDownMixer) {
8108 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008109 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008110 EFFECT_UIID_DOWNMIX, &descriptors);
8111 if (status != NO_ERROR) {
8112 return;
8113 }
8114 ALOG_ASSERT(!descriptors.empty(),
8115 "%s getDescriptors() returned no error but empty list", __func__);
8116
8117 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8118 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008119 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008120
8121 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8122 ALOGW("%s error creating downmixer %d", __func__, status);
8123 finalDownMixer.clear();
8124 } else {
8125 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008126 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008127 }
8128 }
8129
8130 {
Andy Hung972bec12023-08-31 16:13:39 -07008131 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008132 mFinalDownMixer = finalDownMixer;
8133 }
8134}
8135
Andy Hunge2514462023-12-06 14:59:24 -08008136void SpatializerThread::threadLoop_exit()
8137{
8138 // The Spatializer EffectHandle must be released on the PlaybackThread
8139 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8140 mFinalDownMixer.clear();
8141
8142 PlaybackThread::threadLoop_exit();
8143}
8144
Eric Laurent81784c32012-11-19 14:55:58 -08008145// ----------------------------------------------------------------------------
8146// Record
8147// ----------------------------------------------------------------------------
8148
Andy Hung583043b2023-07-17 17:05:00 -07008149sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008150 AudioStreamIn* input,
8151 audio_io_handle_t id,
8152 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008153 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008154}
8155
Andy Hung583043b2023-07-17 17:05:00 -07008156RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008157 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008158 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008159 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008160 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008161 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008162 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008163 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008164 mActiveTracks(&this->mLocalLog),
8165 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008166 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008167 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008168 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8169 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008170 // mFastCapture below
8171 , mFastCaptureFutex(0)
8172 // mInputSource
8173 // mPipeSink
8174 // mPipeSource
8175 , mPipeFramesP2(0)
8176 // mPipeMemory
8177 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008178 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008179 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008180{
Glenn Kastend7dca052015-03-05 16:05:54 -08008181 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008182 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008183
George Burgess IVa8f90c12020-05-14 11:27:19 -07008184 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008185 mIsMsdDevice = strcmp(
8186 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8187 }
8188
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008189 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008190
Andy Hungc8fddf32018-08-08 18:32:37 -07008191 // TODO: We may also match on address as well as device type for
8192 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008193 // TODO: This property should be ensure that only contains one single device type.
8194 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8195 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008196 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8197 : AUDIO_DEVICE_NONE));
8198
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008199 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008200 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008201 size_t numCounterOffers = 0;
8202 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008203#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008204 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008205#else
8206 (void)
8207#endif
8208 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008209 ALOG_ASSERT(index == 0);
8210
8211 // initialize fast capture depending on configuration
8212 bool initFastCapture;
8213 switch (kUseFastCapture) {
8214 case FastCapture_Never:
8215 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008216 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008217 break;
8218 case FastCapture_Always:
8219 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008220 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008221 break;
8222 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008223 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008224 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008225 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008226 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8227 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8228 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008229 break;
8230 // case FastCapture_Dynamic:
8231 }
8232
8233 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008234 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008235 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008236 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8237 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008238 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008239 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008240 const sp<MemoryDealer> roHeap(readOnlyHeap());
8241 sp<IMemory> pipeMemory;
8242 if ((roHeap == 0) ||
8243 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008244 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008245 ALOGE("not enough memory for pipe buffer size=%zu; "
8246 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8247 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8248 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008249 goto failed;
8250 }
8251 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8252 memset(pipeBuffer, 0, pipeSize);
8253 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008254 const NBAIO_Format offersFast[1] = {format};
8255 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008256 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008257 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008258 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008259 mPipeSink = pipe;
8260 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008261 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008262 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008263 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008264 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008265 mPipeSource = pipeReader;
8266 mPipeFramesP2 = pipeFramesP2;
8267 mPipeMemory = pipeMemory;
8268
8269 // create fast capture
8270 mFastCapture = new FastCapture();
8271 FastCaptureStateQueue *sq = mFastCapture->sq();
8272#ifdef STATE_QUEUE_DUMP
8273 // FIXME
8274#endif
8275 FastCaptureState *state = sq->begin();
8276 state->mCblk = NULL;
8277 state->mInputSource = mInputSource.get();
8278 state->mInputSourceGen++;
8279 state->mPipeSink = pipe;
8280 state->mPipeSinkGen++;
8281 state->mFrameCount = mFrameCount;
8282 state->mCommand = FastCaptureState::COLD_IDLE;
8283 // already done in constructor initialization list
8284 //mFastCaptureFutex = 0;
8285 state->mColdFutexAddr = &mFastCaptureFutex;
8286 state->mColdGen++;
8287 state->mDumpState = &mFastCaptureDumpState;
8288#ifdef TEE_SINK
8289 // FIXME
8290#endif
Andy Hung583043b2023-07-17 17:05:00 -07008291 mFastCaptureNBLogWriter =
8292 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008293 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8294 sq->end();
8295 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8296
8297 // start the fast capture
8298 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8299 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008300 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008301 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008302#ifdef AUDIO_WATCHDOG
8303 // FIXME
8304#endif
8305
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008306 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008307 }
Andy Hung8946a282018-04-19 20:04:56 -07008308#ifdef TEE_SINK
8309 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8310 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8311#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008312failed: ;
8313
8314 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008315}
8316
Andy Hungee58e4a2023-07-07 13:47:37 -07008317RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008318{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008319 if (mFastCapture != 0) {
8320 FastCaptureStateQueue *sq = mFastCapture->sq();
8321 FastCaptureState *state = sq->begin();
8322 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8323 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8324 if (old == -1) {
8325 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8326 }
8327 }
8328 state->mCommand = FastCaptureState::EXIT;
8329 sq->end();
8330 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8331 mFastCapture->join();
8332 mFastCapture.clear();
8333 }
Andy Hung583043b2023-07-17 17:05:00 -07008334 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8335 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008336 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008337}
8338
Andy Hungee58e4a2023-07-07 13:47:37 -07008339void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008340{
Glenn Kastend7dca052015-03-05 16:05:54 -08008341 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008342}
8343
Andy Hungee58e4a2023-07-07 13:47:37 -07008344void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008345{
8346 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008347 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008348 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008349 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008350 track->invalidate();
8351 }
8352 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008353 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008354}
8355
Andy Hungee58e4a2023-07-07 13:47:37 -07008356bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008357{
Eric Laurent81784c32012-11-19 14:55:58 -08008358 nsecs_t lastWarning = 0;
8359
8360 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008361
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008362reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008363 {
Andy Hung972bec12023-08-31 16:13:39 -07008364 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008365 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008366 }
8367
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008368 // used to request a deferred sleep, to be executed later while mutex is unlocked
8369 uint32_t sleepUs = 0;
8370
Andy Hung95c94a22023-10-20 16:41:18 -07008371 // timestamp correction enable is determined under lock, used in processing step.
8372 bool timestampCorrectionEnabled = false;
8373
Andy Hung446f4df2019-02-21 12:26:41 -08008374 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8375
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008376 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008377 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008378 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8379 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008380 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008381 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008382
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008383 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008384 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008385
Glenn Kasten735f45f2014-08-18 15:51:59 -07008386 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008387 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008388
Glenn Kasten735f45f2014-08-18 15:51:59 -07008389 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008390 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008391
Eric Laurent33403f02020-05-29 18:35:06 -07008392 bool silenceFastCapture = false;
8393
Andy Hungc5007f82023-08-29 14:26:09 -07008394 { // scope for mutex()
8395 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008396
Eric Laurent021cf962014-05-13 10:18:14 -07008397 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008398
Eric Laurent000a4192014-01-29 15:17:32 -08008399 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008400 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008401 if (exitPending()) {
8402 break;
8403 }
8404
Eric Laurent5c25d562016-07-13 17:17:45 -07008405 // sleep with mutex unlocked
8406 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008407 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008408 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008409 ATRACE_END();
8410 sleepUs = 0;
8411 continue;
8412 }
8413
Glenn Kasten2b806402013-11-20 16:37:38 -08008414 // if no active track(s), then standby and release wakelock
8415 size_t size = mActiveTracks.size();
8416 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008417 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008418 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008419 releaseWakeLock_l();
8420 ALOGV("RecordThread: loop stopping");
8421 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008422 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008423 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008424 goto reacquire_wakelock;
8425 }
8426
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008427 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008428 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008429 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008430 if (activeTrack) { // ensure track release is outside lock.
8431 oldActiveTracks.emplace_back(std::move(activeTrack));
8432 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008433 activeTrack = mActiveTracks[i];
8434 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008435 if (activeTrack->isFastTrack()) {
8436 ALOG_ASSERT(fastTrackToRemove == 0);
8437 fastTrackToRemove = activeTrack;
8438 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008439 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008440 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008441 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008442 continue;
8443 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008444
Andy Hung8d31fd22023-06-26 19:20:57 -07008445 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008446 switch (activeTrackState) {
8447
Andy Hung8d31fd22023-06-26 19:20:57 -07008448 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008449 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008450 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008451 if (activeTrack->isFastTrack()) {
8452 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8453 // Keep a ref on fast track to wait for FastCapture thread to get updated
8454 // state before potential track removal
8455 fastTrackToRemove = activeTrack;
8456 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008457 doBroadcast = true;
8458 size--;
8459 continue;
8460
Andy Hung8d31fd22023-06-26 19:20:57 -07008461 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008462 sleepUs = 10000;
8463 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008464 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008465 continue;
8466
Andy Hung8d31fd22023-06-26 19:20:57 -07008467 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008468 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008469 if (mStandby) {
8470 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008471 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008472 mStandby = false;
8473 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008474 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008475 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008476 break;
8477
Andy Hung8d31fd22023-06-26 19:20:57 -07008478 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008479 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008480 break;
8481
Andy Hung8d31fd22023-06-26 19:20:57 -07008482 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8483 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8484 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008485 default:
Andy Hungce685402018-10-05 17:23:27 -07008486 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8487 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008488 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008489
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008490 if (activeTrack->isFastTrack()) {
8491 ALOG_ASSERT(!mFastTrackAvail);
8492 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008493 // if the active fast track is silenced either:
8494 // 1) silence the whole capture from fast capture buffer if this is
8495 // the only active track
8496 // 2) invalidate this track: this will cause the client to reconnect and possibly
8497 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008498 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008499 if (activeTrack->isSilenced()) {
8500 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008501 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008502 } else {
8503 silenceFastCapture = true;
8504 }
8505 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008506 // Invalidate fast tracks if access to audio history is required as this is not
8507 // possible with fast tracks. Once the fast track has been invalidated, no new
8508 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8509 if (mMaxSharedAudioHistoryMs != 0) {
8510 invalidate = true;
8511 }
8512 if (invalidate) {
8513 activeTrack->invalidate();
8514 ALOG_ASSERT(fastTrackToRemove == 0);
8515 fastTrackToRemove = activeTrack;
8516 removeTrack_l(activeTrack);
8517 mActiveTracks.remove(activeTrack);
8518 size--;
8519 continue;
8520 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008521 fastTrack = activeTrack;
8522 }
Eric Laurent33403f02020-05-29 18:35:06 -07008523
8524 activeTracks.add(activeTrack);
8525 i++;
8526
Glenn Kasten9e982352013-08-14 14:39:50 -07008527 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008528
Andy Hungab65b182023-09-06 19:41:47 -07008529 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008530
Kevin Rocard069c2712018-03-29 19:09:14 -07008531 updateMetadata_l();
8532
Eric Laurent5c25d562016-07-13 17:17:45 -07008533 if (allStopped) {
8534 standbyIfNotAlreadyInStandby();
8535 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008536 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008537 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008538 }
8539
8540 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008541 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008542 if (sleepUs == 0) {
8543 sleepUs = kRecordThreadSleepUs;
8544 }
8545 continue;
8546 }
8547 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008548
Andy Hung95c94a22023-10-20 16:41:18 -07008549 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008550 lockEffectChains_l(effectChains);
8551 }
8552
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008553 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008554
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008555 size_t size = effectChains.size();
8556 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008557 // thread mutex is not locked, but effect chain is locked
8558 effectChains[i]->process_l();
8559 }
8560
Glenn Kasten735f45f2014-08-18 15:51:59 -07008561 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008562 if (mFastCapture != 0) {
8563 FastCaptureStateQueue *sq = mFastCapture->sq();
8564 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008565 bool didModify = false;
8566 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008567 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8568 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8569 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8570 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8571 if (old == -1) {
8572 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8573 }
8574 }
8575 state->mCommand = FastCaptureState::READ_WRITE;
8576#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008577 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008578 FastThreadDumpState::kSamplingNforLowRamDevice :
8579 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008580#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008581 didModify = true;
8582 }
8583 audio_track_cblk_t *cblkOld = state->mCblk;
8584 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8585 if (cblkNew != cblkOld) {
8586 state->mCblk = cblkNew;
8587 // block until acked if removing a fast track
8588 if (cblkOld != NULL) {
8589 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8590 }
8591 didModify = true;
8592 }
jiabin01c8f562018-07-19 17:47:28 -07008593 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8594 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8595 if (state->mFastPatchRecordBufferProvider != abp) {
8596 state->mFastPatchRecordBufferProvider = abp;
8597 state->mFastPatchRecordFormat = fastTrack == 0 ?
8598 AUDIO_FORMAT_INVALID : fastTrack->format();
8599 didModify = true;
8600 }
Eric Laurent33403f02020-05-29 18:35:06 -07008601 if (state->mSilenceCapture != silenceFastCapture) {
8602 state->mSilenceCapture = silenceFastCapture;
8603 didModify = true;
8604 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008605 sq->end(didModify);
8606 if (didModify) {
8607 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008608#if 0
8609 if (kUseFastCapture == FastCapture_Dynamic) {
8610 mNormalSource = mPipeSource;
8611 }
8612#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008613 }
8614 }
8615
Glenn Kasten735f45f2014-08-18 15:51:59 -07008616 // now run the fast track destructor with thread mutex unlocked
8617 fastTrackToRemove.clear();
8618
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008619 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8620 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8621 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8622 // If destination is non-contiguous, first read past the nominal end of buffer, then
8623 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008624
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008625 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008626 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008627 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008628
8629 // If an NBAIO source is present, use it to read the normal capture's data
8630 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008631 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008632
8633 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8634 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8635 // we immediately retry the read() to get data and prevent another overflow.
8636 for (int retries = 0; retries <= 2; ++retries) {
8637 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8638 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8639 framesToRead);
8640 if (framesRead != OVERRUN) break;
8641 }
8642
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008643 const ssize_t availableToRead = mPipeSource->availableToRead();
8644 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008645 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008646 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008647 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8648 "more frames to read than fifo size, %zd > %zu",
8649 availableToRead, mPipeFramesP2);
8650 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8651 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8652 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8653 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008654 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8655 }
8656 if (framesRead < 0) {
8657 status_t status = (status_t) framesRead;
8658 switch (status) {
8659 case OVERRUN:
8660 ALOGW("overrun on read from pipe");
8661 framesRead = 0;
8662 break;
8663 case NEGOTIATE:
8664 ALOGE("re-negotiation is needed");
8665 framesRead = -1; // Will cause an attempt to recover.
8666 break;
8667 default:
8668 ALOGE("unknown error %d on read from pipe", status);
8669 break;
8670 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008671 }
8672 // otherwise use the HAL / AudioStreamIn directly
8673 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008674 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008675 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008676 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008677 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008678 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008679 if (result < 0) {
8680 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008681 } else {
8682 framesRead = bytesRead / mFrameSize;
8683 }
8684 }
8685
Andy Hung446f4df2019-02-21 12:26:41 -08008686 const int64_t lastIoEndNs = systemTime(); // end IO timing
8687
Andy Hung3f0c9022016-01-15 17:49:46 -08008688 // Update server timestamp with server stats
8689 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008690 if (framesRead >= 0) {
8691 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8692 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8693 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008694
8695 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008696 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008697 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008698 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008699 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8700 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8701 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008702 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008703 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8704
8705 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008706 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008707 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008708 id(), (long long)time, (long long)position);
8709 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8710 position = correctedTimestamp.mFrames;
8711 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008712 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008713 id(), (long long)time, (long long)position);
8714 }
8715
Andy Hung3f0c9022016-01-15 17:49:46 -08008716 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8717 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8718 // Note: In general record buffers should tend to be empty in
8719 // a properly running pipeline.
8720 //
8721 // Also, it is not advantageous to call get_presentation_position during the read
8722 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008723 } else {
8724 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008725 }
8726 }
Andy Hunge6c37112019-02-26 17:38:10 -08008727
8728 // From the timestamp, input read latency is negative output write latency.
8729 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008730 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008731 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8732 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8733 mLatencyMs.add(latencyMs);
8734 }
8735
Andy Hung3f0c9022016-01-15 17:49:46 -08008736 // Use this to track timestamp information
8737 // ALOGD("%s", mTimestamp.toString().c_str());
8738
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008739 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008740 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008741 // Force input into standby so that it tries to recover at next read attempt
8742 inputStandBy();
8743 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008744 }
8745 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008746 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008747 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008748 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008749 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008750
Andy Hung8946a282018-04-19 20:04:56 -07008751#ifdef TEE_SINK
8752 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8753#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008754 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008755 {
8756 size_t part1 = mRsmpInFramesP2 - rear;
8757 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008758 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008759 (framesRead - part1) * mFrameSize);
8760 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008761 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008762 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008763
8764 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008765
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008766 // loop over each active track
8767 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008768 if (activeTrack) { // ensure track release is outside lock.
8769 oldActiveTracks.emplace_back(std::move(activeTrack));
8770 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008771 activeTrack = activeTracks[i];
8772
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008773 // skip fast tracks, as those are handled directly by FastCapture
8774 if (activeTrack->isFastTrack()) {
8775 continue;
8776 }
8777
Andy Hung73c02e42015-03-29 01:13:58 -07008778 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008779 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8780
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008781 enum {
8782 OVERRUN_UNKNOWN,
8783 OVERRUN_TRUE,
8784 OVERRUN_FALSE
8785 } overrun = OVERRUN_UNKNOWN;
8786
8787 // loop over getNextBuffer to handle circular sink
8788 for (;;) {
8789
Andy Hung8d31fd22023-06-26 19:20:57 -07008790 activeTrack->sinkBuffer().frameCount = ~0;
8791 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8792 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008793 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8794
Andy Hung73c02e42015-03-29 01:13:58 -07008795 // check available frames and handle overrun conditions
8796 // if the record track isn't draining fast enough.
8797 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008798 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008799 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008800 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008801 overrun = OVERRUN_TRUE;
8802 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008803 if (framesOut == 0 || framesIn == 0) {
8804 break;
8805 }
8806
Andy Hung6770c6f2015-04-07 13:43:36 -07008807 // Don't allow framesOut to be larger than what is possible with resampling
8808 // from framesIn.
8809 // This isn't strictly necessary but helps limit buffer resizing in
8810 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008811 if (audio_is_linear_pcm(activeTrack->format())) {
8812 framesOut = min(framesOut,
8813 destinationFramesPossible(
8814 framesIn, mSampleRate, activeTrack->sampleRate()));
8815 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008816
8817 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008818 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008819 // straight from RecordThread buffer to RecordTrack buffer.
8820 AudioBufferProvider::Buffer buffer;
8821 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008822 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008823 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008824 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008825 ALOGV_IF(buffer.frameCount != framesOut,
8826 "%s() read less than expected (%zu vs %zu)",
8827 __func__, buffer.frameCount, framesOut);
8828 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008829 memcpy(activeTrack->sinkBuffer().raw,
8830 buffer.raw, buffer.frameCount * mFrameSize);
8831 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008832 } else {
8833 framesOut = 0;
8834 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008835 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008836 }
8837 } else {
8838 // process frames from the RecordThread buffer provider to the RecordTrack
8839 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008840 framesOut = activeTrack->recordBufferConverter()->convert(
8841 activeTrack->sinkBuffer().raw,
8842 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008843 framesOut);
8844 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008845
8846 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8847 overrun = OVERRUN_FALSE;
8848 }
8849
Andy Hung93bb5732023-05-04 21:16:34 -07008850 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8851 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008852 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008853 if (framesToDrop == 0) {
8854 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008855 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008856 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008857 // Sanitize before releasing if the track has no access to the source data
8858 // An idle UID receives silence from non virtual devices until active
8859 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008860 memset(activeTrack->sinkBuffer().raw,
8861 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008862 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008863 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008864 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008865 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008866 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008867 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008868 }
8869 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008870
8871 switch (overrun) {
8872 case OVERRUN_TRUE:
8873 // client isn't retrieving buffers fast enough
8874 if (!activeTrack->setOverflow()) {
8875 nsecs_t now = systemTime();
8876 // FIXME should lastWarning per track?
8877 if ((now - lastWarning) > kWarningThrottleNs) {
8878 ALOGW("RecordThread: buffer overflow");
8879 lastWarning = now;
8880 }
8881 }
8882 break;
8883 case OVERRUN_FALSE:
8884 activeTrack->clearOverflow();
8885 break;
8886 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008887 break;
8888 }
8889
Andy Hung3f0c9022016-01-15 17:49:46 -08008890 // update frame information and push timestamp out
8891 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008892 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008893 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8894 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008895 }
8896
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008897unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008898 // enable changes in effect chain
8899 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008900 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008901 if (audio_has_proportional_frames(mFormat)
8902 && loopCount == lastLoopCountRead + 1) {
8903 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8904 const double jitterMs =
8905 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8906 {framesRead, readPeriodNs},
8907 {0, 0} /* lastTimestamp */, mSampleRate);
8908 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8909
Andy Hung972bec12023-08-31 16:13:39 -07008910 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008911 mIoJitterMs.add(jitterMs);
8912 mProcessTimeMs.add(processMs);
8913 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008914 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008915 // update timing info.
8916 mLastIoBeginNs = lastIoBeginNs;
8917 mLastIoEndNs = lastIoEndNs;
8918 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008919 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008920 mThreadloopExecutor.process(); // process any remaining deferred actions.
8921 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008922
Glenn Kasten93e471f2013-08-19 08:40:07 -07008923 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008924
8925 {
Andy Hung972bec12023-08-31 16:13:39 -07008926 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008927 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008928 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008929 track->invalidate();
8930 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008931 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008932 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008933 }
8934
8935 releaseWakeLock();
8936
8937 ALOGV("RecordThread %p exiting", this);
8938 return false;
8939}
8940
Andy Hungee58e4a2023-07-07 13:47:37 -07008941void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008942{
8943 if (!mStandby) {
8944 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008945 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008946 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008947 mStandby = true;
8948 }
8949}
8950
Andy Hungee58e4a2023-07-07 13:47:37 -07008951void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008952{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008953 // Idle the fast capture if it's currently running
8954 if (mFastCapture != 0) {
8955 FastCaptureStateQueue *sq = mFastCapture->sq();
8956 FastCaptureState *state = sq->begin();
8957 if (!(state->mCommand & FastCaptureState::IDLE)) {
8958 state->mCommand = FastCaptureState::COLD_IDLE;
8959 state->mColdFutexAddr = &mFastCaptureFutex;
8960 state->mColdGen++;
8961 mFastCaptureFutex = 0;
8962 sq->end();
8963 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8964 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8965#if 0
8966 if (kUseFastCapture == FastCapture_Dynamic) {
8967 // FIXME
8968 }
8969#endif
8970#ifdef AUDIO_WATCHDOG
8971 // FIXME
8972#endif
8973 } else {
8974 sq->end(false /*didModify*/);
8975 }
8976 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008977 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008978 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008979
8980 // If going into standby, flush the pipe source.
8981 if (mPipeSource.get() != nullptr) {
8982 const ssize_t flushed = mPipeSource->flush();
8983 if (flushed > 0) {
8984 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8985 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8986 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8987 }
8988 }
Eric Laurent81784c32012-11-19 14:55:58 -08008989}
8990
Andy Hungc5007f82023-08-29 14:26:09 -07008991// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008992sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008993 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008994 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008995 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008996 audio_format_t format,
8997 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008998 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008999 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009000 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009001 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00009002 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07009003 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08009004 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08009005 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009006 audio_port_handle_t portId,
9007 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009008{
Glenn Kasten74935e42013-12-19 08:56:45 -08009009 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009010 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009011 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009012 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009013 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009014 audio_input_flags_t requestedFlags = *flags;
9015 uint32_t sampleRate;
9016
9017 lStatus = initCheck();
9018 if (lStatus != NO_ERROR) {
9019 ALOGE("createRecordTrack_l() audio driver not initialized");
9020 goto Exit;
9021 }
9022
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009023 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9024 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9025 lStatus = BAD_VALUE;
9026 goto Exit;
9027 }
9028
Eric Laurentec376dc2021-04-08 20:41:22 +02009029 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009030 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009031 lStatus = PERMISSION_DENIED;
9032 goto Exit;
9033 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009034 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009035 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009036 lStatus = BAD_VALUE;
9037 goto Exit;
9038 }
9039 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009040 if (*pSampleRate == 0) {
9041 *pSampleRate = mSampleRate;
9042 }
9043 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009044
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009045 // special case for FAST flag considered OK if fast capture is present and access to
9046 // audio history is not required
9047 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009048 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9049 }
9050
Eric Laurentf14db3c2017-12-08 14:20:36 -08009051 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009052 if ((*flags & inputFlags) != *flags) {
9053 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9054 " input flags (%08x)",
9055 *flags, inputFlags);
9056 *flags = (audio_input_flags_t)(*flags & inputFlags);
9057 }
Eric Laurent81784c32012-11-19 14:55:58 -08009058
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009059 // client expresses a preference for FAST and no access to audio history,
9060 // but we get the final say
9061 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009062 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009063 // we formerly checked for a callback handler (non-0 tid),
9064 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009065 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009066 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009067 // Frame count is not specified (0), or is less than or equal the pipe depth.
9068 // It is OK to provide a higher capacity than requested.
9069 // We will force it to mPipeFramesP2 below.
9070 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009071 // PCM data
9072 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009073 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009074 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009075 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009076 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009077 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009078 hasFastCapture() &&
9079 // there are sufficient fast track slots available
9080 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009081 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009082 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009083 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009084 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009085 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009086 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009087 audio_input_flags_t old = *flags;
9088 chain->checkInputFlagCompatibility(flags);
9089 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009090 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9091 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009092 }
9093 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009094 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009095 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9096 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009097 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009098 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9099 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009100 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009101 this, frameCount, mFrameCount, mPipeFramesP2,
9102 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009103 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009104 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009105 }
9106 }
9107
Eric Laurentf14db3c2017-12-08 14:20:36 -08009108 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9109 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9110 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9111 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9112 lStatus = BAD_TYPE;
9113 goto Exit;
9114 }
9115
Glenn Kasten74105912014-07-03 12:28:53 -07009116 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009117 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009118 // fast track: frame count is exactly the pipe depth
9119 frameCount = mPipeFramesP2;
9120 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009121 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009122 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009123 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9124 // or 20 ms if there is a fast capture
9125 // TODO This could be a roundupRatio inline, and const
9126 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9127 * sampleRate + mSampleRate - 1) / mSampleRate;
9128 // minimum number of notification periods is at least kMinNotifications,
9129 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9130 static const size_t kMinNotifications = 3;
9131 static const uint32_t kMinMs = 30;
9132 // TODO This could be a roundupRatio inline
9133 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9134 // TODO This could be a roundupRatio inline
9135 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9136 maxNotificationFrames;
9137 const size_t minFrameCount = maxNotificationFrames *
9138 max(kMinNotifications, minNotificationsByMs);
9139 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009140 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9141 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009142 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009143 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009144 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009145 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009146
Andy Hungc5007f82023-08-29 14:26:09 -07009147 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009148 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009149 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009150 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009151 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009152 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009153 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009154 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009155 }
Eric Laurent81784c32012-11-19 14:55:58 -08009156
Andy Hung8d31fd22023-06-26 19:20:57 -07009157 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009158 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009159 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009160 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009161 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009162
Glenn Kasten03003332013-08-06 15:40:54 -07009163 lStatus = track->initCheck();
9164 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009165 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009166 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009167 goto Exit;
9168 }
9169 mTracks.add(track);
9170
Eric Laurent05067782016-06-01 18:27:28 -07009171 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009172 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9173 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9174 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009175 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009176 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009177
9178 if (maxSharedAudioHistoryMs != 0) {
9179 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9180 }
Eric Laurent81784c32012-11-19 14:55:58 -08009181 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009182
Eric Laurent81784c32012-11-19 14:55:58 -08009183 lStatus = NO_ERROR;
9184
9185Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009186 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009187 return track;
9188}
9189
Andy Hungee58e4a2023-07-07 13:47:37 -07009190status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009191 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009192 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009193{
9194 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9195 sp<ThreadBase> strongMe = this;
9196 status_t status = NO_ERROR;
9197
9198 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009199 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009200 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009201 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009202 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009203 event, triggerSession,
9204 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009205 }
9206
9207 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009208 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009209 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009210 if (recordTrack->isInvalid()) {
9211 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009212 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9213 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009214 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009215 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009216 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009217 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9218 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009219 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009220 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009221 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009222 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009223 }
9224 return status;
9225 }
9226
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009227 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9228 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9229 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009230 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009231 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009232 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009233 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009234 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009235 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009236 if (recordTrack->isInvalid()) {
9237 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009238 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9239 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009240 // STARTING_2 forces destroy to call stopInput.
9241 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009242 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9243 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009244 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009245 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009246 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009247 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009248 // Someone else has changed state, let them take over,
9249 // leave mState in the new state.
9250 recordTrack->clearSyncStartEvent();
9251 return INVALID_OPERATION;
9252 }
9253 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009254 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009255 ALOGW("%s(%d): startInput failed, status %d",
9256 __func__, recordTrack->id(), status);
9257 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9258 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009259 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009260 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009261 return status;
9262 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009263 sendIoConfigEvent_l(
9264 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009265 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009266
9267 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9268
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009269 // Catch up with current buffer indices if thread is already running.
9270 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9271 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9272 // see previously buffered data before it called start(), but with greater risk of overrun.
9273
Andy Hung8d31fd22023-06-26 19:20:57 -07009274 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009275 if (!recordTrack->isDirect()) {
9276 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009277 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009278 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009279 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009280 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009281 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009282 return status;
9283 }
Eric Laurent81784c32012-11-19 14:55:58 -08009284}
9285
Andy Hungee58e4a2023-07-07 13:47:37 -07009286void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009287{
Andy Hungee58e4a2023-07-07 13:47:37 -07009288 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009289
9290 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009291 sp<IAfTrackBase> ptr =
9292 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9293 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009294 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009295 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009296 }
Eric Laurent81784c32012-11-19 14:55:58 -08009297 }
9298}
9299
Andy Hungee58e4a2023-07-07 13:47:37 -07009300bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009301 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009302 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009303 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009304 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009305 return false;
9306 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009307 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009308 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009309
Andy Hungabfab202019-03-07 19:45:54 -08009310 // NOTE: Waiting here is important to keep stop synchronous.
9311 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009312 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009313 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009314 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009315 }
Andy Hungce685402018-10-05 17:23:27 -07009316
Andy Hung8d31fd22023-06-26 19:20:57 -07009317 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009318 ALOGV("Record stopped OK");
9319 return true;
9320 }
Andy Hungce685402018-10-05 17:23:27 -07009321
9322 // don't handle anything - we've been invalidated or restarted and in a different state
9323 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009324 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009325 return false;
9326}
9327
Andy Hungee58e4a2023-07-07 13:47:37 -07009328bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009329{
9330 return false;
9331}
9332
Andy Hungee58e4a2023-07-07 13:47:37 -07009333status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009334{
9335#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9336 if (!isValidSyncEvent(event)) {
9337 return BAD_VALUE;
9338 }
9339
Glenn Kastend848eb42016-03-08 13:42:11 -08009340 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009341 status_t ret = NAME_NOT_FOUND;
9342
Andy Hung972bec12023-08-31 16:13:39 -07009343 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009344
9345 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009346 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009347 if (eventSession == track->sessionId()) {
9348 (void) track->setSyncEvent(event);
9349 ret = NO_ERROR;
9350 }
9351 }
9352 return ret;
9353#else
9354 return BAD_VALUE;
9355#endif
9356}
9357
Andy Hungee58e4a2023-07-07 13:47:37 -07009358status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009359 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009360{
9361 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009362 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009363 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009364 return NO_INIT;
9365 }
jiabin9ff780e2018-03-19 18:19:52 -07009366 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9367 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009368}
9369
Andy Hungee58e4a2023-07-07 13:47:37 -07009370status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009371 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009372{
Paul McLean12340082019-03-19 09:35:05 -06009373 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009374 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009375 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009376 return NO_INIT;
9377 }
Paul McLean12340082019-03-19 09:35:05 -06009378 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009379}
9380
Andy Hungee58e4a2023-07-07 13:47:37 -07009381status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009382{
Paul McLean12340082019-03-19 09:35:05 -06009383 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009384 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009385 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009386 return NO_INIT;
9387 }
Paul McLean12340082019-03-19 09:35:05 -06009388 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009389}
9390
Andy Hungee58e4a2023-07-07 13:47:37 -07009391status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009392 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9393 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009394 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009395 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9396}
9397
Andy Hungee58e4a2023-07-07 13:47:37 -07009398status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009399 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9400 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009401
Eric Laurentec376dc2021-04-08 20:41:22 +02009402 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9403 return BAD_VALUE;
9404 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009405
9406 if (sharedAudioStartMs < 0
9407 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009408 return BAD_VALUE;
9409 }
9410
Eric Laurent2407ce32021-04-26 14:56:03 +02009411 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9412 // As we cannot detect more than one wraparound, only accept values up current write position
9413 // after one wraparound
9414 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9415 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009416 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009417 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9418 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009419 // Bring the start frame position within the input buffer to match the documented
9420 // "best effort" behavior of the API.
9421 if (sharedOffset < 0) {
9422 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009423 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009424 sharedAudioStartFrames =
9425 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009426 }
9427
Eric Laurentec376dc2021-04-08 20:41:22 +02009428 mSharedAudioPackageName = sharedAudioPackageName;
9429 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009430 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009431 } else {
9432 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009433 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009434 }
9435 return NO_ERROR;
9436}
9437
Andy Hungee58e4a2023-07-07 13:47:37 -07009438void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009439 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9440 mSharedAudioStartFrames = -1;
9441 mSharedAudioPackageName = "";
9442}
9443
Andy Hungee58e4a2023-07-07 13:47:37 -07009444ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009445{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009446 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009447 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009448 }
9449 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009450 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009451 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009452 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009453 }
9454 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009455 MetadataUpdate change;
9456 change.recordMetadataUpdate = metadata.tracks;
9457 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009458}
9459
Andy Hungc5007f82023-08-29 14:26:09 -07009460// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009461void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009462{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009463 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009464 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009465
Eric Laurent81784c32012-11-19 14:55:58 -08009466 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009467 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009468 removeTrack_l(track);
9469 }
9470}
9471
Andy Hungee58e4a2023-07-07 13:47:37 -07009472void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009473{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009474 String8 result;
9475 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009476 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009477
Eric Laurent81784c32012-11-19 14:55:58 -08009478 mTracks.remove(track);
9479 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009480 if (track->isFastTrack()) {
9481 ALOG_ASSERT(!mFastTrackAvail);
9482 mFastTrackAvail = true;
9483 }
Eric Laurent81784c32012-11-19 14:55:58 -08009484}
9485
Andy Hungee58e4a2023-07-07 13:47:37 -07009486void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009487{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009488 AudioStreamIn *input = mInput;
9489 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9490 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009491 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009492 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009493 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009494 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009495 }
Andy Hungbfa64962017-06-12 14:43:19 -07009496
9497 if (input != nullptr) {
9498 dprintf(fd, " Hal stream dump:\n");
9499 (void)input->stream->dump(fd);
9500 }
9501
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009502 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009503 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009504
Glenn Kasten2f90c512015-12-02 11:40:09 -08009505 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9506 // while we are dumping it. It may be inconsistent, but it won't mutate!
9507 // This is a large object so we place it on the heap.
9508 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009509 const std::unique_ptr<FastCaptureDumpState> copy =
9510 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009511 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009512}
9513
Andy Hungee58e4a2023-07-07 13:47:37 -07009514void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009515{
Eric Laurent81784c32012-11-19 14:55:58 -08009516 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009517 size_t numtracks = mTracks.size();
9518 size_t numactive = mActiveTracks.size();
9519 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009520 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009521 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009522 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009523 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009524 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009525 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009526 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009527 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009528 if (track != 0) {
9529 bool active = mActiveTracks.indexOf(track) >= 0;
9530 if (active) {
9531 numactiveseen++;
9532 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009533 result.append(prefix);
9534 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009535 }
Eric Laurent81784c32012-11-19 14:55:58 -08009536 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009537 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009538 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009539 }
9540
Marco Nelissenb2208842014-02-07 14:00:50 -08009541 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009542 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009543 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009544 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009545 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009546 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009547 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009548 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009549 result.append(prefix);
9550 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009551 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009552 }
Eric Laurent81784c32012-11-19 14:55:58 -08009553
9554 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009555 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009556}
9557
Andy Hungee58e4a2023-07-07 13:47:37 -07009558void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009559{
Andy Hung972bec12023-08-31 16:13:39 -07009560 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009561 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009562 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009563 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009564 track->setSilenced(silenced);
9565 }
9566 }
9567}
Andy Hung73c02e42015-03-29 01:13:58 -07009568
Andy Hung8d31fd22023-06-26 19:20:57 -07009569void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009570{
Andy Hung87c693c2023-07-06 20:56:16 -07009571 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009572 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009573 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009574 const int32_t rear = recordThread->mRsmpInRear;
9575 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009576 if (mRecordTrack->startFrames() >= 0) {
9577 int32_t startFrames = mRecordTrack->startFrames();
9578 // Accept a recent wraparound of mRsmpInRear
9579 if (startFrames <= rear) {
9580 deltaFrames = rear - startFrames;
9581 } else {
9582 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009583 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009584 // start frame cannot be further in the past than start of resampling buffer
9585 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9586 deltaFrames = recordThread->mRsmpInFrames;
9587 }
9588 }
9589 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009590}
9591
Andy Hung8d31fd22023-06-26 19:20:57 -07009592void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009593 size_t *framesAvailable, bool *hasOverrun)
9594{
Andy Hung87c693c2023-07-06 20:56:16 -07009595 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009596 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009597 const int32_t rear = recordThread->mRsmpInRear;
9598 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009599 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009600
9601 size_t framesIn;
9602 bool overrun = false;
9603 if (filled < 0) {
9604 // should not happen, but treat like a massive overrun and re-sync
9605 framesIn = 0;
9606 mRsmpInFront = rear;
9607 overrun = true;
9608 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9609 framesIn = (size_t) filled;
9610 } else {
9611 // client is not keeping up with server, but give it latest data
9612 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009613 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9614 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009615 overrun = true;
9616 }
9617 if (framesAvailable != NULL) {
9618 *framesAvailable = framesIn;
9619 }
9620 if (hasOverrun != NULL) {
9621 *hasOverrun = overrun;
9622 }
9623}
9624
Eric Laurent81784c32012-11-19 14:55:58 -08009625// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009626status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009627 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009628{
Andy Hung87c693c2023-07-06 20:56:16 -07009629 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009630 if (threadBase == 0) {
9631 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009632 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009633 return NOT_ENOUGH_DATA;
9634 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009635 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009636 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009637 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009638 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009639 // FIXME should not be P2 (don't want to increase latency)
9640 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009641 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009642 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009643
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009644 front &= recordThread->mRsmpInFramesP2 - 1;
9645 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009646 if (part1 > (size_t) filled) {
9647 part1 = filled;
9648 }
9649 size_t ask = buffer->frameCount;
9650 ALOG_ASSERT(ask > 0);
9651 if (part1 > ask) {
9652 part1 = ask;
9653 }
9654 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009655 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009656 buffer->raw = NULL;
9657 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009658 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009659 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009660 }
9661
Andy Hung57446612015-04-19 23:56:46 -07009662 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009663 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009664 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009665 return NO_ERROR;
9666}
9667
9668// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009669void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009670 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009671{
Hongwei Wang95e37682019-04-12 11:13:36 -07009672 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009673 if (stepCount == 0) {
9674 return;
9675 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009676 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009677 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009678 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009679 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009680 buffer->frameCount = 0;
9681}
9682
Andy Hungee58e4a2023-07-07 13:47:37 -07009683void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009684{
Andy Hung972bec12023-08-31 16:13:39 -07009685 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009686 checkBtNrec_l();
9687}
9688
Andy Hungee58e4a2023-07-07 13:47:37 -07009689void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009690{
9691 // disable AEC and NS if the device is a BT SCO headset supporting those
9692 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009693 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009694 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009695 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9696 for (size_t i = 0; i < mEffectChains.size(); i++) {
9697 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9698 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9699 }
9700 }
9701}
9702
Andy Hung97a893e2015-03-29 01:03:07 -07009703
Andy Hungee58e4a2023-07-07 13:47:37 -07009704bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009705 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009706{
9707 bool reconfig = false;
9708
Eric Laurent10351942014-05-08 18:49:52 -07009709 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009710
Eric Laurent10351942014-05-08 18:49:52 -07009711 audio_format_t reqFormat = mFormat;
9712 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009713 // 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 +08009714 [[maybe_unused]] audio_channel_mask_t channelMask =
9715 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009716
9717 AudioParameter param = AudioParameter(keyValuePair);
9718 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009719
9720 // scope for AutoPark extends to end of method
9721 AutoPark<FastCapture> park(mFastCapture);
9722
Eric Laurent10351942014-05-08 18:49:52 -07009723 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9724 // channel count change can be requested. Do we mandate the first client defines the
9725 // HAL sampling rate and channel count or do we allow changes on the fly?
9726 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9727 samplingRate = value;
9728 reconfig = true;
9729 }
9730 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009731 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009732 status = BAD_VALUE;
9733 } else {
9734 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009735 reconfig = true;
9736 }
Eric Laurent10351942014-05-08 18:49:52 -07009737 }
9738 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9739 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009740 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009741 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009742 status = BAD_VALUE;
9743 } else {
9744 channelMask = mask;
9745 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009746 }
Eric Laurent10351942014-05-08 18:49:52 -07009747 }
9748 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9749 // do not accept frame count changes if tracks are open as the track buffer
9750 // size depends on frame count and correct behavior would not be guaranteed
9751 // if frame count is changed after track creation
9752 if (mActiveTracks.size() > 0) {
9753 status = INVALID_OPERATION;
9754 } else {
9755 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009756 }
Eric Laurent10351942014-05-08 18:49:52 -07009757 }
9758 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009759 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009760 }
9761 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9762 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009763 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009764 }
Glenn Kastene198c362013-08-13 09:13:36 -07009765
Eric Laurent10351942014-05-08 18:49:52 -07009766 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009767 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009768 if (status == INVALID_OPERATION) {
9769 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009770 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009771 }
9772 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009773 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009774 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9775 if (mInput->stream->getAudioProperties(&config) == OK &&
9776 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9777 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009778 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009779 status = NO_ERROR;
9780 }
Eric Laurent81784c32012-11-19 14:55:58 -08009781 }
Eric Laurent10351942014-05-08 18:49:52 -07009782 if (status == NO_ERROR) {
9783 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009784 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009785 }
9786 }
Eric Laurent81784c32012-11-19 14:55:58 -08009787 }
Eric Laurent10351942014-05-08 18:49:52 -07009788
Eric Laurent81784c32012-11-19 14:55:58 -08009789 return reconfig;
9790}
9791
Andy Hungee58e4a2023-07-07 13:47:37 -07009792String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009793{
Andy Hung972bec12023-08-31 16:13:39 -07009794 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009795 if (initCheck() == NO_ERROR) {
9796 String8 out_s8;
9797 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9798 return out_s8;
9799 }
Eric Laurent81784c32012-11-19 14:55:58 -08009800 }
Andy Hung920f6572022-10-06 12:09:49 -07009801 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009802}
9803
Andy Hungab65b182023-09-06 19:41:47 -07009804void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009805 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009806 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009807 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009808 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009809 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009810 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009811 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9812 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009813 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009814 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009815 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009816 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009817 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009818 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009819 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009820 break;
9821 }
Andy Hungab65b182023-09-06 19:41:47 -07009822 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009823}
9824
Andy Hungee58e4a2023-07-07 13:47:37 -07009825void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009826{
Dean Wheatley6c009512023-10-23 09:34:14 +11009827 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9828 mSampleRate = audioConfig.sample_rate;
9829 mChannelMask = audioConfig.channel_mask;
9830 if (!audio_is_input_channel(mChannelMask)) {
9831 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9832 }
9833
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009834 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009835
9836 // Get actual HAL format.
9837 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9838 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9839 // Get format from the shim, which will be different than the HAL format
9840 // if recording compressed audio from IEC61937 wrapped sources.
9841 mFormat = audioConfig.format;
9842 if (!audio_is_valid_format(mFormat)) {
9843 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9844 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009845 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009846 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9847 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009848 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009849 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009850 ALOGI("HAL format %#x is not linear pcm", mFormat);
9851 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009852 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009853 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9854 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009855 result = mInput->stream->getBufferSize(&mBufferSize);
9856 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009857 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009858 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9859 "mBufferSize=%zu, mFrameCount=%zu",
9860 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009861
Eric Laurentec376dc2021-04-08 20:41:22 +02009862 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9863 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009864 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009865
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009866 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9867 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009868
9869 audio_input_flags_t flags = mInput->flags;
9870 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9871 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009872 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009873 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9874 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9875 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9876 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9877 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9878 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009879}
9880
Andy Hungee58e4a2023-07-07 13:47:37 -07009881uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009882{
Andy Hung972bec12023-08-31 16:13:39 -07009883 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009884 uint32_t result;
9885 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9886 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009887 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009888 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009889}
9890
Andy Hungee58e4a2023-07-07 13:47:37 -07009891KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009892{
Glenn Kastend848eb42016-03-08 13:42:11 -08009893 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009894 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009895 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009896 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009897 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009898 if (ids.indexOfKey(sessionId) < 0) {
9899 ids.add(sessionId, true);
9900 }
9901 }
9902 return ids;
9903}
9904
Andy Hungee58e4a2023-07-07 13:47:37 -07009905AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009906{
Andy Hung972bec12023-08-31 16:13:39 -07009907 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009908 AudioStreamIn *input = mInput;
9909 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009910 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009911 return input;
9912}
9913
Andy Hungc5007f82023-08-29 14:26:09 -07009914// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009915sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009916{
9917 if (mInput == NULL) {
9918 return NULL;
9919 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009920 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009921}
9922
Andy Hungee58e4a2023-07-07 13:47:37 -07009923status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009924{
Eric Laurent81784c32012-11-19 14:55:58 -08009925 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009926 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009927 chain->setInBuffer(NULL);
9928 chain->setOutBuffer(NULL);
9929
9930 checkSuspendOnAddEffectChain_l(chain);
9931
Eric Laurent1b928682014-10-02 19:41:47 -07009932 // make sure enabled pre processing effects state is communicated to the HAL as we
9933 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009934 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009935
Eric Laurent81784c32012-11-19 14:55:58 -08009936 mEffectChains.add(chain);
9937
9938 return NO_ERROR;
9939}
9940
Andy Hungee58e4a2023-07-07 13:47:37 -07009941size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009942{
9943 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009944
9945 for (size_t i = 0; i < mEffectChains.size(); i++) {
9946 if (chain == mEffectChains[i]) {
9947 mEffectChains.removeAt(i);
9948 break;
9949 }
Eric Laurent81784c32012-11-19 14:55:58 -08009950 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009951 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009952}
9953
Andy Hungee58e4a2023-07-07 13:47:37 -07009954status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009955 audio_patch_handle_t *handle)
9956{
9957 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009958
9959 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009960 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009961 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009962 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009963 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009964 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009965 }
9966
Eric Laurentd8365c52017-07-16 15:27:05 -07009967 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009968
9969 // store new source and send to effects
9970 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9971 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009972 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009973 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009974 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009975 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009976
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009977 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009978 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9979 status = hwDevice->createAudioPatch(patch->num_sources,
9980 patch->sources,
9981 patch->num_sinks,
9982 patch->sinks,
9983 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009984 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009985 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9986 patch->sinks[0].ext.mix.usecase.source,
9987 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009988 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009989 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009990
jiabinc52b1ff2019-10-31 17:20:42 -07009991 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009992 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009993 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009994 }
Eric Laurent296fb132015-05-01 11:38:42 -07009995
Andy Hungc2b11cb2020-04-22 09:04:01 -07009996 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009997 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009998 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009999 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -070010000 // also dispatch to active AudioRecords
10001 for (const auto &track : mActiveTracks) {
10002 track->logEndInterval();
10003 track->logBeginInterval(pathSourcesAsString);
10004 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010005 // Force meteadata update after a route change
10006 mActiveTracks.setHasChanged();
10007
Eric Laurent1c333e22014-05-20 10:48:17 -070010008 return status;
10009}
10010
Andy Hungee58e4a2023-07-07 13:47:37 -070010011status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010012{
10013 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010014
jiabinc52b1ff2019-10-31 17:20:42 -070010015 mPatch = audio_patch{};
10016 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010017
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010018 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010019 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10020 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010021 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010022 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010023 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010024 // Force meteadata update after a route change
10025 mActiveTracks.setHasChanged();
10026
Eric Laurent1c333e22014-05-20 10:48:17 -070010027 return status;
10028}
10029
Andy Hungee58e4a2023-07-07 13:47:37 -070010030void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010031{
Andy Hung972bec12023-08-31 16:13:39 -070010032 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010033 mOutDevices = outDevices;
10034 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10035 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010036 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010037 }
10038}
10039
Andy Hungee58e4a2023-07-07 13:47:37 -070010040int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010041{
10042 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010043 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010044 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010045 int32_t oldestFront = mRsmpInRear;
10046 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010047 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010048 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010049 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010050 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010051 if (filled > maxFilled) {
10052 oldestFront = front;
10053 maxFilled = filled;
10054 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010055 }
Andy Hung920f6572022-10-06 12:09:49 -070010056 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010057 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10058 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010059 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010060}
10061
Andy Hungee58e4a2023-07-07 13:47:37 -070010062void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010063{
10064 if (offset == 0) {
10065 return;
10066 }
10067 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010068 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010069 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010070 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010071 }
10072}
10073
Andy Hungee58e4a2023-07-07 13:47:37 -070010074void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010075{
10076 // This is the formula for calculating the temporary buffer size.
10077 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10078 // 1 full output buffer, regardless of the alignment of the available input.
10079 // The value is somewhat arbitrary, and could probably be even larger.
10080 // A larger value should allow more old data to be read after a track calls start(),
10081 // without increasing latency.
10082 //
10083 // Note this is independent of the maximum downsampling ratio permitted for capture.
10084 size_t minRsmpInFrames = mFrameCount * 7;
10085
10086 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10087 // capture history available to another client using the same session ID:
10088 // dimension the resampler input buffer accordingly.
10089
10090 // Get oldest client read position: getOldestFront_l() must be called before altering
10091 // mRsmpInRear, or mRsmpInFrames
10092 int32_t previousFront = getOldestFront_l();
10093 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10094 int32_t previousRear = mRsmpInRear;
10095 mRsmpInRear = 0;
10096
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010097 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010098 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010099 "resizeInputBuffer_l() called with invalid max shared history %d",
10100 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010101 if (maxSharedAudioHistoryMs != 0) {
10102 // resizeInputBuffer_l should never be called with a non zero shared history if the
10103 // buffer was not already allocated
10104 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10105 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10106 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10107 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010108 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010109 return;
10110 }
10111 mRsmpInFrames = rsmpInFrames;
10112 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010113 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010114 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10115 // initialized
10116 if (mRsmpInFrames < minRsmpInFrames) {
10117 mRsmpInFrames = minRsmpInFrames;
10118 }
10119 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10120
10121 // TODO optimize audio capture buffer sizes ...
10122 // Here we calculate the size of the sliding buffer used as a source
10123 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10124 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10125 // be better to have it derived from the pipe depth in the long term.
10126 // The current value is higher than necessary. However it should not add to latency.
10127
10128 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10129 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10130
10131 void *rsmpInBuffer;
10132 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10133 // if posix_memalign fails, will segv here.
10134 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10135
10136 // Copy audio history if any from old buffer before freeing it
10137 if (previousRear != 0) {
10138 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10139 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10140
10141 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10142 previousFront &= previousRsmpInFramesP2 - 1;
10143 size_t part1 = previousRsmpInFramesP2 - previousFront;
10144 if (part1 > (size_t) unread) {
10145 part1 = unread;
10146 }
10147 if (part1 != 0) {
10148 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10149 part1 * mFrameSize);
10150 mRsmpInRear = part1;
10151 part1 = unread - part1;
10152 if (part1 != 0) {
10153 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10154 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10155 mRsmpInRear += part1;
10156 }
10157 }
10158 // Update front for all clients according to new rear
10159 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10160 } else {
10161 mRsmpInRear = 0;
10162 }
10163 free(mRsmpInBuffer);
10164 mRsmpInBuffer = rsmpInBuffer;
10165}
10166
Andy Hungee58e4a2023-07-07 13:47:37 -070010167void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010168{
Andy Hung972bec12023-08-31 16:13:39 -070010169 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010170 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010171 if (record->getSource()) {
10172 mSource = record->getSource();
10173 }
Eric Laurent83b88082014-06-20 18:31:16 -070010174}
10175
Andy Hungee58e4a2023-07-07 13:47:37 -070010176void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010177{
Andy Hung972bec12023-08-31 16:13:39 -070010178 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010179 if (mSource == record->getSource()) {
10180 mSource = mInput;
10181 }
Eric Laurent83b88082014-06-20 18:31:16 -070010182 destroyTrack_l(record);
10183}
10184
Andy Hungee58e4a2023-07-07 13:47:37 -070010185void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010186{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010187 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010188 config->role = AUDIO_PORT_ROLE_SINK;
10189 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10190 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010191 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10192 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10193 config->flags.input = mInput->flags;
10194 }
Eric Laurent83b88082014-06-20 18:31:16 -070010195}
Eric Laurent1c333e22014-05-20 10:48:17 -070010196
Eric Laurent6acd1d42017-01-04 14:23:29 -080010197// ----------------------------------------------------------------------------
10198// Mmap
10199// ----------------------------------------------------------------------------
10200
Andy Hung7aa7d102023-07-07 15:58:48 -070010201// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10202// MmapPlaybackThread or MmapCaptureThread instance.
10203class MmapThreadHandle : public MmapStreamInterface {
10204public:
10205 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10206 ~MmapThreadHandle() override;
10207
10208 // MmapStreamInterface virtuals
10209 status_t createMmapBuffer(int32_t minSizeFrames,
10210 struct audio_mmap_buffer_info* info) final;
10211 status_t getMmapPosition(struct audio_mmap_position* position) final;
10212 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10213 status_t start(const AudioClient& client,
10214 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10215 status_t stop(audio_port_handle_t handle) final;
10216 status_t standby() final;
10217 status_t reportData(const void* buffer, size_t frameCount) final;
10218private:
10219 const sp<IAfMmapThread> mThread;
10220};
10221
10222/* static */
10223sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10224 const sp<IAfMmapThread>& mmapThread) {
10225 return sp<MmapThreadHandle>::make(mmapThread);
10226}
10227
10228MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229 : mThread(thread)
10230{
Phil Burk9fabbf82017-08-03 12:02:00 -070010231 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010232}
10233
Andy Hung7aa7d102023-07-07 15:58:48 -070010234// MmapStreamInterface could be directly implemented by MmapThread excepting this
10235// special handling on adapter dtor.
10236MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010237{
Phil Burk9fabbf82017-08-03 12:02:00 -070010238 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010239}
10240
Andy Hung7aa7d102023-07-07 15:58:48 -070010241status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242 struct audio_mmap_buffer_info *info)
10243{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010244 return mThread->createMmapBuffer(minSizeFrames, info);
10245}
10246
Andy Hung7aa7d102023-07-07 15:58:48 -070010247status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010248{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010249 return mThread->getMmapPosition(position);
10250}
10251
Andy Hung7aa7d102023-07-07 15:58:48 -070010252status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010253 int64_t *timeNanos) {
10254 return mThread->getExternalPosition(position, timeNanos);
10255}
10256
Andy Hung7aa7d102023-07-07 15:58:48 -070010257status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010258 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010259{
jiabind1f1cb62020-03-24 11:57:57 -070010260 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261}
10262
Andy Hung7aa7d102023-07-07 15:58:48 -070010263status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010264{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265 return mThread->stop(handle);
10266}
10267
Andy Hung7aa7d102023-07-07 15:58:48 -070010268status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010269{
Eric Laurent18b57012017-02-13 16:23:52 -080010270 return mThread->standby();
10271}
10272
Andy Hung7aa7d102023-07-07 15:58:48 -070010273status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10274{
jiabinfc791ee2023-02-15 19:43:40 +000010275 return mThread->reportData(buffer, frameCount);
10276}
10277
Eric Laurent6acd1d42017-01-04 14:23:29 -080010278
Andy Hungee58e4a2023-07-07 13:47:37 -070010279MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010280 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010281 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010282 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010283 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010284 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010285 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010286 mActiveTracks(&this->mLocalLog),
10287 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10288 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289{
Eric Laurent18b57012017-02-13 16:23:52 -080010290 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291 readHalParameters_l();
10292}
10293
Andy Hungee58e4a2023-07-07 13:47:37 -070010294void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010295{
10296 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10297}
10298
Andy Hungee58e4a2023-07-07 13:47:37 -070010299void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010300{
Andy Hung8d31fd22023-06-26 19:20:57 -070010301 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010302 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010303 {
Andy Hung972bec12023-08-31 16:13:39 -070010304 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010305 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010306 activeTracks.add(t);
10307 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010308 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010309 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010310 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010311 stop(t->portId());
10312 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010313 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010314 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010315 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010317 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010318 }
10319}
10320
10321
Andy Hung8d672e02023-09-15 18:19:28 -070010322void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010323 audio_stream_type_t streamType __unused,
10324 audio_session_t sessionId,
10325 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010326 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 audio_port_handle_t portId)
10328{
10329 mAttr = *attr;
10330 mSessionId = sessionId;
10331 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010332 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333 mPortId = portId;
10334}
10335
Andy Hungee58e4a2023-07-07 13:47:37 -070010336status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010337 struct audio_mmap_buffer_info *info)
10338{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010339 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010340 if (mHalStream == 0) {
10341 return NO_INIT;
10342 }
Eric Laurent18b57012017-02-13 16:23:52 -080010343 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010344 return mHalStream->createMmapBuffer(minSizeFrames, info);
10345}
10346
Andy Hungee58e4a2023-07-07 13:47:37 -070010347status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010348{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010349 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 if (mHalStream == 0) {
10351 return NO_INIT;
10352 }
10353 return mHalStream->getMmapPosition(position);
10354}
10355
Andy Hungee58e4a2023-07-07 13:47:37 -070010356status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010357{
Eric Laurentdda206a2022-07-08 17:28:35 +020010358 // The HAL must receive track metadata before starting the stream
10359 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010360 status_t ret = mHalStream->start();
10361 if (ret != NO_ERROR) {
10362 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10363 return ret;
10364 }
Andy Hungcf10d742020-04-28 15:38:24 -070010365 if (mStandby) {
10366 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010367 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010368 mStandby = false;
10369 }
Eric Laurent331679c2018-04-16 17:03:16 -070010370 return NO_ERROR;
10371}
10372
Andy Hungee58e4a2023-07-07 13:47:37 -070010373status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010374 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375 audio_port_handle_t *handle)
10376{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010377 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010378 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010379 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 if (mHalStream == 0) {
10381 return NO_INIT;
10382 }
10383
10384 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385
Eric Laurentdda206a2022-07-08 17:28:35 +020010386 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010387 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010388 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010389 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010390 }
10391
10392 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10393
10394 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010395 AttributionSourceState adjAttributionSource;
10396 if (!com::android::media::audio::audioserver_permissions()) {
10397 adjAttributionSource = afutils::checkAttributionSourcePackage(
10398 client.attributionSource);
10399 } else {
10400 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10401 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10402 client.attributionSource,
10403 mAfThreadCallback->getPermissionProvider()
10404 );
10405 if (!validatedRes.has_value()) {
10406 ALOGE("MMAP client package validation fail: %s",
10407 validatedRes.error().toString8().c_str());
10408 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10409 }
10410 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10411 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010412
Andy Hung3f49ebb2023-09-19 14:48:41 -070010413 const auto localSessionId = mSessionId;
10414 auto localAttr = mAttr;
Andy Hung6b137d12024-08-27 22:35:17 +000010415 float volume = 0.0f;
Eric Laurenta54f1282017-07-01 19:39:32 -070010416 if (isOutput()) {
10417 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10418 config.sample_rate = mSampleRate;
10419 config.channel_mask = mChannelMask;
10420 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010421 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010422 audio_output_flags_t flags =
10423 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010424 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010425 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010426 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010427 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010428 mutex().unlock();
10429 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10430 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010431 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010432 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010433 &config,
10434 flags,
10435 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010436 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010437 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010438 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +000010439 &isBitPerfect,
10440 &volume);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010441 mutex().lock();
10442 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010443 ALOGD_IF(!secondaryOutputs.empty(),
10444 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010445 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010446 audio_config_base_t config;
10447 config.sample_rate = mSampleRate;
10448 config.channel_mask = mChannelMask;
10449 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010450 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010451 mutex().unlock();
10452 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010453 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010454 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010455 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010456 &config,
10457 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10458 &deviceId,
10459 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010460 mutex().lock();
10461 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010462 }
10463 // APM should not chose a different input or output stream for the same set of attributes
10464 // and audo configuration
10465 if (ret != NO_ERROR || io != mId) {
10466 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10467 __FUNCTION__, ret, io, mId);
10468 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010469 }
10470
10471 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010472 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010473 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010474 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010475 } else {
jiabin09609032022-06-15 19:26:01 +000010476 {
10477 // Add the track record before starting input so that the silent status for the
10478 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010479 setClientSilencedState_l(portId, false /*silenced*/);
10480 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010481 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010482 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010483 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010484 }
10485
10486 // abort if start is rejected by audio policy manager
10487 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010488 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010489 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010490 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010492 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010494 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 }
Andy Hungc5007f82023-08-29 14:26:09 -070010496 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010497 } else {
10498 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010499 }
jiabin09609032022-06-15 19:26:01 +000010500 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501 return PERMISSION_DENIED;
10502 }
10503
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010504 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010505 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10506 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010507 mChannelMask, mSessionId, isOutput(),
10508 client.attributionSource,
Andy Hung6b137d12024-08-27 22:35:17 +000010509 IPCThreadState::self()->getCallingPid(), portId,
10510 volume);
jiabin09609032022-06-15 19:26:01 +000010511 if (!isOutput()) {
10512 track->setSilenced_l(isClientSilenced_l(portId));
10513 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010514
Eric Laurent4eb58f12018-12-07 16:41:02 -080010515 if (isOutput()) {
10516 // force volume update when a new track is added
10517 mHalVolFloat = -1.0f;
10518 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010519 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010520 if (t->isSilenced_l()
10521 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010522 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010523 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010524 }
10525 }
10526
Eric Laurent6acd1d42017-01-04 14:23:29 -080010527 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010528 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010529 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010530 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531 chain->incTrackCnt();
10532 chain->incActiveTrackCnt();
10533 }
10534
Andy Hungc2b11cb2020-04-22 09:04:01 -070010535 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010537
10538 if (mActiveTracks.size() == 1) {
10539 ret = exitStandby_l();
10540 }
10541
Eric Laurent6acd1d42017-01-04 14:23:29 -080010542 broadcast_l();
10543
Eric Laurentdda206a2022-07-08 17:28:35 +020010544 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545
Eric Laurentdda206a2022-07-08 17:28:35 +020010546 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547}
10548
Andy Hungee58e4a2023-07-07 13:47:37 -070010549status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010550{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010552 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553
10554 if (mHalStream == 0) {
10555 return NO_INIT;
10556 }
10557
Eric Laurenta54f1282017-07-01 19:39:32 -070010558 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010559 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010560 return NO_ERROR;
10561 }
10562
Andy Hung8d31fd22023-06-26 19:20:57 -070010563 sp<IAfMmapTrack> track;
10564 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010565 if (handle == t->portId()) {
10566 track = t;
10567 break;
10568 }
10569 }
10570 if (track == 0) {
10571 return BAD_VALUE;
10572 }
10573
10574 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010575 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010576
Andy Hungc5007f82023-08-29 14:26:09 -070010577 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010579 AudioSystem::stopOutput(track->portId());
10580 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010582 AudioSystem::stopInput(track->portId());
10583 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010584 }
Andy Hungc5007f82023-08-29 14:26:09 -070010585 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010586
Andy Hung116bc262023-06-20 18:56:17 -070010587 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588 if (chain != 0) {
10589 chain->decActiveTrackCnt();
10590 chain->decTrackCnt();
10591 }
10592
Eric Laurentdda206a2022-07-08 17:28:35 +020010593 if (mActiveTracks.isEmpty()) {
10594 mHalStream->stop();
10595 }
10596
Eric Laurent6acd1d42017-01-04 14:23:29 -080010597 broadcast_l();
10598
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599 return NO_ERROR;
10600}
10601
Andy Hungee58e4a2023-07-07 13:47:37 -070010602status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010603NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010604{
10605 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010606 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010607
10608 if (mHalStream == 0) {
10609 return NO_INIT;
10610 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010611 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010612 return INVALID_OPERATION;
10613 }
10614 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010615 if (!mStandby) {
10616 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010617 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010618 mStandby = true;
10619 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010620 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010621 return NO_ERROR;
10622}
10623
Andy Hungee58e4a2023-07-07 13:47:37 -070010624status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010625 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10626 return INVALID_OPERATION;
10627}
10628
Andy Hungee58e4a2023-07-07 13:47:37 -070010629void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010630{
10631 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10632 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10633 mFormat = mHALFormat;
10634 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10635 result = mHalStream->getFrameSize(&mFrameSize);
10636 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010637 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10638 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639 result = mHalStream->getBufferSize(&mBufferSize);
10640 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10641 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010642
Andy Hungcf10d742020-04-28 15:38:24 -070010643 // TODO: make a readHalParameters call?
10644 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010645 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010646 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010647 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10648 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10649 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10650 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10651 /*
10652 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10653 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10654 (int32_t)mHapticChannelMask)
10655 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10656 (int32_t)mHapticChannelCount)
10657 */
10658 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010659 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010660 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10661 (int32_t)mFrameCount) // sic - added HAL
10662 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010663}
10664
Andy Hungee58e4a2023-07-07 13:47:37 -070010665bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010666{
Andy Hungab65b182023-09-06 19:41:47 -070010667 {
10668 audio_utils::unique_lock _l(mutex());
10669 checkSilentMode_l();
10670 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010671
10672 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10673
10674 while (!exitPending())
10675 {
Andy Hung116bc262023-06-20 18:56:17 -070010676 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010677
Andy Hung13850be2019-03-14 11:33:09 -070010678 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010679 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010680
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681 if (mSignalPending) {
10682 // A signal was raised while we were unlocked
10683 mSignalPending = false;
10684 } else {
10685 if (mConfigEvents.isEmpty()) {
10686 // we're about to wait, flush the binder command buffer
10687 IPCThreadState::self()->flushCommands();
10688
10689 if (exitPending()) {
10690 break;
10691 }
10692
Eric Laurent6acd1d42017-01-04 14:23:29 -080010693 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010694 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010695 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010696 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697
10698 checkSilentMode_l();
10699
10700 continue;
10701 }
10702 }
10703
10704 processConfigEvents_l();
10705
10706 processVolume_l();
10707
10708 checkInvalidTracks_l();
10709
Andy Hungab65b182023-09-06 19:41:47 -070010710 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010711
Kevin Rocard069c2712018-03-29 19:09:14 -070010712 updateMetadata_l();
10713
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010715 } // release Thread lock
10716
Eric Laurent6acd1d42017-01-04 14:23:29 -080010717 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010718 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719 }
Andy Hung13850be2019-03-14 11:33:09 -070010720
10721 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010722 unlockEffectChains(effectChains);
10723 // Effect chains will be actually deleted here if they were removed from
10724 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010725 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010726 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010727 mThreadloopExecutor.process(); // process any remaining deferred actions.
10728 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010729
10730 threadLoop_exit();
10731
10732 if (!mStandby) {
10733 threadLoop_standby();
10734 mStandby = true;
10735 }
10736
Eric Laurent6acd1d42017-01-04 14:23:29 -080010737 ALOGV("Thread %p type %d exiting", this, mType);
10738 return false;
10739}
10740
Andy Hungc5007f82023-08-29 14:26:09 -070010741// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010742bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010743 status_t& status)
10744{
10745 AudioParameter param = AudioParameter(keyValuePair);
10746 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010747 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010748 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010749 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010751 if (sendToHal) {
10752 status = mHalStream->setParameters(keyValuePair);
10753 } else {
10754 status = NO_ERROR;
10755 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010756
10757 return false;
10758}
10759
Andy Hungee58e4a2023-07-07 13:47:37 -070010760String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010761{
Andy Hung972bec12023-08-31 16:13:39 -070010762 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763 String8 out_s8;
10764 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10765 return out_s8;
10766 }
Andy Hung920f6572022-10-06 12:09:49 -070010767 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010768}
10769
Andy Hungab65b182023-09-06 19:41:47 -070010770void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010771 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010772 sp<AudioIoDescriptor> desc;
10773 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010774 switch (event) {
10775 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010776 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010777 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010778 isInput = true;
10779 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010781 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010782 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010783 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10784 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010785 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010786 case AUDIO_INPUT_CLOSED:
10787 case AUDIO_OUTPUT_CLOSED:
10788 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010789 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 break;
10791 }
Andy Hungab65b182023-09-06 19:41:47 -070010792 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793}
10794
Andy Hungee58e4a2023-07-07 13:47:37 -070010795status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010796 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010797NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798{
10799 status_t status = NO_ERROR;
10800
10801 // store new device and send to effects
10802 audio_devices_t type = AUDIO_DEVICE_NONE;
10803 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010804 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10805 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10806 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010807 if (isOutput()) {
10808 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010809 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10810 && !mAudioHwDev->supportsAudioPatches(),
10811 "Enumerated device type(%#x) must not be used "
10812 "as it does not support audio patches",
10813 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010814 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010815 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10816 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010817 }
10818 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010819 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820 } else {
10821 type = patch->sources[0].ext.device.type;
10822 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010823 numDevices = mPatch.num_sources;
10824 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010825 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010826 }
10827
10828 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010829 if (isOutput()) {
10830 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10831 } else {
10832 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10833 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010834 }
10835
jiabinc52b1ff2019-10-31 17:20:42 -070010836 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837 // store new source and send to effects
10838 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10839 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10840 for (size_t i = 0; i < mEffectChains.size(); i++) {
10841 mEffectChains[i]->setAudioSource_l(mAudioSource);
10842 }
10843 }
10844 }
10845
jiabin78b86f22024-02-22 00:39:29 +000010846 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10847 // okay to notify the client earlier before the new patch creation.
10848 if (mDeviceId != deviceId) {
10849 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10850 // The aaudioservice handle the routing changed event asynchronously. In that case,
10851 // it is safe to hold the lock here.
10852 callback->onRoutingChanged(deviceId);
10853 }
10854 }
10855
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010857 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10858 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010859 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010860 audio_port_config port;
10861 std::optional<audio_source_t> source;
10862 if (isOutput()) {
10863 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010864 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010865 port = patch->sources[0];
10866 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010867 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010868 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010869 *handle = AUDIO_PATCH_HANDLE_NONE;
10870 }
10871
jiabinc52b1ff2019-10-31 17:20:42 -070010872 if (numDevices == 0 || mDeviceId != deviceId) {
10873 if (isOutput()) {
10874 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10875 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010876 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010877 } else {
10878 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10879 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10880 }
jiabinc52b1ff2019-10-31 17:20:42 -070010881 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010882 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010883 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010884 // Force meteadata update after a route change
10885 mActiveTracks.setHasChanged();
10886
Eric Laurent6acd1d42017-01-04 14:23:29 -080010887 return status;
10888}
10889
Andy Hungee58e4a2023-07-07 13:47:37 -070010890status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010891{
10892 status_t status = NO_ERROR;
10893
jiabinc52b1ff2019-10-31 17:20:42 -070010894 mPatch = audio_patch{};
10895 mOutDeviceTypeAddrs.clear();
10896 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010897
10898 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10899 supportsAudioPatches : false;
10900
10901 if (supportsAudioPatches) {
10902 status = mHalDevice->releaseAudioPatch(handle);
10903 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010904 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010905 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010906 // Force meteadata update after a route change
10907 mActiveTracks.setHasChanged();
10908
Eric Laurent6acd1d42017-01-04 14:23:29 -080010909 return status;
10910}
10911
Andy Hungee58e4a2023-07-07 13:47:37 -070010912void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010913NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010914{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010915 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010916 if (isOutput()) {
10917 config->role = AUDIO_PORT_ROLE_SOURCE;
10918 config->ext.mix.hw_module = mAudioHwDev->handle();
10919 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10920 } else {
10921 config->role = AUDIO_PORT_ROLE_SINK;
10922 config->ext.mix.hw_module = mAudioHwDev->handle();
10923 config->ext.mix.usecase.source = mAudioSource;
10924 }
10925}
10926
Andy Hungee58e4a2023-07-07 13:47:37 -070010927status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010928{
10929 audio_session_t session = chain->sessionId();
10930
10931 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10932 // Attach all tracks with same session ID to this chain.
10933 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010934 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935 if (session == track->sessionId()) {
10936 chain->incTrackCnt();
10937 chain->incActiveTrackCnt();
10938 }
10939 }
10940
10941 chain->setThread(this);
10942 chain->setInBuffer(nullptr);
10943 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010944 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010945
10946 mEffectChains.add(chain);
10947 checkSuspendOnAddEffectChain_l(chain);
10948 return NO_ERROR;
10949}
10950
Andy Hungee58e4a2023-07-07 13:47:37 -070010951size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010952{
10953 audio_session_t session = chain->sessionId();
10954
10955 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10956
10957 for (size_t i = 0; i < mEffectChains.size(); i++) {
10958 if (chain == mEffectChains[i]) {
10959 mEffectChains.removeAt(i);
10960 // detach all active tracks from the chain
10961 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010962 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010963 if (session == track->sessionId()) {
10964 chain->decActiveTrackCnt();
10965 chain->decTrackCnt();
10966 }
10967 }
10968 break;
10969 }
10970 }
10971 return mEffectChains.size();
10972}
10973
Andy Hungee58e4a2023-07-07 13:47:37 -070010974void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010975{
10976 mHalStream->standby();
10977}
10978
Andy Hungee58e4a2023-07-07 13:47:37 -070010979void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010980{
Phil Burk7dce7282017-09-27 13:51:41 -070010981 // Do not call callback->onTearDown() because it is redundant for thread exit
10982 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010983}
10984
Andy Hungee58e4a2023-07-07 13:47:37 -070010985status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010986{
10987 return BAD_VALUE;
10988}
10989
Andy Hungee58e4a2023-07-07 13:47:37 -070010990bool MmapThread::isValidSyncEvent(
10991 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010992{
10993 return false;
10994}
10995
Andy Hungee58e4a2023-07-07 13:47:37 -070010996status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010997 const effect_descriptor_t *desc, audio_session_t sessionId)
10998{
10999 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080011000 if (audio_is_global_session(sessionId)) {
11001 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080011002 desc->name, mThreadName);
11003 return BAD_VALUE;
11004 }
11005
11006 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11007 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11008 desc->name);
11009 return BAD_VALUE;
11010 }
11011 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011012 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11013 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011014 return BAD_VALUE;
11015 }
11016
11017 // Only allow effects without processing load or latency
11018 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11019 return BAD_VALUE;
11020 }
11021
Andy Hung116bc262023-06-20 18:56:17 -070011022 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011023 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11024 return BAD_VALUE;
11025 }
11026
Eric Laurent6acd1d42017-01-04 14:23:29 -080011027 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011028}
11029
Andy Hungee58e4a2023-07-07 13:47:37 -070011030void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011031{
Andy Hung8d31fd22023-06-26 19:20:57 -070011032 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011034 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11035 // The aaudioservice handle the routing changed event asynchronously. In that case,
11036 // it is safe to hold the lock here.
11037 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
11038 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011039 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11040 mNoCallbackWarningCount++;
11041 }
11042 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 }
11044 }
11045}
11046
Andy Hungee58e4a2023-07-07 13:47:37 -070011047void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011048{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011049 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11050 mAttr.content_type, mAttr.usage, mAttr.source);
11051 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011052 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011053 dprintf(fd, " No active clients\n");
11054 }
11055}
11056
Andy Hungee58e4a2023-07-07 13:47:37 -070011057void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011058{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011060 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011061 dprintf(fd, " %zu Tracks\n", numtracks);
11062 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011063 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011064 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011065 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011066 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011067 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011068 result.append(prefix);
11069 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011070 }
11071 } else {
11072 dprintf(fd, "\n");
11073 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011074 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011075}
11076
Andy Hungee58e4a2023-07-07 13:47:37 -070011077/* static */
11078sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011079 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011080 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011081 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011082}
11083
11084MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011085 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011086 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011087 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011088 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011089 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011090{
11091 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11092 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011093 mMasterVolume = afThreadCallback->masterVolume_l();
11094 mMasterMute = afThreadCallback->masterMute_l();
Andy Hung6b137d12024-08-27 22:35:17 +000011095 if (!audioserver_flags::portid_volume_management()) {
11096 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11097 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11098 mStreamTypes[stream].volume = 0.0f;
11099 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11100 }
11101 // Audio patch and call assistant volume are always max
11102 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11103 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11104 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11105 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011106 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011107 if (mAudioHwDev) {
11108 if (mAudioHwDev->canSetMasterVolume()) {
11109 mMasterVolume = 1.0;
11110 }
11111
11112 if (mAudioHwDev->canSetMasterMute()) {
11113 mMasterMute = false;
11114 }
11115 }
11116}
11117
Andy Hungee58e4a2023-07-07 13:47:37 -070011118void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011119 audio_stream_type_t streamType,
11120 audio_session_t sessionId,
11121 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011122 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011123 audio_port_handle_t portId)
11124{
Andy Hung8d672e02023-09-15 18:19:28 -070011125 audio_utils::lock_guard l(mutex());
11126 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011127 mStreamType = streamType;
11128}
11129
Andy Hungee58e4a2023-07-07 13:47:37 -070011130AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011131{
Andy Hung972bec12023-08-31 16:13:39 -070011132 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011133 AudioStreamOut *output = mOutput;
11134 mOutput = NULL;
11135 return output;
11136}
11137
Andy Hungee58e4a2023-07-07 13:47:37 -070011138void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011139{
Andy Hung972bec12023-08-31 16:13:39 -070011140 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011141 // Don't apply master volume in SW if our HAL can do it for us.
11142 if (mAudioHwDev &&
11143 mAudioHwDev->canSetMasterVolume()) {
11144 mMasterVolume = 1.0;
11145 } else {
11146 mMasterVolume = value;
11147 }
11148}
11149
Andy Hungee58e4a2023-07-07 13:47:37 -070011150void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011151{
Andy Hung972bec12023-08-31 16:13:39 -070011152 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011153 // Don't apply master mute in SW if our HAL can do it for us.
11154 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11155 mMasterMute = false;
11156 } else {
11157 mMasterMute = muted;
11158 }
11159}
11160
Andy Hungee58e4a2023-07-07 13:47:37 -070011161void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011162{
Andy Hung972bec12023-08-31 16:13:39 -070011163 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011164 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011165 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011166 broadcast_l();
11167 }
11168}
11169
Andy Hungee58e4a2023-07-07 13:47:37 -070011170float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011171{
Andy Hung972bec12023-08-31 16:13:39 -070011172 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011173 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011174}
11175
Andy Hungee58e4a2023-07-07 13:47:37 -070011176void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011177{
Andy Hung972bec12023-08-31 16:13:39 -070011178 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011179 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011180 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011181 broadcast_l();
11182 }
11183}
11184
Andy Hung6b137d12024-08-27 22:35:17 +000011185status_t MmapPlaybackThread::setPortsVolume(
11186 const std::vector<audio_port_handle_t>& portIds, float volume) {
11187 audio_utils::lock_guard _l(mutex());
11188 for (const auto& portId : portIds) {
11189 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11190 if (portId == track->portId()) {
11191 track->setPortVolume(volume);
11192 break;
11193 }
11194 }
11195 }
11196 broadcast_l();
11197 return NO_ERROR;
11198}
11199
Andy Hungee58e4a2023-07-07 13:47:37 -070011200void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011201{
Andy Hung972bec12023-08-31 16:13:39 -070011202 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011203 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011204 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011205 track->invalidate();
11206 }
11207 broadcast_l();
11208 }
11209}
11210
Andy Hungee58e4a2023-07-07 13:47:37 -070011211void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011212{
Andy Hung972bec12023-08-31 16:13:39 -070011213 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011214 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011215 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011216 if (portIds.find(track->portId()) != portIds.end()) {
11217 track->invalidate();
11218 trackMatch = true;
11219 portIds.erase(track->portId());
11220 }
11221 if (portIds.empty()) {
11222 break;
11223 }
11224 }
11225 if (trackMatch) {
11226 broadcast_l();
11227 }
11228}
11229
Andy Hungee58e4a2023-07-07 13:47:37 -070011230void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011231NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011232{
Andy Hung6b137d12024-08-27 22:35:17 +000011233 float volume = 0;
11234 if (!audioserver_flags::portid_volume_management()) {
11235 if (mMasterMute || streamMuted_l()) {
11236 volume = 0;
11237 } else {
11238 volume = mMasterVolume * streamVolume_l();
11239 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011240 } else {
Andy Hung6b137d12024-08-27 22:35:17 +000011241 if (mMasterMute) {
11242 volume = 0;
11243 } else {
11244 // All mmap tracks are declared with the same audio attributes to the audio policy
11245 // manager. Hence, they follow the same routing / volume group. Any change of volume
11246 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11247 size_t numtracks = mActiveTracks.size();
11248 if (numtracks) {
11249 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11250 }
11251 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011252 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011253 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011254 // Convert volumes from float to 8.24
11255 uint32_t vol = (uint32_t)(volume * (1 << 24));
11256
11257 // Delegate volume control to effect in track effect chain if needed
11258 // only one effect chain can be present on DirectOutputThread, so if
11259 // there is one, the track is connected to it
11260 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011261 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011262 volume = (float)vol / (1 << 24);
11263 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011264 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011265 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11266 mHalVolFloat = volume; // HW volume control worked, so update value.
11267 mNoCallbackWarningCount = 0;
11268 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011269 sp<MmapStreamCallback> callback = mCallback.promote();
11270 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011271 mHalVolFloat = volume; // SW volume control worked, so update value.
11272 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011273 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011274 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011275 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011276 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011277 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11278 ALOGW("Could not set MMAP stream volume: no volume callback!");
11279 mNoCallbackWarningCount++;
11280 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011281 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011282 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011283 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011284 track->setMetadataHasChanged();
Andy Hung6b137d12024-08-27 22:35:17 +000011285 if (!audioserver_flags::portid_volume_management()) {
11286 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11287 /*muteState=*/{mMasterMute,
11288 streamVolume_l() == 0.f,
11289 streamMuted_l(),
11290 // TODO(b/241533526): adjust logic to include mute from AppOps
11291 false /*muteFromPlaybackRestricted*/,
11292 false /*muteFromClientVolume*/,
11293 false /*muteFromVolumeShaper*/});
11294 } else {
11295 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11296 /*muteState=*/{mMasterMute,
11297 track->getPortVolume() == 0.f,
11298 /* muteFromStreamMuted= */ false,
11299 // TODO(b/241533526): adjust logic to include mute from AppOps
11300 false /*muteFromPlaybackRestricted*/,
11301 false /*muteFromClientVolume*/,
11302 false /*muteFromVolumeShaper*/});
11303 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011304 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011305 }
11306}
11307
Andy Hungee58e4a2023-07-07 13:47:37 -070011308ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011309{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011310 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011311 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011312 }
11313 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011314 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011315 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011316 playback_track_metadata_v7_t trackMetadata;
11317 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011318 .usage = track->attributes().usage,
11319 .content_type = track->attributes().content_type,
11320 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011321 };
11322 trackMetadata.channel_mask = track->channelMask(),
11323 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11324 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011325 }
11326 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011327
11328 MetadataUpdate change;
11329 change.playbackMetadataUpdate = metadata.tracks;
11330 return change;
11331};
Kevin Rocard069c2712018-03-29 19:09:14 -070011332
Andy Hungee58e4a2023-07-07 13:47:37 -070011333void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011334{
11335 if (!mMasterMute) {
11336 char value[PROPERTY_VALUE_MAX];
11337 if (property_get("ro.audio.silent", value, "0") > 0) {
11338 char *endptr;
11339 unsigned long ul = strtoul(value, &endptr, 0);
11340 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011341 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011342 // The setprop command will not allow a property to be changed after
11343 // the first time it is set, so we don't have to worry about un-muting.
11344 setMasterMute_l(true);
11345 }
11346 }
11347 }
11348}
11349
Andy Hungee58e4a2023-07-07 13:47:37 -070011350void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011351{
11352 MmapThread::toAudioPortConfig(config);
11353 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11354 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11355 config->flags.output = mOutput->flags;
11356 }
11357}
11358
Andy Hungee58e4a2023-07-07 13:47:37 -070011359status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011360 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011361{
11362 if (mOutput == nullptr) {
11363 return NO_INIT;
11364 }
11365 struct timespec timestamp;
11366 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11367 if (status == NO_ERROR) {
11368 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11369 }
11370 return status;
11371}
11372
Andy Hungee58e4a2023-07-07 13:47:37 -070011373status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011374 // Send to MelProcessor for sound dose measurement.
11375 auto processor = mMelProcessor.load();
11376 if (processor) {
11377 processor->process(buffer, frameCount * mFrameSize);
11378 }
11379
jiabinfc791ee2023-02-15 19:43:40 +000011380 return NO_ERROR;
11381}
11382
Andy Hungc5007f82023-08-29 14:26:09 -070011383// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011384void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011385 const sp<audio_utils::MelProcessor>& processor)
11386{
11387 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011388 mMelProcessor.store(processor);
11389 if (processor) {
11390 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011391 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011392
11393 // no need to update output format for MMapPlaybackThread since it is
11394 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011395}
11396
Andy Hungc5007f82023-08-29 14:26:09 -070011397// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011398void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011399{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011400 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11401 auto melProcessor = mMelProcessor.load();
11402 if (melProcessor != nullptr) {
11403 melProcessor->pause();
11404 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011405}
11406
Andy Hungee58e4a2023-07-07 13:47:37 -070011407void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011408{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011409 MmapThread::dumpInternals_l(fd, args);
Andy Hung6b137d12024-08-27 22:35:17 +000011410 if (!audioserver_flags::portid_volume_management()) {
11411 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11412 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11413 } else {
11414 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11415 }
11416 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011417 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11418}
11419
Andy Hungee58e4a2023-07-07 13:47:37 -070011420/* static */
11421sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011422 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011423 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011424 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011425}
11426
11427MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011428 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011429 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011430 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011431 mInput(input)
11432{
11433 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11434 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11435}
11436
Andy Hungee58e4a2023-07-07 13:47:37 -070011437status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011438{
Phil Burkf054fc32018-12-06 09:45:59 -080011439 {
11440 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011441 if (mInput != nullptr && mInput->stream != nullptr) {
11442 mInput->stream->setGain(1.0f);
11443 }
11444 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011445 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011446}
11447
Andy Hungee58e4a2023-07-07 13:47:37 -070011448AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011449{
Andy Hung972bec12023-08-31 16:13:39 -070011450 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011451 AudioStreamIn *input = mInput;
11452 mInput = NULL;
11453 return input;
11454}
Kevin Rocard069c2712018-03-29 19:09:14 -070011455
Andy Hungee58e4a2023-07-07 13:47:37 -070011456void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011457{
11458 bool changed = false;
11459 bool silenced = false;
11460
11461 sp<MmapStreamCallback> callback = mCallback.promote();
11462 if (callback == 0) {
11463 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11464 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11465 mNoCallbackWarningCount++;
11466 }
11467 }
11468
11469 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11470 // track is silenced and unmute otherwise
11471 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11472 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11473 changed = true;
11474 silenced = mActiveTracks[i]->isSilenced_l();
11475 }
11476 }
11477
11478 if (changed) {
11479 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11480 }
11481}
11482
Andy Hungee58e4a2023-07-07 13:47:37 -070011483ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011484{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011485 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011486 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011487 }
11488 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011489 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011490 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011491 record_track_metadata_v7_t trackMetadata;
11492 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011493 .source = track->attributes().source,
11494 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011495 };
11496 trackMetadata.channel_mask = track->channelMask(),
11497 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11498 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011499 }
11500 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011501 MetadataUpdate change;
11502 change.recordMetadataUpdate = metadata.tracks;
11503 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011504}
11505
Andy Hungee58e4a2023-07-07 13:47:37 -070011506void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011507{
Andy Hung972bec12023-08-31 16:13:39 -070011508 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011509 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011510 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011511 mActiveTracks[i]->setSilenced_l(silenced);
11512 broadcast_l();
11513 }
11514 }
jiabin09609032022-06-15 19:26:01 +000011515 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011516}
11517
Andy Hungee58e4a2023-07-07 13:47:37 -070011518void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011519{
11520 MmapThread::toAudioPortConfig(config);
11521 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11522 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11523 config->flags.input = mInput->flags;
11524 }
11525}
11526
Andy Hungee58e4a2023-07-07 13:47:37 -070011527status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011528 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011529{
11530 if (mInput == nullptr) {
11531 return NO_INIT;
11532 }
11533 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11534}
11535
jiabinc658e452022-10-21 20:52:21 +000011536// ----------------------------------------------------------------------------
11537
Andy Hungee58e4a2023-07-07 13:47:37 -070011538/* static */
11539sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011540 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011541 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011542 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011543}
11544
Andy Hung583043b2023-07-17 17:05:00 -070011545BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011546 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011547 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011548
Andy Hungee58e4a2023-07-07 13:47:37 -070011549PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011550 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011551 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11552 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011553 float volumeLeft = 1.0f;
11554 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011555 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11556 bitPerfectTrack != nullptr) {
11557 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011558 mAudioMixer->setParameter(
11559 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11560 mAudioMixer->setParameter(
11561 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11562 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011563 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011564 mIsBitPerfect = true;
11565 } else {
11566 mIsBitPerfect = false;
11567 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11568 // active.
11569 for (const auto& track : mActiveTracks) {
11570 const int trackId = track->id();
11571 mAudioMixer->setParameter(
11572 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11573 }
11574 }
jiabin76d94692022-12-15 21:51:21 +000011575 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11576 mVolumeLeft = volumeLeft;
11577 mVolumeRight = volumeRight;
11578 setVolumeForOutput_l(volumeLeft, volumeRight);
11579 }
jiabinc658e452022-10-21 20:52:21 +000011580 return result;
11581}
11582
Andy Hungee58e4a2023-07-07 13:47:37 -070011583void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011584 MixerThread::threadLoop_mix();
11585 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11586}
11587
jiabin220eea12024-05-17 17:55:20 +000011588void BitPerfectThread::setTracksInternalMute(
11589 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11590 for (auto& track : mTracks) {
11591 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11592 track->setInternalMute(it->second);
11593 tracksInternalMute->erase(it);
11594 }
11595 }
11596}
11597
11598sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11599 if (com::android::media::audioserver::
11600 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11601 sp<IAfTrack> bitPerfectTrack = nullptr;
11602 bool allOtherTracksMuted = true;
11603 // Return the bit perfect track if all other tracks are muted
11604 for (const auto& track : mActiveTracks) {
11605 if (track->isBitPerfect()) {
11606 bitPerfectTrack = track;
11607 } else if (track->getFinalVolume() != 0.f) {
11608 allOtherTracksMuted = false;
11609 if (bitPerfectTrack != nullptr) {
11610 break;
11611 }
11612 }
11613 }
11614 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11615 } else {
11616 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11617 return mActiveTracks[0];
11618 }
11619 }
11620 return nullptr;
11621}
11622
Glenn Kasten63238ef2015-03-02 15:50:29 -080011623} // namespace android