blob: 406b83216d0033ecd3de99aad573de3c75ce7ccd [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");
jiabin10b2fb82024-09-03 17:51:35 +00001199 case BIT_PERFECT:
1200 return String16("AudioBitPerfect");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001201 default:
1202 ALOG_ASSERT(false);
1203 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001204 }
1205}
1206
Andy Hungee58e4a2023-07-07 13:47:37 -07001207void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001208{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001209 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001210 if (mPowerManager != 0) {
1211 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001212 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001213 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1214 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001215 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001216 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001217 {} /* workSource */,
1218 {} /* historyTag */);
1219 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001220 mWakeLockToken = binder;
1221 }
Chris Ye6597d732020-02-28 22:38:25 -08001222 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001223 }
Wei Jia3f273d12015-11-24 09:06:49 -08001224
Andy Hung3f0c9022016-01-15 17:49:46 -08001225 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001226 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1227 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001228}
1229
Andy Hungee58e4a2023-07-07 13:47:37 -07001230void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001231{
Andy Hung972bec12023-08-31 16:13:39 -07001232 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001233 releaseWakeLock_l();
1234}
1235
Andy Hungee58e4a2023-07-07 13:47:37 -07001236void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001237{
Andy Hung3f0c9022016-01-15 17:49:46 -08001238 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001239 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001240 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001241 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001242 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001243 }
1244 mWakeLockToken.clear();
1245 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001246}
1247
Andy Hungee58e4a2023-07-07 13:47:37 -07001248void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001249 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001250 // use checkService() to avoid blocking if power service is not up yet
1251 sp<IBinder> binder =
1252 defaultServiceManager()->checkService(String16("power"));
1253 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001254 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001255 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001256 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001257 binder->linkToDeath(mDeathRecipient);
1258 }
1259 }
1260}
1261
Andy Hungee58e4a2023-07-07 13:47:37 -07001262void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001263 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001264
1265#if !LOG_NDEBUG
1266 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001267 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001268 s << uid << " ";
1269 }
1270 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1271#endif
1272
Andy Hung438e7572015-12-14 15:51:17 -08001273 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1274 if (mSystemReady) {
1275 ALOGE("no wake lock to update, but system ready!");
1276 } else {
1277 ALOGW("no wake lock to update, system not ready yet");
1278 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001279 return;
1280 }
1281 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001282 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001283 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1284 mWakeLockToken, uidsAsInt);
1285 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001286 }
1287}
1288
Andy Hungee58e4a2023-07-07 13:47:37 -07001289void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001290{
Andy Hung972bec12023-08-31 16:13:39 -07001291 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001292 releaseWakeLock_l();
1293 mPowerManager.clear();
1294}
1295
Andy Hungee58e4a2023-07-07 13:47:37 -07001296void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001297 const DeviceDescriptorBaseVector& outDevices __unused)
1298{
1299 ALOGE("%s should only be called in RecordThread", __func__);
1300}
1301
Andy Hungee58e4a2023-07-07 13:47:37 -07001302void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001303{
1304 ALOGE("%s should only be called in RecordThread", __func__);
1305}
1306
Andy Hungee58e4a2023-07-07 13:47:37 -07001307void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001308{
1309 sp<ThreadBase> thread = mThread.promote();
1310 if (thread != 0) {
1311 thread->clearPowerManager();
1312 }
1313 ALOGW("power manager service died !!!");
1314}
1315
Andy Hungee58e4a2023-07-07 13:47:37 -07001316void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001317 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001318{
Andy Hung116bc262023-06-20 18:56:17 -07001319 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001320 if (chain != 0) {
1321 if (type != NULL) {
1322 chain->setEffectSuspended_l(type, suspend);
1323 } else {
1324 chain->setEffectSuspendedAll_l(suspend);
1325 }
1326 }
1327
1328 updateSuspendedSessions_l(type, suspend, sessionId);
1329}
1330
Andy Hungee58e4a2023-07-07 13:47:37 -07001331void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001332{
1333 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1334 if (index < 0) {
1335 return;
1336 }
1337
1338 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1339 mSuspendedSessions.valueAt(index);
1340
1341 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001342 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001343 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001344 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001345 chain->setEffectSuspendedAll_l(true);
1346 } else {
1347 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1348 desc->mType.timeLow);
1349 chain->setEffectSuspended_l(&desc->mType, true);
1350 }
1351 }
1352 }
1353}
1354
Andy Hungee58e4a2023-07-07 13:47:37 -07001355void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001356 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001357 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001358{
1359 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1360
1361 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1362
1363 if (suspend) {
1364 if (index >= 0) {
1365 sessionEffects = mSuspendedSessions.valueAt(index);
1366 } else {
1367 mSuspendedSessions.add(sessionId, sessionEffects);
1368 }
1369 } else {
1370 if (index < 0) {
1371 return;
1372 }
1373 sessionEffects = mSuspendedSessions.valueAt(index);
1374 }
1375
1376
Andy Hung116bc262023-06-20 18:56:17 -07001377 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001378 if (type != NULL) {
1379 key = type->timeLow;
1380 }
1381 index = sessionEffects.indexOfKey(key);
1382
1383 sp<SuspendedSessionDesc> desc;
1384 if (suspend) {
1385 if (index >= 0) {
1386 desc = sessionEffects.valueAt(index);
1387 } else {
1388 desc = new SuspendedSessionDesc();
1389 if (type != NULL) {
1390 desc->mType = *type;
1391 }
1392 sessionEffects.add(key, desc);
1393 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1394 }
1395 desc->mRefCount++;
1396 } else {
1397 if (index < 0) {
1398 return;
1399 }
1400 desc = sessionEffects.valueAt(index);
1401 if (--desc->mRefCount == 0) {
1402 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1403 sessionEffects.removeItemsAt(index);
1404 if (sessionEffects.isEmpty()) {
1405 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1406 sessionId);
1407 mSuspendedSessions.removeItem(sessionId);
1408 }
1409 }
1410 }
1411 if (!sessionEffects.isEmpty()) {
1412 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1413 }
1414}
1415
Andy Hungee58e4a2023-07-07 13:47:37 -07001416void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001417 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001418 bool threadLocked)
1419NO_THREAD_SAFETY_ANALYSIS // manual locking
1420{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001421 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001422 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001423 }
Eric Laurent81784c32012-11-19 14:55:58 -08001424
Eric Laurent81784c32012-11-19 14:55:58 -08001425 if (mType != RECORD) {
1426 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1427 // another session. This gives the priority to well behaved effect control panels
1428 // and applications not using global effects.
1429 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1430 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001431 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001432 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1433 }
1434 }
1435
Eric Laurent6b446ce2019-12-13 10:56:31 -08001436 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001437 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001438 }
1439}
1440
Andy Hungc5007f82023-08-29 14:26:09 -07001441// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001442status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001443 const effect_descriptor_t *desc, audio_session_t sessionId)
1444{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001445 // No global output effect sessions on record threads
1446 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1447 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001448 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1449 desc->name, mThreadName);
1450 return BAD_VALUE;
1451 }
1452 // only pre processing effects on record thread
1453 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1454 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1455 desc->name, mThreadName);
1456 return BAD_VALUE;
1457 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001458
1459 // always allow effects without processing load or latency
1460 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1461 return NO_ERROR;
1462 }
1463
Eric Laurent4c415062016-06-17 16:14:16 -07001464 audio_input_flags_t flags = mInput->flags;
1465 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1466 if (flags & AUDIO_INPUT_FLAG_RAW) {
1467 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1468 desc->name, mThreadName);
1469 return BAD_VALUE;
1470 }
1471 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1472 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1473 desc->name, mThreadName);
1474 return BAD_VALUE;
1475 }
1476 }
jiabineb3bda02020-06-30 14:07:03 -07001477
Andy Hung116bc262023-06-20 18:56:17 -07001478 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001479 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1480 return BAD_VALUE;
1481 }
Eric Laurent4c415062016-06-17 16:14:16 -07001482 return NO_ERROR;
1483}
1484
Andy Hungc5007f82023-08-29 14:26:09 -07001485// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001486status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001487 const effect_descriptor_t *desc, audio_session_t sessionId)
1488{
1489 // no preprocessing on playback threads
1490 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001491 ALOGW("%s: pre processing effect %s created on playback"
1492 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001493 return BAD_VALUE;
1494 }
1495
Eric Laurent3e4de772017-07-16 16:55:08 -07001496 // always allow effects without processing load or latency
1497 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1498 return NO_ERROR;
1499 }
1500
Andy Hung116bc262023-06-20 18:56:17 -07001501 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001502 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1503 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001504 return BAD_VALUE;
1505 }
1506
Eric Laurent4eb45d02023-12-20 12:07:17 +01001507 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001508 && mType != SPATIALIZER) {
1509 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1510 __func__, mType);
1511 return BAD_VALUE;
1512 }
1513
Eric Laurent4c415062016-06-17 16:14:16 -07001514 switch (mType) {
1515 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001516 audio_output_flags_t flags = mOutput->flags;
1517 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1518 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1519 // global effects are applied only to non fast tracks if they are SW
1520 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1521 break;
1522 }
1523 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1524 // only post processing on output stage session
1525 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001526 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1527 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001528 return BAD_VALUE;
1529 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001530 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1531 // only post processing on output stage session
1532 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001533 ALOGW("%s: non post processing effect %s not allowed on device session",
1534 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001535 return BAD_VALUE;
1536 }
Eric Laurent4c415062016-06-17 16:14:16 -07001537 } else {
1538 // no restriction on effects applied on non fast tracks
1539 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1540 break;
1541 }
1542 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001543
Eric Laurent4c415062016-06-17 16:14:16 -07001544 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001545 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001546 return BAD_VALUE;
1547 }
1548 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001549 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1550 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001551 return BAD_VALUE;
1552 }
1553 }
1554 } break;
1555 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001556 // nothing actionable on offload threads, if the effect:
1557 // - is offloadable: the effect can be created
1558 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1559 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001560 break;
1561 case DIRECT:
1562 // Reject any effect on Direct output threads for now, since the format of
1563 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001564 ALOGW("%s: effect %s on DIRECT output thread %s",
1565 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001566 return BAD_VALUE;
1567 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001568 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001569 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1570 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001571 return BAD_VALUE;
1572 }
1573 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001574 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1575 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001576 return BAD_VALUE;
1577 }
1578 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001579 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1580 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001581 return BAD_VALUE;
1582 }
1583 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001584 case SPATIALIZER:
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001585 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are supported on spatializer mixer, but only
1586 // the spatialized track have global effects applied for now.
Eric Laurentb62d0362021-10-26 17:40:18 +02001587 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1588 // are supported and added after the spatializer.
1589 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001590 ALOGD("%s: global effect %s on spatializer thread %s", __func__, desc->name,
1591 mThreadName);
Eric Laurentb62d0362021-10-26 17:40:18 +02001592 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1593 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001594 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001595 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1596 break;
1597 }
1598 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1599 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1600 __func__, desc->name);
1601 return BAD_VALUE;
1602 }
1603 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1604 // only post processing on output stage session
1605 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1606 ALOGW("%s: non post processing effect %s not allowed on device session",
1607 __func__, desc->name);
1608 return BAD_VALUE;
1609 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001610 }
1611 break;
jiabinc658e452022-10-21 20:52:21 +00001612 case BIT_PERFECT:
1613 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1614 // Allow HW accelerated effects of tunnel type
1615 break;
1616 }
1617 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1618 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1619 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1620 // 3) there is any bit-perfect track with the given session id.
1621 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1622 sessionId == AUDIO_SESSION_DEVICE) {
1623 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1624 __func__, desc->name, mThreadName);
1625 return BAD_VALUE;
1626 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1627 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1628 __func__, desc->name, sessionId);
1629 return BAD_VALUE;
1630 }
1631 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001632 default:
1633 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1634 }
1635
1636 return NO_ERROR;
1637}
1638
Andy Hungc5007f82023-08-29 14:26:09 -07001639// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001640sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001641 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001642 const sp<IEffectClient>& effectClient,
1643 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001644 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001645 effect_descriptor_t *desc,
1646 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001647 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001648 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001649 bool probe,
1650 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001651{
Andy Hung116bc262023-06-20 18:56:17 -07001652 sp<IAfEffectModule> effect;
1653 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001654 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001655 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001656 bool chainCreated = false;
1657 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001658 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001659
1660 lStatus = initCheck();
1661 if (lStatus != NO_ERROR) {
1662 ALOGW("createEffect_l() Audio driver not initialized.");
1663 goto Exit;
1664 }
1665
Eric Laurent81784c32012-11-19 14:55:58 -08001666 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1667
Andy Hungc5007f82023-08-29 14:26:09 -07001668 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001669 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001670
Eric Laurent4c415062016-06-17 16:14:16 -07001671 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001672 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001673 goto Exit;
1674 }
1675
Eric Laurent81784c32012-11-19 14:55:58 -08001676 // check for existing effect chain with the requested audio session
1677 chain = getEffectChain_l(sessionId);
1678 if (chain == 0) {
1679 // create a new chain for this session
1680 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001681 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001682 addEffectChain_l(chain);
1683 chain->setStrategy(getStrategyForSession_l(sessionId));
1684 chainCreated = true;
1685 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001686 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001687 }
1688
1689 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1690
1691 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001692 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001693 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001694 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001695 if (lStatus != NO_ERROR) {
1696 goto Exit;
1697 }
1698 effectCreated = true;
1699
jiabinc52b1ff2019-10-31 17:20:42 -07001700 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001701 effect->setDevices(outDeviceTypeAddrs());
1702 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001703 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001704 effect->setAudioSource(mAudioSource);
1705 }
jiabin1319f5a2021-03-30 22:21:24 +00001706 if (effect->isHapticGenerator()) {
1707 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1708 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001709 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001710 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001711 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001712 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001713 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001714 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001715 }
1716 }
Eric Laurent81784c32012-11-19 14:55:58 -08001717 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001718 handle = IAfEffectHandle::create(
1719 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001720 lStatus = handle->initCheck();
1721 if (lStatus == OK) {
1722 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001723 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001724 }
Eric Laurent81784c32012-11-19 14:55:58 -08001725 if (enabled != NULL) {
1726 *enabled = (int)effect->isEnabled();
1727 }
1728 }
1729
1730Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001731 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001732 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001733 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001734 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001735 }
Eric Laurent81784c32012-11-19 14:55:58 -08001736 if (chainCreated) {
1737 removeEffectChain_l(chain);
1738 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001739 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001740 }
1741
Glenn Kasten9156ef32013-08-06 15:39:08 -07001742 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001743 return handle;
1744}
1745
Andy Hungee58e4a2023-07-07 13:47:37 -07001746void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 bool unpinIfLast)
1748{
1749 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001750 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001751 {
Andy Hung972bec12023-08-31 16:13:39 -07001752 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001753 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001754 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001755 return;
1756 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001757 effect = effectBase->asEffectModule();
1758 if (effect == nullptr) {
1759 return;
1760 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001761 // restore suspended effects if the disconnected handle was enabled and the last one.
1762 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1763 if (remove) {
1764 removeEffect_l(effect, true);
1765 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001766 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001767 }
1768 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001769 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001770 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001771 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001772 }
1773 }
1774}
1775
Andy Hungee58e4a2023-07-07 13:47:37 -07001776void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001777 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001778 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001779 broadcast_l();
1780 }
1781 if (!effect->isOffloadable()) {
1782 if (mType == ThreadBase::OFFLOAD) {
1783 PlaybackThread *t = (PlaybackThread *)this;
1784 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1785 }
1786 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001787 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001788 }
1789 }
1790}
1791
Andy Hungee58e4a2023-07-07 13:47:37 -07001792void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001793 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001794 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001795 broadcast_l();
1796 }
1797}
1798
Andy Hungee58e4a2023-07-07 13:47:37 -07001799sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001800 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001801{
Andy Hung972bec12023-08-31 16:13:39 -07001802 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001803 return getEffect_l(sessionId, effectId);
1804}
1805
Andy Hungee58e4a2023-07-07 13:47:37 -07001806sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001807 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001808{
Andy Hung116bc262023-06-20 18:56:17 -07001809 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001810 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1811}
1812
Andy Hungee58e4a2023-07-07 13:47:37 -07001813std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001814{
Andy Hung116bc262023-06-20 18:56:17 -07001815 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001816 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001817}
1818
Andy Hung972bec12023-08-31 16:13:39 -07001819// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1820// ThreadBase::mutex() held
1821status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001822{
1823 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001824 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001825 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001826 bool chainCreated = false;
1827
Eric Laurent5baf2af2013-09-12 17:37:00 -07001828 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001829 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1830 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001831
Eric Laurent81784c32012-11-19 14:55:58 -08001832 if (chain == 0) {
1833 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001834 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001835 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001836 addEffectChain_l(chain);
1837 chain->setStrategy(getStrategyForSession_l(sessionId));
1838 chainCreated = true;
1839 }
Andy Hung972bec12023-08-31 16:13:39 -07001840 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001841
1842 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001843 ALOGW("%s: %p effect %s already present in chain %p",
1844 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001845 return BAD_VALUE;
1846 }
1847
Shunkai Yaod125e402024-01-20 03:19:06 +00001848 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001849
Shunkai Yao29d10572024-03-19 04:31:47 +00001850 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001851 if (status != NO_ERROR) {
1852 if (chainCreated) {
1853 removeEffectChain_l(chain);
1854 }
1855 return status;
1856 }
1857
jiabin8f278ee2019-11-11 12:16:27 -08001858 effect->setDevices(outDeviceTypeAddrs());
1859 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001860 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001861 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001862
Eric Laurent81784c32012-11-19 14:55:58 -08001863 return NO_ERROR;
1864}
1865
Andy Hungee58e4a2023-07-07 13:47:37 -07001866void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001867
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001868 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001869 effect_descriptor_t desc = effect->desc();
1870 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1871 detachAuxEffect_l(effect->id());
1872 }
1873
Andy Hung116bc262023-06-20 18:56:17 -07001874 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001875 if (chain != 0) {
1876 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001877 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001878 removeEffectChain_l(chain);
1879 }
1880 } else {
1881 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1882 }
1883}
1884
Shunkai Yaof4847652024-01-12 00:25:20 +00001885void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1886 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001887{
1888 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001889 for (const auto& effectChain : effectChains) {
1890 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001891 }
1892}
1893
Shunkai Yaof4847652024-01-12 00:25:20 +00001894void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1895 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001896{
Shunkai Yaof4847652024-01-12 00:25:20 +00001897 for (const auto& effectChain : effectChains) {
1898 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001899 }
1900}
1901
Andy Hungee58e4a2023-07-07 13:47:37 -07001902sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001903{
Andy Hung972bec12023-08-31 16:13:39 -07001904 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001905 return getEffectChain_l(sessionId);
1906}
1907
Andy Hungee58e4a2023-07-07 13:47:37 -07001908sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001909 const
Eric Laurent81784c32012-11-19 14:55:58 -08001910{
1911 size_t size = mEffectChains.size();
1912 for (size_t i = 0; i < size; i++) {
1913 if (mEffectChains[i]->sessionId() == sessionId) {
1914 return mEffectChains[i];
1915 }
1916 }
1917 return 0;
1918}
1919
Andy Hungee58e4a2023-07-07 13:47:37 -07001920void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001921{
Andy Hung972bec12023-08-31 16:13:39 -07001922 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001923 size_t size = mEffectChains.size();
1924 for (size_t i = 0; i < size; i++) {
1925 mEffectChains[i]->setMode_l(mode);
1926 }
1927}
1928
Andy Hungee58e4a2023-07-07 13:47:37 -07001929void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001930{
1931 config->type = AUDIO_PORT_TYPE_MIX;
1932 config->ext.mix.handle = mId;
1933 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001934 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001935 config->channel_mask = mChannelMask;
1936 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1937 AUDIO_PORT_CONFIG_FORMAT;
1938}
1939
Andy Hungee58e4a2023-07-07 13:47:37 -07001940void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001941{
Andy Hung972bec12023-08-31 16:13:39 -07001942 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001943 if (mSystemReady) {
1944 return;
1945 }
1946 mSystemReady = true;
1947
1948 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1949 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1950 }
1951 mPendingConfigEvents.clear();
1952}
1953
Andy Hungdae27702016-10-31 14:01:16 -07001954template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001955ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001956 ssize_t index = mActiveTracks.indexOf(track);
1957 if (index >= 0) {
1958 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1959 return index;
1960 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001961 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001962 mActiveTracksGeneration++;
1963 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001964 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001965 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001966 return mActiveTracks.add(track);
1967}
1968
1969template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001970ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001971 ssize_t index = mActiveTracks.remove(track);
1972 if (index < 0) {
1973 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1974 return index;
1975 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001976 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001977 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001978 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001979 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001980 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001981#ifdef TEE_SINK
1982 track->dumpTee(-1 /* fd */, "_REMOVE");
1983#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001984 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001985 return index;
1986}
1987
1988template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001989void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001990 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001991 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001992 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001993 }
1994 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001995 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001996 mActiveTracks.clear();
1997 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001998}
1999
2000template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07002001void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07002002 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002003 // Updates ActiveTracks client uids to the thread wakelock.
2004 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2005 thread->updateWakeLockUids_l(getWakeLockUids());
2006 mLastActiveTracksGeneration = mActiveTracksGeneration;
2007 }
Andy Hungdae27702016-10-31 14:01:16 -07002008}
Eric Laurent83b88082014-06-20 18:31:16 -07002009
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002010template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002011bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002012 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002013 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002014
2015 for (const sp<T> &track : mActiveTracks) {
2016 // Do not short-circuit as all hasChanged states must be reset
2017 // as all the metadata are going to be sent
2018 hasChanged |= track->readAndClearHasChanged();
2019 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002020 return hasChanged;
2021}
2022
2023template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002024void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002025 const char *funcName, const sp<T> &track) const {
2026 if (mLocalLog != nullptr) {
2027 String8 result;
2028 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002029 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002030 }
2031}
2032
Andy Hungee58e4a2023-07-07 13:47:37 -07002033void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002034{
2035 // Thread could be blocked waiting for async
2036 // so signal it to handle state changes immediately
2037 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2038 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2039 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002040 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002041}
2042
Andy Hungd0979812019-02-21 15:51:44 -08002043// Call only from threadLoop() or when it is idle.
2044// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002045void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002046NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002047{
2048 // Do not log if we have no stats.
2049 // We choose the timestamp verifier because it is the most likely item to be present.
2050 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2051 if (nstats == 0) {
2052 return;
2053 }
2054
2055 // Don't log more frequently than once per 12 hours.
2056 // We use BOOTTIME to include suspend time.
2057 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2058 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2059 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2060 return;
2061 }
2062
2063 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2064 mLastRecordedTimeNs = timeNs;
2065
Ray Essickf27e9872019-12-07 06:28:46 -08002066 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002067
2068#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2069
2070 // thread configuration
2071 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2072 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2073 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2074 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2075 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2076 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2077 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002078 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2079 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002080
2081 // thread statistics
2082 if (mIoJitterMs.getN() > 0) {
2083 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2084 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2085 }
2086 if (mProcessTimeMs.getN() > 0) {
2087 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2088 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2089 }
2090 const auto tsjitter = mTimestampVerifier.getJitterMs();
2091 if (tsjitter.getN() > 0) {
2092 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2093 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2094 }
2095 if (mLatencyMs.getN() > 0) {
2096 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2097 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2098 }
Robert Wu06db0a32021-08-10 19:05:34 +00002099 if (mMonopipePipeDepthStats.getN() > 0) {
2100 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2101 mMonopipePipeDepthStats.getMean());
2102 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2103 mMonopipePipeDepthStats.getStdDev());
2104 }
Andy Hungd0979812019-02-21 15:51:44 -08002105
2106 item->selfrecord();
2107}
2108
Andy Hungee58e4a2023-07-07 13:47:37 -07002109product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002110{
Andy Hung583043b2023-07-17 17:05:00 -07002111 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002112 return PRODUCT_STRATEGY_NONE;
2113 }
2114 return AudioSystem::getStrategyForStream(stream);
2115}
2116
Andy Hungc5007f82023-08-29 14:26:09 -07002117// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002118void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002119 const sp<audio_utils::MelProcessor>& /*processor*/)
2120{
2121 // Do nothing
2122 ALOGW("%s: ThreadBase does not support CSD", __func__);
2123}
2124
Andy Hungc5007f82023-08-29 14:26:09 -07002125// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002126void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002127{
2128 // Do nothing
2129 ALOGW("%s: ThreadBase does not support CSD", __func__);
2130}
2131
Eric Laurent81784c32012-11-19 14:55:58 -08002132// ----------------------------------------------------------------------------
2133// Playback
2134// ----------------------------------------------------------------------------
2135
Andy Hung583043b2023-07-17 17:05:00 -07002136PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002137 AudioStreamOut* output,
2138 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002139 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002140 bool systemReady,
2141 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002142 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002143 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002144 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002145 mMixerBuffer(NULL),
2146 mMixerBufferSize(0),
2147 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2148 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002149 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002150 mEffectBuffer(NULL),
2151 mEffectBufferSize(0),
2152 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2153 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002154 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002155 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002156 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002157 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002158 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002159 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002160 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002161 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002162 mMixerStatus(MIXER_IDLE),
2163 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002164 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002165 mBytesRemaining(0),
2166 mCurrentWriteLength(0),
2167 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002168 mWriteAckSequence(0),
2169 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002170 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002171 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002172 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002173 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002174 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002175 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002176 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002177{
Glenn Kastend7dca052015-03-05 16:05:54 -08002178 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002179 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002180
Andy Hungc5007f82023-08-29 14:26:09 -07002181 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002182 // it would be safer to explicitly pass initial masterVolume/masterMute as
2183 // parameter.
2184 //
2185 // If the HAL we are using has support for master volume or master mute,
2186 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2187 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002188 mMasterVolume = afThreadCallback->masterVolume_l();
2189 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002190 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002191 if (mOutput->audioHwDev->canSetMasterVolume()) {
2192 mMasterVolume = 1.0;
2193 }
2194
2195 if (mOutput->audioHwDev->canSetMasterMute()) {
2196 mMasterMute = false;
2197 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002198 mIsMsdDevice = strcmp(
2199 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002200 }
2201
Eric Laurentf1f22e72021-07-13 14:04:14 +02002202 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2203 mMixerChannelMask = mixerConfig->channel_mask;
2204 }
2205
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002206 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002207
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002208 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002209 && mMixerChannelMask != mChannelMask) {
2210 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2211 mChannelMask, mMixerChannelMask);
2212 }
2213
Andy Hungc8fddf32018-08-08 18:32:37 -07002214 // TODO: We may also match on address as well as device type for
2215 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002216 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002217 // TODO: This property should be ensure that only contains one single device type.
2218 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2219 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002220 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2221 : AUDIO_DEVICE_NONE));
2222 }
Andy Hung6b137d12024-08-27 22:35:17 +00002223 if (!audioserver_flags::portid_volume_management()) {
2224 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2225 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2226 mStreamTypes[stream].volume = 0.0f;
2227 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2228 }
2229 // Audio patch and call assistant volume are always max
2230 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2231 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2232 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2233 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002234 }
Eric Laurent81784c32012-11-19 14:55:58 -08002235}
2236
Andy Hungee58e4a2023-07-07 13:47:37 -07002237PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002238{
Andy Hung583043b2023-07-17 17:05:00 -07002239 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002240 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002241 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002242 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002243 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002244}
2245
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002246// Thread virtuals
2247
Andy Hungee58e4a2023-07-07 13:47:37 -07002248void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002249{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002250 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002251 ALOGE("The stream is not open yet"); // This should not happen.
2252 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002253 // Callbacks take strong or weak pointers as a parameter.
2254 // Since PlaybackThread passes itself as a callback handler, it can only
2255 // be done outside of the constructor. Creating weak and especially strong
2256 // pointers to a refcounted object in its own constructor is strongly
2257 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2258 // Even if a function takes a weak pointer, it is possible that it will
2259 // need to convert it to a strong pointer down the line.
2260 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2261 mOutput->stream->setCallback(this) == OK) {
2262 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002263 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002264 }
2265
jiabinf6eb4c32020-02-25 14:06:25 -08002266 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002267 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002268 }
2269 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002270 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002271 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002272}
2273
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002274// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002275void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002276{
2277 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002278 status_t result = mOutput->stream->exit();
2279 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002280}
2281
Andy Hungee58e4a2023-07-07 13:47:37 -07002282void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002283{
Eric Laurent81784c32012-11-19 14:55:58 -08002284 String8 result;
Andy Hung6b137d12024-08-27 22:35:17 +00002285 if (!audioserver_flags::portid_volume_management()) {
2286 result.appendFormat(" Stream volumes in dB: ");
2287 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2288 const stream_type_t *st = &mStreamTypes[i];
2289 if (i > 0) {
2290 result.appendFormat(", ");
2291 }
2292 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2293 if (st->mute) {
2294 result.append("M");
2295 }
Eric Laurent81784c32012-11-19 14:55:58 -08002296 }
2297 }
2298 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002299 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002300 result.clear();
2301
Eric Laurent81784c32012-11-19 14:55:58 -08002302 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2303 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002304 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002305 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002306
2307 size_t numtracks = mTracks.size();
2308 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002309 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002310 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002311 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002312 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002313 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002314 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002315 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002316 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002317 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002318 if (track != 0) {
2319 bool active = mActiveTracks.indexOf(track) >= 0;
2320 if (active) {
2321 numactiveseen++;
2322 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002323 result.append(prefix);
2324 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002325 }
2326 }
2327 } else {
2328 result.append("\n");
2329 }
2330 if (numactiveseen != numactive) {
2331 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002332 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002333 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002334 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002335 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002336 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002337 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002338 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002339 result.append(prefix);
2340 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002341 }
2342 }
2343 }
2344
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002345 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002346}
2347
Andy Hungee58e4a2023-07-07 13:47:37 -07002348void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002349{
Andy Hung04cb8f72020-03-20 13:44:33 -07002350 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002351 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002352 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2353 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002354 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2355 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2356 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2357 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002358 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002359 dprintf(fd, " Total writes: %d\n", mNumWrites);
2360 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2361 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002362 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002363 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002364 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002365 AudioStreamOut *output = mOutput;
2366 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002367 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002368 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002369 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2370 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2371 if (mPipeSink.get() != nullptr) {
2372 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2373 }
2374 if (output != nullptr) {
2375 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002376 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002377 }
Eric Laurent81784c32012-11-19 14:55:58 -08002378}
2379
Andy Hungc5007f82023-08-29 14:26:09 -07002380// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002381sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002382 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002383 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002384 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002385 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002386 audio_format_t format,
2387 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002388 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002389 size_t *pNotificationFrameCount,
2390 uint32_t notificationsPerBuffer,
2391 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002392 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002393 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002394 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002395 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002396 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002397 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002398 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002399 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002400 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002401 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002402 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00002403 audio_output_flags_t *afTrackFlags,
2404 float volume)
Eric Laurent81784c32012-11-19 14:55:58 -08002405{
Glenn Kasten74935e42013-12-19 08:56:45 -08002406 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002407 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002408 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002409 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002410 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002411 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002412 uint32_t sampleRate;
2413
2414 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2415 lStatus = BAD_VALUE;
2416 goto Exit;
2417 }
Eric Laurent21da6472017-11-09 16:29:26 -08002418
2419 if (*pSampleRate == 0) {
2420 *pSampleRate = mSampleRate;
2421 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002422 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002423
2424 // special case for FAST flag considered OK if fast mixer is present
2425 if (hasFastMixer()) {
2426 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2427 }
2428
2429 // Check if requested flags are compatible with output stream flags
2430 if ((*flags & outputFlags) != *flags) {
2431 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2432 *flags, outputFlags);
2433 *flags = (audio_output_flags_t)(*flags & outputFlags);
2434 }
Eric Laurent81784c32012-11-19 14:55:58 -08002435
jiabinc658e452022-10-21 20:52:21 +00002436 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002437 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002438 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002439 if (chain.get() != nullptr) {
2440 // Bit-perfect is required according to the configuration and preferred mixer
2441 // attributes, but it is not in the output flag from the client's request. Explicitly
2442 // adding bit-perfect flag to check the compatibility
2443 audio_output_flags_t flagsToCheck =
2444 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2445 chain->checkOutputFlagCompatibility(&flagsToCheck);
2446 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2447 ALOGE("%s cannot create track as there is data-processing effect attached to "
2448 "given session id(%d)", __func__, sessionId);
2449 lStatus = BAD_VALUE;
2450 goto Exit;
2451 }
2452 *flags = flagsToCheck;
2453 }
2454 }
2455
Eric Laurent81784c32012-11-19 14:55:58 -08002456 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002457 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002458 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002459 // PCM data
2460 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002461 // TODO: extract as a data library function that checks that a computationally
2462 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002463 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002464 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2465 (channelMask == AUDIO_CHANNEL_OUT_MONO
2466 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002467 // hardware sample rate
2468 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002469 // normal mixer has an associated fast mixer
2470 hasFastMixer() &&
2471 // there are sufficient fast track slots available
2472 (mFastTrackAvailMask != 0)
2473 // FIXME test that MixerThread for this fast track has a capable output HAL
2474 // FIXME add a permission test also?
2475 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002476 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2477 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002478 // read the fast track multiplier property the first time it is needed
2479 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2480 if (ok != 0) {
2481 ALOGE("%s pthread_once failed: %d", __func__, ok);
2482 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002483 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002484 }
Eric Laurent4c415062016-06-17 16:14:16 -07002485
2486 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002487 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002488 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002489 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002490 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002491 AUDIO_SESSION_OUTPUT_STAGE,
2492 AUDIO_SESSION_OUTPUT_MIX,
2493 sessionId,
2494 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002495 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002496 if (chain.get() != nullptr) {
2497 audio_output_flags_t old = *flags;
2498 chain->checkOutputFlagCompatibility(flags);
2499 if (old != *flags) {
2500 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2501 (int)session, (int)old, (int)*flags);
2502 }
Eric Laurent4c415062016-06-17 16:14:16 -07002503 }
2504 }
2505 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002506 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002507 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2508 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002509 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002510 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002511 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002512 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002513 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002514 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002515 audio_is_linear_pcm(format), channelMask, sampleRate,
2516 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002517 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002518 }
2519 }
Eric Laurent21da6472017-11-09 16:29:26 -08002520
2521 if (!audio_has_proportional_frames(format)) {
2522 if (sharedBuffer != 0) {
2523 // Same comment as below about ignoring frameCount parameter for set()
2524 frameCount = sharedBuffer->size();
2525 } else if (frameCount == 0) {
2526 frameCount = mNormalFrameCount;
2527 }
2528 if (notificationFrameCount != frameCount) {
2529 notificationFrameCount = frameCount;
2530 }
2531 } else if (sharedBuffer != 0) {
2532 // FIXME: Ensure client side memory buffers need
2533 // not have additional alignment beyond sample
2534 // (e.g. 16 bit stereo accessed as 32 bit frame).
2535 size_t alignment = audio_bytes_per_sample(format);
2536 if (alignment & 1) {
2537 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2538 alignment = 1;
2539 }
2540 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2541 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2542 if (channelCount > 1) {
2543 // More than 2 channels does not require stronger alignment than stereo
2544 alignment <<= 1;
2545 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002546 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002547 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002548 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002549 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002550 goto Exit;
2551 }
Eric Laurent21da6472017-11-09 16:29:26 -08002552
2553 // When initializing a shared buffer AudioTrack via constructors,
2554 // there's no frameCount parameter.
2555 // But when initializing a shared buffer AudioTrack via set(),
2556 // there _is_ a frameCount parameter. We silently ignore it.
2557 frameCount = sharedBuffer->size() / frameSize;
2558 } else {
2559 size_t minFrameCount = 0;
2560 // For fast tracks we try to respect the application's request for notifications per buffer.
2561 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2562 if (notificationsPerBuffer > 0) {
2563 // Avoid possible arithmetic overflow during multiplication.
2564 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2565 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2566 notificationsPerBuffer, mFrameCount);
2567 } else {
2568 minFrameCount = mFrameCount * notificationsPerBuffer;
2569 }
2570 }
2571 } else {
2572 // For normal PCM streaming tracks, update minimum frame count.
2573 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2574 // cover audio hardware latency.
2575 // This is probably too conservative, but legacy application code may depend on it.
2576 // If you change this calculation, also review the start threshold which is related.
2577 uint32_t latencyMs = latency_l();
2578 if (latencyMs == 0) {
2579 ALOGE("Error when retrieving output stream latency");
2580 lStatus = UNKNOWN_ERROR;
2581 goto Exit;
2582 }
2583
2584 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2585 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2586
Eric Laurent81784c32012-11-19 14:55:58 -08002587 }
Eric Laurent21da6472017-11-09 16:29:26 -08002588 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002589 frameCount = minFrameCount;
2590 }
Eric Laurent81784c32012-11-19 14:55:58 -08002591 }
Eric Laurent21da6472017-11-09 16:29:26 -08002592
2593 // Make sure that application is notified with sufficient margin before underrun.
2594 // The client can divide the AudioTrack buffer into sub-buffers,
2595 // and expresses its desire to server as the notification frame count.
2596 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2597 size_t maxNotificationFrames;
2598 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2599 // notify every HAL buffer, regardless of the size of the track buffer
2600 maxNotificationFrames = mFrameCount;
2601 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002602 // Triple buffer the notification period for a triple buffered mixer period;
2603 // otherwise, double buffering for the notification period is fine.
2604 //
2605 // TODO: This should be moved to AudioTrack to modify the notification period
2606 // on AudioTrack::setBufferSizeInFrames() changes.
2607 const int nBuffering =
2608 (uint64_t{frameCount} * mSampleRate)
2609 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2610
Eric Laurent21da6472017-11-09 16:29:26 -08002611 maxNotificationFrames = frameCount / nBuffering;
2612 // If client requested a fast track but this was denied, then use the smaller maximum.
2613 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2614 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2615 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2616 maxNotificationFrames = maxNotificationFramesFastDenied;
2617 }
2618 }
2619 }
2620 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2621 if (notificationFrameCount == 0) {
2622 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2623 maxNotificationFrames, frameCount);
2624 } else {
2625 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2626 notificationFrameCount, maxNotificationFrames, frameCount);
2627 }
2628 notificationFrameCount = maxNotificationFrames;
2629 }
2630 }
2631
Glenn Kasten74935e42013-12-19 08:56:45 -08002632 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002633 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002634
Glenn Kastenc3df8382014-03-13 15:05:25 -07002635 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002636 case BIT_PERFECT:
2637 if (isBitPerfect) {
2638 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2639 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2640 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2641 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2642 mChannelMask);
2643 lStatus = BAD_VALUE;
2644 goto Exit;
2645 }
2646 }
2647 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002648
2649 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002650 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002651 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002652 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2653 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002654 sampleRate, format, channelMask, mOutput, mFormat);
2655 lStatus = BAD_VALUE;
2656 goto Exit;
2657 }
2658 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002659 break;
2660
2661 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002662 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002663 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2664 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002665 sampleRate, format, channelMask, mOutput, mFormat);
2666 lStatus = BAD_VALUE;
2667 goto Exit;
2668 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002669 break;
2670
2671 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002672 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002673 ALOGE("createTrack_l() Bad parameter: format %#x \""
2674 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002675 format, mOutput, mFormat);
2676 lStatus = BAD_VALUE;
2677 goto Exit;
2678 }
Andy Hungcd044842014-08-07 11:04:34 -07002679 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002680 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2681 lStatus = BAD_VALUE;
2682 goto Exit;
2683 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002684 break;
2685
Eric Laurent81784c32012-11-19 14:55:58 -08002686 }
2687
2688 lStatus = initCheck();
2689 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002690 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002691 goto Exit;
2692 }
2693
Andy Hungc5007f82023-08-29 14:26:09 -07002694 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002695 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002696
2697 // all tracks in same audio session must share the same routing strategy otherwise
2698 // conflicts will happen when tracks are moved from one output to another by audio policy
2699 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002700 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002701 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002702 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002703 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002704 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002705 if (sessionId == t->sessionId() && strategy != actual) {
2706 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2707 strategy, actual);
2708 lStatus = BAD_VALUE;
2709 goto Exit;
2710 }
2711 }
2712 }
2713
Deeraj Soman2b515232024-05-14 12:58:24 +05302714 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2715 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002716 // dynamic audio policy.
2717 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302718 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002719 audio_output_flags_t trackFlags = *flags;
2720 if (mType == DIRECT) {
2721 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302722 } else if (mType == OFFLOAD) {
2723 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2724 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002725 }
jiabin94ed47c2023-07-27 23:34:20 +00002726 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002727
Andy Hung8d31fd22023-06-26 19:20:57 -07002728 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002729 channelMask, frameCount,
2730 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002731 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002732 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Andy Hung6b137d12024-08-27 22:35:17 +00002733 speed, isSpatialized, isBitPerfect, volume);
Glenn Kasten03003332013-08-06 15:40:54 -07002734
Glenn Kasten03003332013-08-06 15:40:54 -07002735 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2736 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002737 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002738 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002739 goto Exit;
2740 }
2741 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002742 {
Andy Hung972bec12023-08-31 16:13:39 -07002743 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002744 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002745 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002746 }
2747 }
Eric Laurent81784c32012-11-19 14:55:58 -08002748
Andy Hung116bc262023-06-20 18:56:17 -07002749 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002750 if (chain != 0) {
2751 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2752 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002753 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002754 chain->incTrackCnt();
2755 }
2756
Eric Laurent05067782016-06-01 18:27:28 -07002757 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002758 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2759 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2760 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002761 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002762 }
2763 }
2764
2765 lStatus = NO_ERROR;
2766
2767Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002768 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002769 return track;
2770}
2771
Andy Hung1bc088a2018-02-09 15:57:31 -08002772template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002773ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002774{
Andy Hungc0691382018-09-12 18:01:57 -07002775 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002776 const ssize_t index = mTracks.remove(track);
2777 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002778 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002779 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002780 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002781 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002782 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002783 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002784 }
2785 return index;
2786}
2787
Andy Hungee58e4a2023-07-07 13:47:37 -07002788uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002789{
2790 return latency;
2791}
2792
Andy Hungee58e4a2023-07-07 13:47:37 -07002793uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002794{
Andy Hung972bec12023-08-31 16:13:39 -07002795 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002796 return latency_l();
2797}
Andy Hungee58e4a2023-07-07 13:47:37 -07002798uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002799NO_THREAD_SAFETY_ANALYSIS
2800// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002801{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002802 uint32_t latency;
2803 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2804 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002805 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002806 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002807}
2808
Andy Hungee58e4a2023-07-07 13:47:37 -07002809void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002810{
Andy Hung972bec12023-08-31 16:13:39 -07002811 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002812 // Don't apply master volume in SW if our HAL can do it for us.
2813 if (mOutput && mOutput->audioHwDev &&
2814 mOutput->audioHwDev->canSetMasterVolume()) {
2815 mMasterVolume = 1.0;
2816 } else {
2817 mMasterVolume = value;
2818 }
2819}
2820
Andy Hungee58e4a2023-07-07 13:47:37 -07002821void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002822{
2823 mMasterBalance.store(balance);
2824}
2825
Andy Hungee58e4a2023-07-07 13:47:37 -07002826void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002827{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002828 if (isDuplicating()) {
2829 return;
2830 }
Andy Hung972bec12023-08-31 16:13:39 -07002831 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002832 // Don't apply master mute in SW if our HAL can do it for us.
2833 if (mOutput && mOutput->audioHwDev &&
2834 mOutput->audioHwDev->canSetMasterMute()) {
2835 mMasterMute = false;
2836 } else {
2837 mMasterMute = muted;
2838 }
2839}
2840
Andy Hungee58e4a2023-07-07 13:47:37 -07002841void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002842{
Andy Hung972bec12023-08-31 16:13:39 -07002843 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002844 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002845 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002846}
2847
Andy Hungee58e4a2023-07-07 13:47:37 -07002848void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002849{
Andy Hung972bec12023-08-31 16:13:39 -07002850 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002851 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002852 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002853}
2854
Andy Hungee58e4a2023-07-07 13:47:37 -07002855float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002856{
Andy Hung972bec12023-08-31 16:13:39 -07002857 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002858 return mStreamTypes[stream].volume;
2859}
2860
Andy Hung6b137d12024-08-27 22:35:17 +00002861status_t PlaybackThread::setPortsVolume(
2862 const std::vector<audio_port_handle_t>& portIds, float volume) {
2863 audio_utils::lock_guard _l(mutex());
2864 for (const auto& portId : portIds) {
2865 for (size_t i = 0; i < mTracks.size(); i++) {
2866 sp<IAfTrack> track = mTracks[i].get();
2867 if (portId == track->portId()) {
2868 track->setPortVolume(volume);
2869 break;
2870 }
2871 }
2872 }
2873 broadcast_l();
2874 return NO_ERROR;
2875}
2876
Andy Hungee58e4a2023-07-07 13:47:37 -07002877void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002878{
2879 mOutput->stream->setVolume(left, right);
2880}
2881
Andy Hungc5007f82023-08-29 14:26:09 -07002882// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002883status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002884{
2885 status_t status = ALREADY_EXISTS;
2886
Eric Laurent81784c32012-11-19 14:55:58 -08002887 if (mActiveTracks.indexOf(track) < 0) {
2888 // the track is newly added, make sure it fills up all its
2889 // buffers before playing. This is to ensure the client will
2890 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002891 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002892 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002893 // Because the track is not on the ActiveTracks,
2894 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002895 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002896 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002897 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002898 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002899 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002900 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002901 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002902 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002903 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002904 }
2905 return INVALID_OPERATION;
2906 }
2907 // abort if start is rejected by audio policy manager
2908 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002909 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2910 // current playback thread is reopened, which may happen when clients set preferred
2911 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2912 // immediately.
2913 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 }
2915#ifdef ADD_BATTERY_DATA
2916 // to track the speaker usage
2917 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2918#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002919 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002920 }
2921
Eric Laurent51716182016-02-29 18:00:56 -08002922 // set retry count for buffer fill
2923 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002924 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002925 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002926 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002927 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002928 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002929 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002930 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002931 track->retryCount() = kMaxTrackStartupRetries;
2932 track->fillingStatus() =
2933 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002934 }
2935
Andy Hung116bc262023-06-20 18:56:17 -07002936 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002937 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2938 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002939 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002940 // Unlock due to VibratorService will lock for this call and will
2941 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002942 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002943 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002944 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002945 std::optional<media::AudioVibratorInfo> vibratorInfo;
2946 {
2947 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2948 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002949 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002950 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002951 }
Andy Hungc5007f82023-08-29 14:26:09 -07002952 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002953 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002954 if (vibratorInfo) {
2955 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2956 }
2957
jiabin57303cc2018-12-18 15:45:57 -08002958 // Haptic playback should be enabled by vibrator service.
2959 if (track->getHapticPlaybackEnabled()) {
2960 // Disable haptic playback of all active track to ensure only
2961 // one track playing haptic if current track should play haptic.
2962 for (const auto &t : mActiveTracks) {
2963 t->setHapticPlaybackEnabled(false);
2964 }
jiabin245cdd92018-12-07 17:55:15 -08002965 }
jiabine70bc7f2020-06-30 22:07:55 -07002966
2967 // Set haptic intensity for effect
2968 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002969 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002970 }
jiabin245cdd92018-12-07 17:55:15 -08002971 }
2972
Andy Hung8d31fd22023-06-26 19:20:57 -07002973 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002974 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002975
2976 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2977 // all key changes are complete. It is possible that the threadLoop will begin
2978 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002979 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002980
Eric Laurentd0107bc2013-06-11 14:38:48 -07002981 if (chain != 0) {
2982 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2983 track->sessionId());
2984 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002985 }
2986
Andy Hungc2b11cb2020-04-22 09:04:01 -07002987 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002988 status = NO_ERROR;
2989 }
2990
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002991 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002992 return status;
2993}
2994
Andy Hungee58e4a2023-07-07 13:47:37 -07002995bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002996{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002997 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002998 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002999 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07003000 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08003002 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07003003 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07003004 if (track->isPausePending()) {
3005 track->pauseAck();
3006 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003007 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003008 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003009
3010 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003011}
3012
Andy Hungee58e4a2023-07-07 13:47:37 -07003013void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003014{
3015 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003016
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003017 String8 result;
3018 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003019 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003020
Eric Laurent81784c32012-11-19 14:55:58 -08003021 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003022 {
Andy Hung972bec12023-08-31 16:13:39 -07003023 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003024 mAudioTrackCallbacks.erase(track);
3025 }
Eric Laurent81784c32012-11-19 14:55:58 -08003026 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003027 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003028 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003029 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3030 mFastTrackAvailMask |= 1 << index;
3031 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003032 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003033 }
Andy Hung116bc262023-06-20 18:56:17 -07003034 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003035 if (chain != 0) {
3036 chain->decTrackCnt();
3037 }
3038}
3039
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003040std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3041{
3042 std::set<int32_t> result;
3043 for (const auto& t : mTracks) {
3044 if (t->isExternalTrack()) {
3045 result.insert(t->portId());
3046 }
3047 }
3048 return result;
3049}
3050
3051std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3052{
3053 audio_utils::lock_guard _l(mutex());
3054 return getTrackPortIds_l();
3055}
3056
Andy Hungee58e4a2023-07-07 13:47:37 -07003057String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003058{
Andy Hung972bec12023-08-31 16:13:39 -07003059 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003060 String8 out_s8;
3061 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3062 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003063 }
Andy Hung920f6572022-10-06 12:09:49 -07003064 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003065}
3066
Andy Hungee58e4a2023-07-07 13:47:37 -07003067status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003068 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003069 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003070 return NO_INIT;
3071 }
3072 return mOutput->stream->selectPresentation(presentationId, programId);
3073}
3074
Andy Hungab65b182023-09-06 19:41:47 -07003075void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003076 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003077 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003078 sp<AudioIoDescriptor> desc;
3079 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003080 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003081 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003082 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003083 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003084 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3085 mSampleRate, mFormat, mChannelMask,
3086 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3087 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003088 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003089 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003090 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003091 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003092 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003093 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003094 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003095 break;
3096 }
Andy Hungab65b182023-09-06 19:41:47 -07003097 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003098}
3099
Andy Hungee58e4a2023-07-07 13:47:37 -07003100void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003102 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003103}
3104
Andy Hungee58e4a2023-07-07 13:47:37 -07003105void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003106{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003107 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003108}
3109
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003110void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003111{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003112 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003113}
3114
Andy Hungee58e4a2023-07-07 13:47:37 -07003115void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003116 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003117{
Andy Hungee58e4a2023-07-07 13:47:37 -07003118 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003119 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003120 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003121 if (playbackThread == nullptr) {
3122 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3123 return;
3124 }
3125
jiabinf6eb4c32020-02-25 14:06:25 -08003126 audio_utils::metadata::Data metadata =
3127 audio_utils::metadata::dataFromByteString(metadataBs);
3128 if (metadata.empty()) {
3129 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3130 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3131 (int)metadataBs.size());
3132 return;
3133 }
3134
3135 audio_utils::metadata::ByteString metaDataStr =
3136 audio_utils::metadata::byteStringFromData(metadata);
3137 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003138 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003139 for (const auto& callbackPair : mAudioTrackCallbacks) {
3140 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003141 }
3142 }).detach();
3143}
3144
Andy Hungee58e4a2023-07-07 13:47:37 -07003145void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003146{
Andy Hung972bec12023-08-31 16:13:39 -07003147 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003148 // reject out of sequence requests
3149 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3150 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003151 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003152 }
3153}
3154
Andy Hungee58e4a2023-07-07 13:47:37 -07003155void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003156{
Andy Hung972bec12023-08-31 16:13:39 -07003157 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003158 // reject out of sequence requests
3159 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003160 // Register discontinuity when HW drain is completed because that can cause
3161 // the timestamp frame position to reset to 0 for direct and offload threads.
3162 // (Out of sequence requests are ignored, since the discontinuity would be handled
3163 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003164 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003165 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003166 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003167 }
3168}
3169
Andy Hungee58e4a2023-07-07 13:47:37 -07003170void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003171NO_THREAD_SAFETY_ANALYSIS
3172// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003173{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003174 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003175 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3176 mSampleRate = audioConfig.sample_rate;
3177 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003178 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003179 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003180 }
Andy Hung81994d62023-07-20 21:44:14 -07003181 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003182 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3183 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003184 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003185
3186 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3187 mMixerChannelMask = mChannelMask;
3188 }
3189
Andy Hunge5412692014-05-16 11:25:07 -07003190 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003191 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003192
Eric Laurentf1f22e72021-07-13 14:04:14 +02003193 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3194
Phil Burkca5e6142015-07-14 09:42:29 -07003195 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003196 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003197 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003198 // Get format from the shim, which will be different than the HAL format
3199 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003200 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003201 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003202 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003203 }
Andy Hung81994d62023-07-20 21:44:14 -07003204 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003205 LOG_FATAL("HAL format %#x not supported for mixed output",
3206 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003207 }
Phil Burk062e67a2015-02-11 13:40:50 -08003208 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003209 result = mOutput->stream->getBufferSize(&mBufferSize);
3210 LOG_ALWAYS_FATAL_IF(result != OK,
3211 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003212 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003213 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003214 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003215 mFrameCount);
3216 }
3217
Eric Laurentd1f69b02014-12-15 14:33:13 -08003218 mHwSupportsPause = false;
3219 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003220 bool supportsPause = false, supportsResume = false;
3221 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3222 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003223 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003224 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003225 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003226 } else if (supportsResume) {
3227 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003228 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003229 }
3230 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003231 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3232 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3233 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003234
Andy Hungfbfc3952015-01-15 13:33:51 -08003235 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3236 // For best precision, we use float instead of the associated output
3237 // device format (typically PCM 16 bit).
3238
3239 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3240 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3241 mBufferSize = mFrameSize * mFrameCount;
3242
3243 // TODO: We currently use the associated output device channel mask and sample rate.
3244 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3245 // (if a valid mask) to avoid premature downmix.
3246 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3247 // instead of the output device sample rate to avoid loss of high frequency information.
3248 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3249 }
3250
Andy Hung09a50072014-02-27 14:30:47 -08003251 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003252 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003253 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003254 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3255 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003256 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3257 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003258
Eric Laurent81784c32012-11-19 14:55:58 -08003259 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3260 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3261 maxNormalFrameCount = maxNormalFrameCount & ~15;
3262 if (maxNormalFrameCount < minNormalFrameCount) {
3263 maxNormalFrameCount = minNormalFrameCount;
3264 }
3265 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3266 if (multiplier <= 1.0) {
3267 multiplier = 1.0;
3268 } else if (multiplier <= 2.0) {
3269 if (2 * mFrameCount <= maxNormalFrameCount) {
3270 multiplier = 2.0;
3271 } else {
3272 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3273 }
3274 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003275 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003276 }
3277 }
3278 mNormalFrameCount = multiplier * mFrameCount;
3279 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003280 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003281 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3282 }
Andy Hungab65b182023-09-06 19:41:47 -07003283 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3284 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003285
Andy Hung08fb1742015-05-31 23:22:10 -07003286 // Check if we want to throttle the processing to no more than 2x normal rate
3287 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003288 mThreadThrottleTimeMs = 0;
3289 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003290 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3291
Andy Hung010a1a12014-03-13 13:57:33 -07003292 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3293 // Originally this was int16_t[] array, need to remove legacy implications.
3294 free(mSinkBuffer);
3295 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003296
Andy Hung5b10a202014-03-13 13:59:29 -07003297 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3298 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3299 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003300 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003301
Andy Hung69aed5f2014-02-25 17:24:40 -08003302 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3303 // drives the output.
3304 free(mMixerBuffer);
3305 mMixerBuffer = NULL;
3306 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003307 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003308 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003309 * audio_bytes_per_sample(mMixerBufferFormat);
3310 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3311 }
Andy Hung98ef9782014-03-04 14:46:50 -08003312 free(mEffectBuffer);
3313 mEffectBuffer = NULL;
3314 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003315 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003316 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003317 * audio_bytes_per_sample(mEffectBufferFormat);
3318 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3319 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003320
Eric Laurentb62d0362021-10-26 17:40:18 +02003321 if (mType == SPATIALIZER) {
3322 free(mPostSpatializerBuffer);
3323 mPostSpatializerBuffer = nullptr;
3324 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3325 * audio_bytes_per_sample(mEffectBufferFormat);
3326 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3327 }
3328
Mikhail Naganov55773032020-10-01 15:08:13 -07003329 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3330 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003331 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3332 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003333 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003334
Eric Laurent81784c32012-11-19 14:55:58 -08003335 // force reconfiguration of effect chains and engines to take new buffer size and audio
3336 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003337 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003338 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3339 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003340 // create a copy of mEffectChains as calling moveEffectChain_ll()
3341 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003342 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003343 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003344 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003345 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003346 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003347
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003348 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003349 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003350 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003351 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003352 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3353 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3354 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3355 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3356 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3357 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3358 (int32_t)mHapticChannelMask)
3359 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3360 (int32_t)mHapticChannelCount)
3361 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003362 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003363 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3364 (int32_t)mFrameCount) // sic - added HAL
3365 ;
3366 uint32_t latencyMs;
3367 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3368 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3369 }
3370 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003371}
3372
Andy Hungee58e4a2023-07-07 13:47:37 -07003373ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003374{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003375 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003376 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003377 }
3378 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003379 static const bool stereo_spatialization_property =
3380 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3381 const bool stereo_spatialization_enabled =
3382 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3383 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003384 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3385 for (const sp<IAfTrack>& track : mActiveTracks) {
3386 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3387 allSessionsMetadata[track->sessionId()];
3388 auto backInserter = std::back_inserter(sessionMetadata);
3389 // No track is invalid as this is called after prepareTrack_l in the same
3390 // critical section
3391 track->copyMetadataTo(backInserter);
3392 }
3393 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3394 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3395 metadata.tracks.insert(metadata.tracks.end(),
3396 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3397 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3398 chain->sendMetadata_l(sessionTrackMetadata, {});
3399 }
3400 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3401 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3402 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3403 }
3404 }
3405 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3406 chain->sendMetadata_l(metadata.tracks, {});
3407 }
3408 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3409 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3410 }
3411 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3412 chain->sendMetadata_l(metadata.tracks, {});
3413 }
3414 } else {
3415 auto backInserter = std::back_inserter(metadata.tracks);
3416 for (const sp<IAfTrack>& track : mActiveTracks) {
3417 // No track is invalid as this is called after prepareTrack_l in the same
3418 // critical section
3419 track->copyMetadataTo(backInserter);
3420 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003421 }
Kevin Rocard12381092018-04-11 09:19:59 -07003422 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003423 MetadataUpdate change;
3424 change.playbackMetadataUpdate = metadata.tracks;
3425 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003426}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003427
Andy Hungee58e4a2023-07-07 13:47:37 -07003428void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003429 const StreamOutHalInterface::SourceMetadata& metadata)
3430{
3431 mOutput->stream->updateSourceMetadata(metadata);
3432};
3433
Andy Hungee58e4a2023-07-07 13:47:37 -07003434status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003435 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003436{
3437 if (halFrames == NULL || dspFrames == NULL) {
3438 return BAD_VALUE;
3439 }
Andy Hung972bec12023-08-31 16:13:39 -07003440 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003441 if (initCheck() != NO_ERROR) {
3442 return INVALID_OPERATION;
3443 }
Andy Hung818e7a32016-02-16 18:08:07 -08003444 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003445 *halFrames = framesWritten;
3446
3447 if (isSuspended()) {
3448 // return an estimation of rendered frames when the output is suspended
3449 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003450 *dspFrames = (uint32_t)
3451 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003452 return NO_ERROR;
3453 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003454 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003455 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003456 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003457 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003458 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003459 }
3460}
3461
Andy Hungee58e4a2023-07-07 13:47:37 -07003462product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003463{
3464 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3465 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3466 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003467 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003468 }
3469 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003470 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003471 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003472 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003473 }
3474 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003475 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003476}
3477
3478
Andy Hungee58e4a2023-07-07 13:47:37 -07003479AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003480{
Andy Hung972bec12023-08-31 16:13:39 -07003481 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003482 return mOutput;
3483}
3484
Andy Hungee58e4a2023-07-07 13:47:37 -07003485AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003486{
Andy Hung972bec12023-08-31 16:13:39 -07003487 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003488 AudioStreamOut *output = mOutput;
3489 mOutput = NULL;
3490 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3491 // must push a NULL and wait for ack
3492 mOutputSink.clear();
3493 mPipeSink.clear();
3494 mNormalSink.clear();
3495 return output;
3496}
3497
Andy Hungc5007f82023-08-29 14:26:09 -07003498// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003499sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003500{
3501 if (mOutput == NULL) {
3502 return NULL;
3503 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003504 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003505}
3506
Andy Hungee58e4a2023-07-07 13:47:37 -07003507uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003508{
3509 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3510}
3511
Andy Hungee58e4a2023-07-07 13:47:37 -07003512status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003513{
3514 if (!isValidSyncEvent(event)) {
3515 return BAD_VALUE;
3516 }
3517
Andy Hung972bec12023-08-31 16:13:39 -07003518 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003519
3520 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003521 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003522 if (event->triggerSession() == track->sessionId()) {
3523 (void) track->setSyncEvent(event);
3524 return NO_ERROR;
3525 }
3526 }
3527
3528 return NAME_NOT_FOUND;
3529}
3530
Andy Hungee58e4a2023-07-07 13:47:37 -07003531bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003532{
3533 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3534}
3535
Andy Hungee58e4a2023-07-07 13:47:37 -07003536void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003537 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003538{
Andy Hungfe726a62018-09-27 15:17:25 -07003539 // Miscellaneous track cleanup when removed from the active list,
3540 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003541#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003542 for (const auto& track : tracksToRemove) {
3543 if (track->isExternalTrack()) {
3544 // to track the speaker usage
3545 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003546 }
3547 }
Andy Hungfe726a62018-09-27 15:17:25 -07003548#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003549}
3550
Andy Hungee58e4a2023-07-07 13:47:37 -07003551void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003552{
3553 if (!mMasterMute) {
3554 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003555 if (mOutDeviceTypeAddrs.empty()) {
3556 ALOGD("ro.audio.silent is ignored since no output device is set");
3557 return;
3558 }
Andy Hungab65b182023-09-06 19:41:47 -07003559 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003560 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3561 return;
3562 }
Eric Laurent81784c32012-11-19 14:55:58 -08003563 if (property_get("ro.audio.silent", value, "0") > 0) {
3564 char *endptr;
3565 unsigned long ul = strtoul(value, &endptr, 0);
3566 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003567 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003568 // The setprop command will not allow a property to be changed after
3569 // the first time it is set, so we don't have to worry about un-muting.
3570 setMasterMute_l(true);
3571 }
3572 }
3573 }
3574}
3575
3576// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003577ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003578{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003579 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003580 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003581 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003582 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003583
3584 // If an NBAIO sink is present, use it to write the normal mixer's submix
3585 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003586
Andy Hung010a1a12014-03-13 13:57:33 -07003587 const size_t count = mBytesRemaining / mFrameSize;
3588
Simon Wilson2d590962012-11-29 15:18:50 -08003589 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003590 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003591 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003592 if (screenState != mScreenState) {
3593 mScreenState = screenState;
3594 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3595 if (pipe != NULL) {
3596 pipe->setAvgFrames((mScreenState & 1) ?
3597 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3598 }
3599 }
Andy Hung010a1a12014-03-13 13:57:33 -07003600 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003601 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003602
Eric Laurent81784c32012-11-19 14:55:58 -08003603 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003604 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003605
Andy Hung8946a282018-04-19 20:04:56 -07003606#ifdef TEE_SINK
3607 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3608#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003609 } else {
3610 bytesWritten = framesWritten;
3611 }
3612 // otherwise use the HAL / AudioStreamOut directly
3613 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003614 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003615
Eric Laurentbfb1b832013-01-07 09:53:42 -08003616 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003617 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3618 mWriteAckSequence += 2;
3619 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003620 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003621 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003622 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003623 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003624 // FIXME We should have an implementation of timestamps for direct output threads.
3625 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003626 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003627 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003628
Eric Laurentbfb1b832013-01-07 09:53:42 -08003629 if (mUseAsyncWrite &&
3630 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3631 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003632 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003633 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003634 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003635 }
Eric Laurent81784c32012-11-19 14:55:58 -08003636 }
3637
Eric Laurent81784c32012-11-19 14:55:58 -08003638 mNumWrites++;
3639 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003640 if (mStandby) {
3641 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003642 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003643 mStandby = false;
3644 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003645 return bytesWritten;
3646}
3647
Andy Hungc5007f82023-08-29 14:26:09 -07003648// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003649void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003650 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003651{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003652 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003653 if (outputSink != nullptr) {
3654 outputSink->startMelComputation(processor);
3655 }
Vlad Popab042ee62022-10-20 18:05:00 +02003656}
3657
Andy Hungc5007f82023-08-29 14:26:09 -07003658// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003659void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003660{
3661 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003662 if (outputSink != nullptr) {
3663 outputSink->stopMelComputation();
3664 }
Vlad Popab042ee62022-10-20 18:05:00 +02003665}
3666
Andy Hungee58e4a2023-07-07 13:47:37 -07003667void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003668{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003669 bool supportsDrain = false;
3670 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003671 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3672 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003673 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3674 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003675 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003676 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003677 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003678 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003679 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003680 }
3681}
3682
Andy Hungee58e4a2023-07-07 13:47:37 -07003683void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003684{
Eric Laurent275e8e92014-11-30 15:14:47 -08003685 {
Andy Hung972bec12023-08-31 16:13:39 -07003686 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003687 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003688 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003689 track->invalidate();
3690 }
Andy Hungdae27702016-10-31 14:01:16 -07003691 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3692 // After we exit there are no more track changes sent to BatteryNotifier
3693 // because that requires an active threadLoop.
3694 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3695 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003696 }
Eric Laurent81784c32012-11-19 14:55:58 -08003697}
3698
3699/*
3700The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003701 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003702 - mActiveSleepTimeUs from activeSleepTimeUs()
3703 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003704 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3705 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003706 - maxPeriod from frame count and sample rate (MIXER only)
3707
3708The parameters that affect these derived values are:
3709 - frame count
3710 - frame size
3711 - sample rate
3712 - device type: A2DP or not
3713 - device latency
3714 - format: PCM or not
3715 - active sleep time
3716 - idle sleep time
3717*/
3718
Andy Hungee58e4a2023-07-07 13:47:37 -07003719void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003720{
Andy Hung25c2dac2014-02-27 14:56:00 -08003721 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003722 mActiveSleepTimeUs = activeSleepTimeUs();
3723 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003724
Andy Hung8fe87eb2023-07-20 21:31:38 -07003725 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003726
Eric Laurent42537be2016-01-08 17:16:42 -08003727 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3728 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003729 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003730 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3731 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3732 }
3733 }
Eric Laurent81784c32012-11-19 14:55:58 -08003734}
3735
Andy Hungee58e4a2023-07-07 13:47:37 -07003736bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003737{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003738 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003739 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003740 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003741 size_t size = mTracks.size();
3742 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003743 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003744 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003745 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003746 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003747 }
3748 }
Eric Laurent13084622016-05-17 10:51:49 -07003749 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003750}
3751
Andy Hungee58e4a2023-07-07 13:47:37 -07003752void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003753{
Andy Hung972bec12023-08-31 16:13:39 -07003754 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003755 invalidateTracks_l(streamType);
3756}
3757
Andy Hungee58e4a2023-07-07 13:47:37 -07003758void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003759 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003760 invalidateTracks_l(portIds);
3761}
3762
Andy Hungee58e4a2023-07-07 13:47:37 -07003763bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003764 bool trackMatch = false;
3765 const size_t size = mTracks.size();
3766 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003767 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003768 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3769 t->invalidate();
3770 portIds.erase(t->portId());
3771 trackMatch = true;
3772 }
3773 if (portIds.empty()) {
3774 break;
3775 }
3776 }
3777 return trackMatch;
3778}
3779
jiabinf042b9b2021-05-07 23:46:28 +00003780// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003781IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003782 audio_port_handle_t trackPortId) {
3783 for (size_t i = 0; i < mTracks.size(); i++) {
3784 if (mTracks[i]->portId() == trackPortId) {
3785 return mTracks[i].get();
3786 }
3787 }
3788 return nullptr;
3789}
3790
Andy Hungee58e4a2023-07-07 13:47:37 -07003791status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003792{
Glenn Kastend848eb42016-03-08 13:42:11 -08003793 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003794 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003795 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003796
Andy Hungd3639922022-04-28 18:00:49 -07003797 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003798 if (!audio_is_global_session(session)) {
3799 // player sessions on a spatializer output will use a dedicated input buffer and
3800 // will either output multi channel to mEffectBuffer if the track is spatilaized
3801 // or stereo to mPostSpatializerBuffer if not spatialized.
3802 uint32_t channelMask;
3803 bool isSessionSpatialized =
3804 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3805 if (isSessionSpatialized) {
3806 channelMask = mMixerChannelMask;
3807 } else {
3808 channelMask = mChannelMask;
3809 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003810 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003811 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003812 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003813 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003814 &halInBuffer);
3815 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003816
Andy Hung583043b2023-07-17 17:05:00 -07003817 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003818 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3819 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3820 &halOutBuffer);
3821 if (result != OK) return result;
3822
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003823 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003824
Mikhail Naganov022b9952017-01-04 16:36:51 -08003825 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3826 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003827 } else {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003828 status_t result = INVALID_OPERATION;
3829 // Buffer configuration for global sessions on a SPATIALIZER thread:
3830 // - AUDIO_SESSION_OUTPUT_MIX session uses the mEffectBuffer as input and output buffer
3831 // - AUDIO_SESSION_OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3832 // mPostSpatializerBuffer as output buffer
3833 // - AUDIO_SESSION_DEVICE session uses the mPostSpatializerBuffer as input and output
3834 // buffer
3835 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_OUTPUT_STAGE) {
3836 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3837 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3838 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003839
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003840 if (session == AUDIO_SESSION_OUTPUT_MIX) {
3841 halOutBuffer = halInBuffer;
3842 }
3843 }
3844
3845 if (session == AUDIO_SESSION_OUTPUT_STAGE || session == AUDIO_SESSION_DEVICE) {
3846 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3847 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3848 if (result != OK) return result;
3849
3850 if (session == AUDIO_SESSION_DEVICE) {
3851 halInBuffer = halOutBuffer;
3852 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003853 }
3854 }
3855 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003856 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003857 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3858 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3859 &halInBuffer);
3860 if (result != OK) return result;
3861 halOutBuffer = halInBuffer;
3862 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3863 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003864 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003865 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003866 // Only one effect chain can be present in direct output thread and it uses
3867 // the sink buffer as input
3868 if (mType != DIRECT) {
3869 size_t numSamples = mNormalFrameCount
3870 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3871 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003872 const status_t allocateStatus =
3873 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003874 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003875 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003876 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003877
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003878 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003879 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3880 buffer, session);
3881 }
3882 }
3883 }
3884
3885 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003886 // Attach all tracks with same session ID to this chain.
3887 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003888 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003889 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003890 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3891 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003892 track->setMainBuffer(buffer);
3893 chain->incTrackCnt();
3894 }
3895 }
3896
3897 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003898 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003899 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003900 ALOGV("addEffectChain_l() activating track %p on session %d",
3901 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003902 chain->incActiveTrackCnt();
3903 }
3904 }
3905 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003906
Eric Laurentaaa44472014-09-12 17:41:50 -07003907 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003908 chain->setInBuffer(halInBuffer);
3909 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003910 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3911 // chains list in order to be processed last as it contains output device effects.
3912 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3913 // processing effects specific to an output stream before effects applied to all streams
3914 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003915 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3916 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003917 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003918 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003919 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003920 // Effect chain for other sessions are inserted at beginning of effect
3921 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003922 // sessions is not important.
3923 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003924 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3925 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003926 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003927 size_t size = mEffectChains.size();
3928 size_t i = 0;
3929 for (i = 0; i < size; i++) {
3930 if (mEffectChains[i]->sessionId() < session) {
3931 break;
3932 }
3933 }
3934 mEffectChains.insertAt(chain, i);
3935 checkSuspendOnAddEffectChain_l(chain);
3936
3937 return NO_ERROR;
3938}
3939
Andy Hungee58e4a2023-07-07 13:47:37 -07003940size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003941{
Glenn Kastend848eb42016-03-08 13:42:11 -08003942 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003943
3944 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3945
3946 for (size_t i = 0; i < mEffectChains.size(); i++) {
3947 if (chain == mEffectChains[i]) {
3948 mEffectChains.removeAt(i);
3949 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003950 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003951 if (session == track->sessionId()) {
3952 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3953 chain.get(), session);
3954 chain->decActiveTrackCnt();
3955 }
3956 }
3957
3958 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003959 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003960 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003961 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003962 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003963 chain->decTrackCnt();
3964 }
3965 }
3966 break;
3967 }
3968 }
3969 return mEffectChains.size();
3970}
3971
Andy Hungee58e4a2023-07-07 13:47:37 -07003972status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003973 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003974{
Andy Hung972bec12023-08-31 16:13:39 -07003975 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003976 return attachAuxEffect_l(track, EffectId);
3977}
3978
Andy Hungee58e4a2023-07-07 13:47:37 -07003979status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003980 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003981{
3982 status_t status = NO_ERROR;
3983
3984 if (EffectId == 0) {
3985 track->setAuxBuffer(0, NULL);
3986 } else {
3987 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003988 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003989 if (effect != 0) {
3990 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3991 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3992 } else {
3993 status = INVALID_OPERATION;
3994 }
3995 } else {
3996 status = BAD_VALUE;
3997 }
3998 }
3999 return status;
4000}
4001
Andy Hungee58e4a2023-07-07 13:47:37 -07004002void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08004003{
4004 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004005 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004006 if (track->auxEffectId() == effectId) {
4007 attachAuxEffect_l(track, 0);
4008 }
4009 }
4010}
4011
Andy Hungee58e4a2023-07-07 13:47:37 -07004012bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07004013NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08004014{
Andy Hung78d8d952023-05-30 18:10:23 -07004015 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08004016
Andy Hung077d62e2023-10-03 10:49:34 -07004017 if (mType == SPATIALIZER) {
4018 const pid_t tid = getTid();
4019 if (tid == -1) { // odd: we are here, we must be a running thread.
4020 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4021 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004022 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4023 if (priorityBoost > 0) {
4024 stream()->setHalThreadPriority(priorityBoost);
4025 }
Andy Hung077d62e2023-10-03 10:49:34 -07004026 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004027 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4028 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4029 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4030 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4031 // only on ARC.
4032 const pid_t tid = getTid();
4033 if (tid == -1) {
4034 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4035 } else {
4036 const status_t status = requestPriority(getpid(),
4037 tid,
4038 kPriorityPlaybackThreadArc,
4039 false /* isForApp */,
4040 true /* asynchronous */);
4041 if (status != OK) {
4042 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4043 status);
4044 } else {
4045 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4046 }
4047 }
Andy Hung077d62e2023-10-03 10:49:34 -07004048 }
4049
Andy Hung8d31fd22023-06-26 19:20:57 -07004050 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004051
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004052 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004053 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004054
4055 // MIXER
4056 nsecs_t lastWarning = 0;
4057
4058 // DUPLICATING
4059 // FIXME could this be made local to while loop?
4060 writeFrames = 0;
4061
4062 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004063 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004064
Andy Hungd3639922022-04-28 18:00:49 -07004065 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004066 sleepTimeShift = 0;
4067 }
4068
4069 CpuStats cpuStats;
4070 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4071
4072 acquireWakeLock();
4073
Glenn Kasteneef598c2017-04-03 14:41:13 -07004074 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4075 // thread associated with this PlaybackThread.
4076 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4077 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004078 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4079 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004080 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004081 const char *logString = NULL;
4082
rago1bb90822017-05-02 18:31:48 -07004083 // Estimated time for next buffer to be written to hal. This is used only on
4084 // suspended mode (for now) to help schedule the wait time until next iteration.
4085 nsecs_t timeLoopNextNs = 0;
4086
Eric Laurent664539d2013-09-23 18:24:31 -07004087 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004088
Andy Hung2dbffc22018-08-08 18:50:41 -07004089 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004090
Eric Laurentb3f315a2021-07-13 15:09:05 +02004091 sendCheckOutputStageEffectsEvent();
4092
Andy Hung446f4df2019-02-21 12:26:41 -08004093 // loopCount is used for statistics and diagnostics.
4094 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004095 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004096 // Log merge requests are performed during AudioFlinger binder transactions, but
4097 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004098 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004099
Eric Laurent81784c32012-11-19 14:55:58 -08004100 cpuStats.sample(myName);
4101
Andy Hung116bc262023-06-20 18:56:17 -07004102 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004103 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004104 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004105 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004106
Andy Hung2dbffc22018-08-08 18:50:41 -07004107 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4108 //
Andy Hungc5007f82023-08-29 14:26:09 -07004109 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004110 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004111 // Here, we try for the AF lock, but do not block on it as the latency
4112 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004113 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004114 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004115 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004116 status_t status = INVALID_OPERATION;
4117 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004118 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004119 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004120 && swPatches.size() > 0) {
4121 status = swPatches[0].getLatencyMs_l(&latencyMs);
4122 downstreamPatchHandle = swPatches[0].getPatchHandle();
4123 }
4124 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004125 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004126 lastDownstreamPatchHandle = downstreamPatchHandle;
4127 }
4128 if (status == OK) {
4129 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004130 // latency of 5 seconds).
4131 const double minLatency = 0., maxLatency = 5000.;
4132 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004133 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004134 } else {
4135 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004136 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004137 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004138 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004139 }
Andy Hung583043b2023-07-17 17:05:00 -07004140 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004141 }
4142 } else {
4143 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4144 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004145 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004146 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4147 }
4148 }
4149
Eric Laurentb3f315a2021-07-13 15:09:05 +02004150 if (mCheckOutputStageEffects.exchange(false)) {
4151 checkOutputStageEffects();
4152 }
4153
Vlad Popa7e81cea2023-01-19 16:34:16 +01004154 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004155 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004156
Andy Hungc5007f82023-08-29 14:26:09 -07004157 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004158
Eric Laurent021cf962014-05-13 10:18:14 -07004159 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004160 if (mCheckOutputStageEffects.load()) {
4161 continue;
4162 }
Eric Laurent10351942014-05-08 18:49:52 -07004163
Andy Hungc5007f82023-08-29 14:26:09 -07004164 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004165 if (logString != NULL) {
4166 mNBLogWriter->logTimestamp();
4167 mNBLogWriter->log(logString);
4168 logString = NULL;
4169 }
4170
Dean Wheatley12473e92021-03-18 23:00:55 +11004171 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004172
Eric Laurent81784c32012-11-19 14:55:58 -08004173 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174 if (mSignalPending) {
4175 // A signal was raised while we were unlocked
4176 mSignalPending = false;
4177 } else if (waitingAsyncCallback_l()) {
4178 if (exitPending()) {
4179 break;
4180 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004181 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004182 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004183 releaseWakeLock_l();
4184 released = true;
4185 }
Andy Hung10cbff12017-02-21 17:30:14 -08004186
4187 const int64_t waitNs = computeWaitTimeNs_l();
4188 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004189 std::cv_status cvstatus =
4190 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4191 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004192 mSignalPending = true; // if timeout recheck everything
4193 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004194 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004195 if (released) {
4196 acquireWakeLock_l();
4197 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004198 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4199 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004200
4201 continue;
4202 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004203 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004204 isSuspended()) {
4205 // put audio hardware into standby after short delay
4206 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004207
4208 threadLoop_standby();
4209
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004210 // This is where we go into standby
4211 if (!mStandby) {
4212 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004213 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004214 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004215 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004216 }
Andy Hungd0979812019-02-21 15:51:44 -08004217 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004218 }
4219
Eric Tan39ec8d62018-07-24 09:49:29 -07004220 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004221 // we're about to wait, flush the binder command buffer
4222 IPCThreadState::self()->flushCommands();
4223
4224 clearOutputTracks();
4225
4226 if (exitPending()) {
4227 break;
4228 }
4229
4230 releaseWakeLock_l();
4231 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004232 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004233 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004234 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004235 acquireWakeLock_l();
4236
4237 mMixerStatus = MIXER_IDLE;
4238 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4239 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004240 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004241 checkSilentMode_l();
4242
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004243 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4244 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004245 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004246 sleepTimeShift = 0;
4247 }
4248
4249 continue;
4250 }
4251 }
Eric Laurent81784c32012-11-19 14:55:58 -08004252 // mMixerStatusIgnoringFastTracks is also updated internally
4253 mMixerStatus = prepareTracks_l(&tracksToRemove);
4254
Andy Hungab65b182023-09-06 19:41:47 -07004255 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004256
Vlad Popa7e81cea2023-01-19 16:34:16 +01004257 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004258
Andy Hungf302e812024-01-26 11:55:15 -08004259 // Acquire a local copy of active tracks with lock (release w/o lock).
4260 //
4261 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4262 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4263 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4264 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4265
4266 setHalLatencyMode_l();
4267
4268 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4269 // so this is done before we lock our effect chains.
4270 for (const auto& track : mActiveTracks) {
4271 track->updateTeePatches_l();
4272 }
4273
4274 // signal actual start of output stream when the render position reported by
4275 // the kernel starts moving.
4276 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4277 && (mKernelPositionOnStandby
4278 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4279 mHalStarted = true;
4280 mWaitHalStartCV.notify_all();
4281 }
4282
Eric Laurent81784c32012-11-19 14:55:58 -08004283 // prevent any changes in effect chain list and in each effect chain
4284 // during mixing and effect process as the audio buffers could be deleted
4285 // or modified if an effect is created or deleted
4286 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004287
4288 // Determine which session to pick up haptic data.
4289 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004290 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004291 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004292 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004293 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004294 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004295 if (effectChain != nullptr
4296 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004297 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004298 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004299 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004300 break;
4301 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004302 if (activeHapticSessionId == AUDIO_SESSION_NONE
4303 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004304 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004305 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004306 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004307 }
4308 }
4309 }
Andy Hungc5007f82023-08-29 14:26:09 -07004310 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004311
Eric Laurentbfb1b832013-01-07 09:53:42 -08004312 if (mBytesRemaining == 0) {
4313 mCurrentWriteLength = 0;
4314 if (mMixerStatus == MIXER_TRACKS_READY) {
4315 // threadLoop_mix() sets mCurrentWriteLength
4316 threadLoop_mix();
4317 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4318 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004319 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004320 // must be written to HAL
4321 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004322 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004323 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004324
4325 // Tally underrun frames as we are inserting 0s here.
4326 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004327 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004328 && !track->isStopped()
4329 && !track->isPaused()
4330 && !track->isTerminated()) {
4331 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4332 __func__, track->id(), track->getTrackStateAsString(),
4333 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004334 track->audioTrackServerProxy()->tallyUnderrunFrames(
4335 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004336 }
4337 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004338 }
4339 }
Andy Hung98ef9782014-03-04 14:46:50 -08004340 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004341 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004342 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004343 // or mSinkBuffer (if there are no effects and there is no data already copied to
4344 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004345 //
4346 // This is done pre-effects computation; if effects change to
4347 // support higher precision, this needs to move.
4348 //
4349 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004350 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004351 uint32_t mixerChannelCount = mEffectBufferValid ?
4352 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004353 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004354 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4355 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4356
David Li88ee0902022-06-22 10:01:21 +08004357 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4358 // do these processes after effects are applied.
4359 if (!mEffectBufferValid) {
4360 // mono blend occurs for mixer threads only (not direct or offloaded)
4361 // and is handled here if we're going directly to the sink.
4362 if (requireMonoBlend()) {
4363 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4364 mNormalFrameCount, true /*limit*/);
4365 }
Andy Hung2ddee192015-12-18 17:34:44 -08004366
David Li88ee0902022-06-22 10:01:21 +08004367 if (!hasFastMixer()) {
4368 // Balance must take effect after mono conversion.
4369 // We do it here if there is no FastMixer.
4370 // mBalance detects zero balance within the class for speed
4371 // (not needed here).
4372 mBalance.setBalance(mMasterBalance.load());
4373 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4374 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004375 }
4376
Andy Hung98ef9782014-03-04 14:46:50 -08004377 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004378 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004379
4380 // If we're going directly to the sink and there are haptic channels,
4381 // we should adjust channels as the sample data is partially interleaved
4382 // in this case.
4383 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4384 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4385 mChannelCount + mHapticChannelCount,
4386 audio_bytes_per_sample(format),
4387 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4388 }
Andy Hung98ef9782014-03-04 14:46:50 -08004389 }
4390
Eric Laurentbfb1b832013-01-07 09:53:42 -08004391 mBytesRemaining = mCurrentWriteLength;
4392 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004393 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4394 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4395 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4396 mBytesWritten += mBytesRemaining;
4397 mFramesWritten += framesRemaining;
4398 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004399 mBytesRemaining = 0;
4400 }
Eric Laurent81784c32012-11-19 14:55:58 -08004401
Eric Laurentbfb1b832013-01-07 09:53:42 -08004402 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004403 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 for (size_t i = 0; i < effectChains.size(); i ++) {
4405 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004406 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004407 if (activeHapticSessionId != AUDIO_SESSION_NONE
4408 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004409 // Haptic data is active in this case, copy it directly from
4410 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004411 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4412 audio_channel_count_from_out_mask(mMixerChannelMask) :
4413 mChannelCount;
4414 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4415 hapticSessionChannelCount = mChannelCount;
4416 }
4417
jiabin47affe52019-04-04 18:02:07 -07004418 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004419 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004420 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004421 memcpy_by_audio_format(
4422 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004423 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004424 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004425 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004426 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004427 }
Eric Laurent81784c32012-11-19 14:55:58 -08004428 }
4429 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004430 // Process effect chains for offloaded thread even if no audio
4431 // was read from audio track: process only updates effect state
4432 // and thus does have to be synchronized with audio writes but may have
4433 // to be called while waiting for async write callback
4434 if (mType == OFFLOAD) {
4435 for (size_t i = 0; i < effectChains.size(); i ++) {
4436 effectChains[i]->process_l();
4437 }
4438 }
Eric Laurent81784c32012-11-19 14:55:58 -08004439
Andy Hung98ef9782014-03-04 14:46:50 -08004440 // Only if the Effects buffer is enabled and there is data in the
4441 // Effects buffer (buffer valid), we need to
4442 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004443 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004444 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004445 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004446 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004447 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004448 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004449 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004450 }
4451
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004452 if (!hasFastMixer()) {
4453 // Balance must take effect after mono conversion.
4454 // We do it here if there is no FastMixer.
4455 // mBalance detects zero balance within the class for speed (not needed here).
4456 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004457 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004458 }
4459
Eric Laurentb62d0362021-10-26 17:40:18 +02004460 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4461 // mPostSpatializerBuffer if the haptics track is spatialized.
4462 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4463 // For other thread types, the haptics channels are already in mEffectBuffer.
4464 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4465 const size_t srcBufferSize = mNormalFrameCount *
4466 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4467 mEffectBufferFormat);
4468 const size_t dstBufferSize = mNormalFrameCount
4469 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4470
4471 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4472 mEffectBufferFormat,
4473 (uint8_t*)mEffectBuffer + srcBufferSize,
4474 mEffectBufferFormat,
4475 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004476 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004477 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4478 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4479 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4480 // Clamp PCM float values more than this distance from 0 to insulate
4481 // a HAL which doesn't handle NaN correctly.
4482 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4483 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4484 static_cast<const float*>(effectBuffer),
4485 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4486 } else {
4487 memcpy_by_audio_format(mSinkBuffer, mFormat,
4488 effectBuffer, mEffectBufferFormat, framesToCopy);
4489 }
jiabin245cdd92018-12-07 17:55:15 -08004490 // The sample data is partially interleaved when haptic channels exist,
4491 // we need to adjust channels here.
4492 if (mHapticChannelCount > 0) {
4493 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4494 mChannelCount + mHapticChannelCount,
4495 audio_bytes_per_sample(mFormat),
4496 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4497 }
Andy Hung98ef9782014-03-04 14:46:50 -08004498 }
4499
Eric Laurent81784c32012-11-19 14:55:58 -08004500 // enable changes in effect chain
4501 unlockEffectChains(effectChains);
4502
Vlad Popafce10862023-02-03 10:37:07 +01004503 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004504 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004505 metadataUpdate.playbackMetadataUpdate);
4506 }
4507
Eric Laurentbfb1b832013-01-07 09:53:42 -08004508 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004509 // mSleepTimeUs == 0 means we must write to audio hardware
4510 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004511 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004512 // writePeriodNs is updated >= 0 when ret > 0.
4513 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004514 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004515 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004516 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004517 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004518 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004519 if (ret < 0) {
4520 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004521 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 mBytesWritten += ret;
4523 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004524 const int64_t frames = ret / mFrameSize;
4525 mFramesWritten += frames;
4526
4527 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4528 // process information relating to write time.
4529 if (audio_has_proportional_frames(mFormat)) {
4530 // we are in a continuous mixing cycle
4531 if (mMixerStatus == MIXER_TRACKS_READY &&
4532 loopCount == lastLoopCountWritten + 1) {
4533
4534 const double jitterMs =
4535 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4536 {frames, writePeriodNs},
4537 {0, 0} /* lastTimestamp */, mSampleRate);
4538 const double processMs =
4539 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4540
Andy Hung972bec12023-08-31 16:13:39 -07004541 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004542 mIoJitterMs.add(jitterMs);
4543 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004544
4545 if (mPipeSink.get() != nullptr) {
4546 // Using the Monopipe availableToWrite, we estimate the current
4547 // buffer size.
4548 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4549 const ssize_t
4550 availableToWrite = mPipeSink->availableToWrite();
4551 const size_t pipeFrames = monoPipe->maxFrames();
4552 const size_t
4553 remainingFrames = pipeFrames - max(availableToWrite, 0);
4554 mMonopipePipeDepthStats.add(remainingFrames);
4555 }
Andy Hung446f4df2019-02-21 12:26:41 -08004556 }
4557
4558 // write blocked detection
4559 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004560 if ((mType == MIXER || mType == SPATIALIZER)
4561 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004562 mNumDelayedWrites++;
4563 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4564 ATRACE_NAME("underrun");
4565 ALOGW("write blocked for %lld msecs, "
4566 "%d delayed writes, thread %d",
4567 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4568 mNumDelayedWrites, mId);
4569 lastWarning = lastIoEndNs;
4570 }
4571 }
4572 }
4573 // update timing info.
4574 mLastIoBeginNs = lastIoBeginNs;
4575 mLastIoEndNs = lastIoEndNs;
4576 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004577 }
4578 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4579 (mMixerStatus == MIXER_DRAIN_ALL)) {
4580 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004581 }
Andy Hungd3639922022-04-28 18:00:49 -07004582 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004583
4584 if (mThreadThrottle
4585 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004586 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004587 // Limit MixerThread data processing to no more than twice the
4588 // expected processing rate.
4589 //
4590 // This helps prevent underruns with NuPlayer and other applications
4591 // which may set up buffers that are close to the minimum size, or use
4592 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4593 //
4594 // The throttle smooths out sudden large data drains from the device,
4595 // e.g. when it comes out of standby, which often causes problems with
4596 // (1) mixer threads without a fast mixer (which has its own warm-up)
4597 // (2) minimum buffer sized tracks (even if the track is full,
4598 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004599 //
4600 // Total time spent in last processing cycle equals time spent in
4601 // 1. threadLoop_write, as well as time spent in
4602 // 2. threadLoop_mix (significant for heavy mixing, especially
4603 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004604
Andy Hung446f4df2019-02-21 12:26:41 -08004605 // it's OK if deltaMs is an overestimate.
4606
4607 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004608
Ivan Lozanoea04d392017-11-07 14:37:07 -08004609 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004610 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004611 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004612
Andy Hung08fb1742015-05-31 23:22:10 -07004613 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004614 // notify of throttle start on verbose log
4615 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4616 "mixer(%p) throttle begin:"
4617 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004618 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004619 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004620 // Throttle must be attributed to the previous mixer loop's write time
4621 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004622 // This also ensures proper timing statistics.
4623 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004624 } else {
4625 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4626 if (diff > 0) {
4627 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004628 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004629 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004630 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004631 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004632 outDeviceTypes_l(),
4633 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004634 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004635 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4636 }
Andy Hung08fb1742015-05-31 23:22:10 -07004637 }
4638 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004639 }
Eric Laurent81784c32012-11-19 14:55:58 -08004640
Eric Laurentbfb1b832013-01-07 09:53:42 -08004641 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004642 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004643 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004644 // suspended requires accurate metering of sleep time.
4645 if (isSuspended()) {
4646 // advance by expected sleepTime
4647 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4648 const nsecs_t nowNs = systemTime();
4649
4650 // compute expected next time vs current time.
4651 // (negative deltas are treated as delays).
4652 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4653 if (deltaNs < -kMaxNextBufferDelayNs) {
4654 // Delays longer than the max allowed trigger a reset.
4655 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4656 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4657 timeLoopNextNs = nowNs + deltaNs;
4658 } else if (deltaNs < 0) {
4659 // Delays within the max delay allowed: zero the delta/sleepTime
4660 // to help the system catch up in the next iteration(s)
4661 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4662 deltaNs = 0;
4663 }
4664 // update sleep time (which is >= 0)
4665 mSleepTimeUs = deltaNs / 1000;
4666 }
Eric Laurente93cc032016-05-05 10:15:10 -07004667 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004668 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004669 }
Glenn Kastene7754022014-10-31 12:11:26 -07004670 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671 }
Eric Laurent81784c32012-11-19 14:55:58 -08004672 }
4673
4674 // Finally let go of removed track(s), without the lock held
4675 // since we can't guarantee the destructors won't acquire that
4676 // same lock. This will also mutate and push a new fast mixer state.
4677 threadLoop_removeTracks(tracksToRemove);
4678 tracksToRemove.clear();
4679
4680 // FIXME I don't understand the need for this here;
4681 // it was in the original code but maybe the
4682 // assignment in saveOutputTracks() makes this unnecessary?
4683 clearOutputTracks();
4684
4685 // Effect chains will be actually deleted here if they were removed from
4686 // mEffectChains list during mixing or effects processing
4687 effectChains.clear();
4688
4689 // FIXME Note that the above .clear() is no longer necessary since effectChains
4690 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004691
4692 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004693 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004694 mThreadloopExecutor.process(); // process any remaining deferred actions.
4695 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004696
Eric Laurentbfb1b832013-01-07 09:53:42 -08004697 threadLoop_exit();
4698
Eric Laurentcf817a22014-08-04 20:36:31 -07004699 if (!mStandby) {
4700 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004701 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004702 }
4703
4704 releaseWakeLock();
4705
4706 ALOGV("Thread %p type %d exiting", this, mType);
4707 return false;
4708}
4709
Andy Hungee58e4a2023-07-07 13:47:37 -07004710void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004711{
Dean Wheatley12473e92021-03-18 23:00:55 +11004712 if (mStandby) {
4713 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4714 return;
4715 } else if (mHwPaused) {
4716 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4717 return;
4718 }
4719
4720 // Gather the framesReleased counters for all active tracks,
4721 // and associate with the sink frames written out. We need
4722 // this to convert the sink timestamp to the track timestamp.
4723 bool kernelLocationUpdate = false;
4724 ExtendedTimestamp timestamp; // use private copy to fetch
4725
4726 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4727 // HAL may be draining some small duration buffered data for fade out.
4728 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4729 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4730 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4731 mSampleRate);
4732
Andy Hungab65b182023-09-06 19:41:47 -07004733 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004734 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4735 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4736 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4737 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4738 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4739 = correctedTimestamp.mFrames;
4740 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4741 = correctedTimestamp.mTimeNs;
4742 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4743 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4744 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4745
4746 // Note: Downstream latency only added if timestamp correction enabled.
4747 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4748 const int64_t newPosition =
4749 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4750 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4751 // prevent retrograde
4752 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4753 newPosition,
4754 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4755 - mSuspendedFrames));
4756 }
4757 }
4758
4759 // We always fetch the timestamp here because often the downstream
4760 // sink will block while writing.
4761
4762 // We keep track of the last valid kernel position in case we are in underrun
4763 // and the normal mixer period is the same as the fast mixer period, or there
4764 // is some error from the HAL.
4765 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4766 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4767 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4768 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4769 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4770
4771 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4772 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4773 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4774 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4775 }
4776
4777 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4778 kernelLocationUpdate = true;
4779 } else {
4780 ALOGVV("getTimestamp error - no valid kernel position");
4781 }
4782
4783 // copy over kernel info
4784 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4785 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4786 + mSuspendedFrames; // add frames discarded when suspended
4787 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4788 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4789 } else {
4790 mTimestampVerifier.error();
4791 }
4792
4793 // mFramesWritten for non-offloaded tracks are contiguous
4794 // even after standby() is called. This is useful for the track frame
4795 // to sink frame mapping.
4796 bool serverLocationUpdate = false;
4797 if (mFramesWritten != mLastFramesWritten) {
4798 serverLocationUpdate = true;
4799 mLastFramesWritten = mFramesWritten;
4800 }
4801 // Only update timestamps if there is a meaningful change.
4802 // Either the kernel timestamp must be valid or we have written something.
4803 if (kernelLocationUpdate || serverLocationUpdate) {
4804 if (serverLocationUpdate) {
4805 // use the time before we called the HAL write - it is a bit more accurate
4806 // to when the server last read data than the current time here.
4807 //
4808 // If we haven't written anything, mLastIoBeginNs will be -1
4809 // and we use systemTime().
4810 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4811 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004812 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004813 }
4814
Andy Hung8d31fd22023-06-26 19:20:57 -07004815 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004816 if (!t->isFastTrack()) {
4817 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004818 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004819 mFramesWritten,
4820 mSampleRate,
4821 mTimestamp);
4822 }
4823 }
4824 }
4825
4826 if (audio_has_proportional_frames(mFormat)) {
4827 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4828 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4829 mLatencyMs.add(latencyMs);
4830 }
4831 }
4832#if 0
4833 // logFormat example
4834 if (z % 100 == 0) {
4835 timespec ts;
4836 clock_gettime(CLOCK_MONOTONIC, &ts);
4837 LOGT("This is an integer %d, this is a float %f, this is my "
4838 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4839 LOGT("A deceptive null-terminated string %\0");
4840 }
4841 ++z;
4842#endif
4843}
4844
Andy Hungc5007f82023-08-29 14:26:09 -07004845// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004846void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004847NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004848{
Andy Hung6c498e92023-12-05 17:28:17 -08004849 if (tracksToRemove.empty()) return;
4850
4851 // Block all incoming TrackHandle requests until we are finished with the release.
4852 setThreadBusy_l(true);
4853
Andy Hungfe726a62018-09-27 15:17:25 -07004854 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004855 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004856 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004857 if (chain != 0) {
4858 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4859 __func__, track->id(), chain.get(), track->sessionId());
4860 chain->decActiveTrackCnt();
4861 }
Andy Hung6c498e92023-12-05 17:28:17 -08004862
Andy Hungfe726a62018-09-27 15:17:25 -07004863 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004864 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004865 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004866 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004867 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004868 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004869 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004870 }
Andy Hung6c498e92023-12-05 17:28:17 -08004871 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004872 }
jiabineb3bda02020-06-30 14:07:03 -07004873 if (mHapticChannelCount > 0 &&
4874 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004875 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004876 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004877 // Unlock due to VibratorService will lock for this call and will
4878 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004879 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004880 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004881
4882 // When the track is stop, set the haptic intensity as MUTE
4883 // for the HapticGenerator effect.
4884 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004885 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004886 }
jiabin245cdd92018-12-07 17:55:15 -08004887 }
Andy Hung6c498e92023-12-05 17:28:17 -08004888
4889 // Under lock, the track is removed from the active tracks list.
4890 //
4891 // Once the track is no longer active, the TrackHandle may directly
4892 // modify it as the threadLoop() is no longer responsible for its maintenance.
4893 // Do not modify the track from threadLoop after the mutex is unlocked
4894 // if it is not active.
4895 mActiveTracks.remove(track);
4896
4897 if (track->isTerminated()) {
4898 // remove from our tracks vector
4899 removeTrack_l(track);
4900 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004901 }
Andy Hung6c498e92023-12-05 17:28:17 -08004902
4903 // Allow incoming TrackHandle requests. We still hold the mutex,
4904 // so pending TrackHandle requests will occur after we unlock it.
4905 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004906}
Eric Laurent81784c32012-11-19 14:55:58 -08004907
Andy Hungee58e4a2023-07-07 13:47:37 -07004908status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004909{
4910 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004911 ExtendedTimestamp ets;
4912 status_t status = mNormalSink->getTimestamp(ets);
4913 if (status == NO_ERROR) {
4914 status = ets.getBestTimestamp(&timestamp);
4915 }
4916 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004917 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004918 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004919 collectTimestamps_l();
4920 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4921 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004922 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004923 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4924 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4925 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4926 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4927 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004928 }
4929 return INVALID_OPERATION;
4930}
Eric Laurent1c333e22014-05-20 10:48:17 -07004931
Eric Laurenteab90452019-06-24 15:17:46 -07004932// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4933// still applied by the mixer.
4934// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4935// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4936// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004937status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004938{
4939 status_t result = NO_ERROR;
4940 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4941 if (*volume != mLeftVolFloat) {
4942 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004943 // HAL can return INVALID_OPERATION if operation is not supported.
4944 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004945 "Error when setting output stream volume: %d", result);
4946 if (result == NO_ERROR) {
4947 mLeftVolFloat = *volume;
4948 }
4949 }
4950 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4951 // remove stream volume contribution from software volume.
4952 if (mLeftVolFloat == *volume) {
4953 *volume = 1.0f;
4954 }
4955 }
4956 return result;
4957}
4958
Andy Hungee58e4a2023-07-07 13:47:37 -07004959status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004960 audio_patch_handle_t *handle)
4961{
Andy Hungf60abce2016-08-26 11:37:54 -07004962 status_t status;
4963 if (property_get_bool("af.patch_park", false /* default_value */)) {
4964 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4965 // or if HAL does not properly lock against access.
4966 AutoPark<FastMixer> park(mFastMixer);
4967 status = PlaybackThread::createAudioPatch_l(patch, handle);
4968 } else {
4969 status = PlaybackThread::createAudioPatch_l(patch, handle);
4970 }
Eric Laurentb0463942022-12-20 16:31:10 +01004971
4972 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004973 return status;
4974}
4975
Andy Hungee58e4a2023-07-07 13:47:37 -07004976status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004977 audio_patch_handle_t *handle)
4978{
4979 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004980
4981 // store new device and send to effects
4982 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004983 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004984 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004985 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4986 && !mOutput->audioHwDev->supportsAudioPatches(),
4987 "Enumerated device type(%#x) must not be used "
4988 "as it does not support audio patches",
4989 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004990 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004991 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4992 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004993 }
4994
François Gaffie0c280aa2018-07-25 10:02:15 +02004995 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004996#ifdef ADD_BATTERY_DATA
4997 // when changing the audio output device, call addBatteryData to notify
4998 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004999 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005000 uint32_t params = 0;
5001 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07005002 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005003 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07005004 }
5005
Eric Laurent054d9d32015-04-24 08:48:48 -07005006 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07005007 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005008 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5009 }
5010
5011 if (params != 0) {
5012 addBatteryData(params);
5013 }
5014 }
5015#endif
5016
5017 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08005018 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005019 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005020
jiabinc52b1ff2019-10-31 17:20:42 -07005021 // mPatch.num_sinks is not set when the thread is created so that
5022 // the first patch creation triggers an ioConfigChanged callback
5023 bool configChanged = (mPatch.num_sinks == 0) ||
5024 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005025 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005026 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005027 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005028
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005029 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005030 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5031 status = hwDevice->createAudioPatch(patch->num_sources,
5032 patch->sources,
5033 patch->num_sinks,
5034 patch->sinks,
5035 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005036 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005037 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005038 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005039 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005040 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005041
5042 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005043 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005044 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005045 // also dispatch to active AudioTracks for MediaMetrics
5046 for (const auto &track : mActiveTracks) {
5047 track->logEndInterval();
5048 track->logBeginInterval(patchSinksAsString);
5049 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005050
Eric Laurente8726fe2015-06-26 09:39:24 -07005051 if (configChanged) {
5052 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5053 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005054 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005055 mActiveTracks.setHasChanged();
5056
Eric Laurent1c333e22014-05-20 10:48:17 -07005057 return status;
5058}
5059
Andy Hungee58e4a2023-07-07 13:47:37 -07005060status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005061{
Andy Hungf60abce2016-08-26 11:37:54 -07005062 status_t status;
5063 if (property_get_bool("af.patch_park", false /* default_value */)) {
5064 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5065 // or if HAL does not properly lock against access.
5066 AutoPark<FastMixer> park(mFastMixer);
5067 status = PlaybackThread::releaseAudioPatch_l(handle);
5068 } else {
5069 status = PlaybackThread::releaseAudioPatch_l(handle);
5070 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005071 return status;
5072}
5073
Andy Hungee58e4a2023-07-07 13:47:37 -07005074status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005075{
5076 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005077
jiabinc52b1ff2019-10-31 17:20:42 -07005078 mPatch = audio_patch{};
5079 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005080
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005081 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005082 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5083 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005084 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005085 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005086 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005087 // Force meteadata update after a route change
5088 mActiveTracks.setHasChanged();
5089
Eric Laurent1c333e22014-05-20 10:48:17 -07005090 return status;
5091}
5092
Andy Hungee58e4a2023-07-07 13:47:37 -07005093void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005094{
Andy Hung972bec12023-08-31 16:13:39 -07005095 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005096 mTracks.add(track);
5097}
5098
Andy Hungee58e4a2023-07-07 13:47:37 -07005099void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005100{
Andy Hung972bec12023-08-31 16:13:39 -07005101 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005102 destroyTrack_l(track);
5103}
5104
Andy Hungee58e4a2023-07-07 13:47:37 -07005105void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005106{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005107 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005108 config->role = AUDIO_PORT_ROLE_SOURCE;
5109 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5110 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005111 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5112 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5113 config->flags.output = mOutput->flags;
5114 }
Eric Laurent83b88082014-06-20 18:31:16 -07005115}
5116
Eric Laurent81784c32012-11-19 14:55:58 -08005117// ----------------------------------------------------------------------------
5118
Andy Hungee58e4a2023-07-07 13:47:37 -07005119/* static */
5120sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005121 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005122 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005123 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005124}
5125
Andy Hung583043b2023-07-17 17:05:00 -07005126MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005127 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005128 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005129 // mAudioMixer below
5130 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005131 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005132 mFastMixerFutex(0),
5133 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005134 // mOutputSink below
5135 // mPipeSink below
5136 // mNormalSink below
5137{
jiabinc52b1ff2019-10-31 17:20:42 -07005138 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005139 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005140 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005141 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5142 mNormalFrameCount);
5143 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5144
Andy Hungfbfc3952015-01-15 13:33:51 -08005145 if (type == DUPLICATING) {
5146 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5147 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5148 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005149 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5150 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005151 return;
5152 }
Eric Laurent81784c32012-11-19 14:55:58 -08005153 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005154 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005155 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005156 const NBAIO_Format offers[1] = {Format_from_SR_C(
5157 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005158#if !LOG_NDEBUG
5159 ssize_t index =
5160#else
5161 (void)
5162#endif
5163 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005164 ALOG_ASSERT(index == 0);
5165
5166 // initialize fast mixer depending on configuration
5167 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005168 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005169 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005170 } else {
5171 switch (kUseFastMixer) {
5172 case FastMixer_Never:
5173 initFastMixer = false;
5174 break;
5175 case FastMixer_Always:
5176 initFastMixer = true;
5177 break;
5178 case FastMixer_Static:
5179 case FastMixer_Dynamic:
5180 initFastMixer = mFrameCount < mNormalFrameCount;
5181 break;
5182 }
5183 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5184 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5185 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005186 }
5187 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005188 audio_format_t fastMixerFormat;
5189 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5190 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5191 } else {
5192 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5193 }
5194 if (mFormat != fastMixerFormat) {
5195 // change our Sink format to accept our intermediate precision
5196 mFormat = fastMixerFormat;
5197 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005198 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005199 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5200 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5201 }
Eric Laurent81784c32012-11-19 14:55:58 -08005202
5203 // create a MonoPipe to connect our submix to FastMixer
5204 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005205
Andy Hung1258c1a2014-05-23 21:22:17 -07005206 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005207 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005208 format.mFormat = fastMixerFormat;
5209 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5210
Eric Laurent81784c32012-11-19 14:55:58 -08005211 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5212 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5213 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5214 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005215 const NBAIO_Format offersFast[1] = {format};
5216 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005217#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005218 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005219#else
5220 (void)
5221#endif
Andy Hung920f6572022-10-06 12:09:49 -07005222 monoPipe->negotiate(offersFast, std::size(offersFast),
5223 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005224 ALOG_ASSERT(index == 0);
5225 monoPipe->setAvgFrames((mScreenState & 1) ?
5226 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5227 mPipeSink = monoPipe;
5228
Eric Laurent81784c32012-11-19 14:55:58 -08005229 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005230 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005231 FastMixerStateQueue *sq = mFastMixer->sq();
5232#ifdef STATE_QUEUE_DUMP
5233 sq->setObserverDump(&mStateQueueObserverDump);
5234 sq->setMutatorDump(&mStateQueueMutatorDump);
5235#endif
5236 FastMixerState *state = sq->begin();
5237 FastTrack *fastTrack = &state->mFastTracks[0];
5238 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5239 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5240 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005241 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5242 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5243 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005244 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005245 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005246 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005247 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005248 fastTrack->mGeneration++;
5249 state->mFastTracksGen++;
5250 state->mTrackMask = 1;
5251 // fast mixer will use the HAL output sink
5252 state->mOutputSink = mOutputSink.get();
5253 state->mOutputSinkGen++;
5254 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005255 // specify sink channel mask when haptic channel mask present as it can not
5256 // be calculated directly from channel count
5257 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005258 ? AUDIO_CHANNEL_NONE
5259 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005260 state->mCommand = FastMixerState::COLD_IDLE;
5261 // already done in constructor initialization list
5262 //mFastMixerFutex = 0;
5263 state->mColdFutexAddr = &mFastMixerFutex;
5264 state->mColdGen++;
5265 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005266 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005267 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005268 sq->end();
5269 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5270
Eric Tan0513b5d2018-09-17 10:32:48 -07005271 NBLog::thread_info_t info;
5272 info.id = mId;
5273 info.type = NBLog::FASTMIXER;
5274 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5275
Eric Laurent81784c32012-11-19 14:55:58 -08005276 // start the fast mixer
5277 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5278 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005279 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005280 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005281
5282#ifdef AUDIO_WATCHDOG
5283 // create and start the watchdog
5284 mAudioWatchdog = new AudioWatchdog();
5285 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5286 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5287 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005288 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005289#endif
Andy Hung8946a282018-04-19 20:04:56 -07005290 } else {
5291#ifdef TEE_SINK
5292 // Only use the MixerThread tee if there is no FastMixer.
5293 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5294 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5295#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005296 }
5297
5298 switch (kUseFastMixer) {
5299 case FastMixer_Never:
5300 case FastMixer_Dynamic:
5301 mNormalSink = mOutputSink;
5302 break;
5303 case FastMixer_Always:
5304 mNormalSink = mPipeSink;
5305 break;
5306 case FastMixer_Static:
5307 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5308 break;
5309 }
Andy Hung922617c2024-06-25 17:07:58 -07005310 // setMasterBalance needs to be called after the FastMixer
5311 // (if any) is set up, in order to deliver the balance settings to it.
5312 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005313}
5314
Andy Hungee58e4a2023-07-07 13:47:37 -07005315MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005316{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005317 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005318 FastMixerStateQueue *sq = mFastMixer->sq();
5319 FastMixerState *state = sq->begin();
5320 if (state->mCommand == FastMixerState::COLD_IDLE) {
5321 int32_t old = android_atomic_inc(&mFastMixerFutex);
5322 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005323 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005324 }
5325 }
5326 state->mCommand = FastMixerState::EXIT;
5327 sq->end();
5328 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5329 mFastMixer->join();
5330 // Though the fast mixer thread has exited, it's state queue is still valid.
5331 // We'll use that extract the final state which contains one remaining fast track
5332 // corresponding to our sub-mix.
5333 state = sq->begin();
5334 ALOG_ASSERT(state->mTrackMask == 1);
5335 FastTrack *fastTrack = &state->mFastTracks[0];
5336 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5337 delete fastTrack->mBufferProvider;
5338 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005339 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005340#ifdef AUDIO_WATCHDOG
5341 if (mAudioWatchdog != 0) {
5342 mAudioWatchdog->requestExit();
5343 mAudioWatchdog->requestExitAndWait();
5344 mAudioWatchdog.clear();
5345 }
5346#endif
5347 }
Andy Hung583043b2023-07-17 17:05:00 -07005348 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005349 delete mAudioMixer;
5350}
5351
Andy Hungee58e4a2023-07-07 13:47:37 -07005352void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005353 PlaybackThread::onFirstRef();
5354
Andy Hung972bec12023-08-31 16:13:39 -07005355 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005356 if (mOutput != nullptr && mOutput->stream != nullptr) {
5357 status_t status = mOutput->stream->setLatencyModeCallback(this);
5358 if (status != INVALID_OPERATION) {
5359 updateHalSupportedLatencyModes_l();
5360 }
5361 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5362 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5363 mBluetoothLatencyModesEnabled.store(
5364 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5365 }
5366}
Eric Laurent81784c32012-11-19 14:55:58 -08005367
Andy Hungee58e4a2023-07-07 13:47:37 -07005368uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005369{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005370 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005371 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5372 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5373 }
5374 return latency;
5375}
5376
Andy Hungee58e4a2023-07-07 13:47:37 -07005377ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005378{
5379 // FIXME we should only do one push per cycle; confirm this is true
5380 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005381 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005382 FastMixerStateQueue *sq = mFastMixer->sq();
5383 FastMixerState *state = sq->begin();
5384 if (state->mCommand != FastMixerState::MIX_WRITE &&
5385 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5386 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005387
5388 // FIXME workaround for first HAL write being CPU bound on some devices
5389 ATRACE_BEGIN("write");
5390 mOutput->write((char *)mSinkBuffer, 0);
5391 ATRACE_END();
5392
Eric Laurent81784c32012-11-19 14:55:58 -08005393 int32_t old = android_atomic_inc(&mFastMixerFutex);
5394 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005395 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005396 }
5397#ifdef AUDIO_WATCHDOG
5398 if (mAudioWatchdog != 0) {
5399 mAudioWatchdog->resume();
5400 }
5401#endif
5402 }
5403 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005404#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005405 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005406 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005407#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005408 sq->end();
5409 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5410 if (kUseFastMixer == FastMixer_Dynamic) {
5411 mNormalSink = mPipeSink;
5412 }
5413 } else {
5414 sq->end(false /*didModify*/);
5415 }
5416 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005417 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005418}
5419
Andy Hungee58e4a2023-07-07 13:47:37 -07005420void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005421{
5422 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005423 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005424 FastMixerStateQueue *sq = mFastMixer->sq();
5425 FastMixerState *state = sq->begin();
5426 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005427 // Report any frames trapped in the Monopipe
5428 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5429 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5430 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5431 "monoPipeWritten:%lld monoPipeLeft:%lld",
5432 (long long)mFramesWritten, (long long)mSuspendedFrames,
5433 (long long)mPipeSink->framesWritten(), pipeFrames);
5434 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5435
Eric Laurent81784c32012-11-19 14:55:58 -08005436 state->mCommand = FastMixerState::COLD_IDLE;
5437 state->mColdFutexAddr = &mFastMixerFutex;
5438 state->mColdGen++;
5439 mFastMixerFutex = 0;
5440 sq->end();
5441 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5442 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5443 if (kUseFastMixer == FastMixer_Dynamic) {
5444 mNormalSink = mOutputSink;
5445 }
5446#ifdef AUDIO_WATCHDOG
5447 if (mAudioWatchdog != 0) {
5448 mAudioWatchdog->pause();
5449 }
5450#endif
5451 } else {
5452 sq->end(false /*didModify*/);
5453 }
5454 }
5455 PlaybackThread::threadLoop_standby();
5456}
5457
Andy Hungee58e4a2023-07-07 13:47:37 -07005458bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005459{
5460 return false;
5461}
5462
Andy Hungee58e4a2023-07-07 13:47:37 -07005463bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005464{
5465 return !mStandby;
5466}
5467
Andy Hungee58e4a2023-07-07 13:47:37 -07005468bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005469{
Andy Hung972bec12023-08-31 16:13:39 -07005470 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005471 return waitingAsyncCallback_l();
5472}
5473
Eric Laurent81784c32012-11-19 14:55:58 -08005474// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005475void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005476{
Andy Hung8d672e02023-09-15 18:19:28 -07005477 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5478 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005479 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005480 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005481 // discard any pending drain or write ack by incrementing sequence
5482 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5483 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005484 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005485 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5486 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005487 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005488 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005489 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005490}
5491
Andy Hungee58e4a2023-07-07 13:47:37 -07005492void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005493{
5494 ALOGV("signal playback thread");
5495 broadcast_l();
5496}
5497
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005498void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005499{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005500 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005501 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5502 invalidateTracks((audio_stream_type_t)i);
5503 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005504 if (isHardError) {
5505 mAfThreadCallback->onHardError(allTrackPortIds);
5506 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005507}
5508
Andy Hungee58e4a2023-07-07 13:47:37 -07005509void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005510{
Eric Laurent81784c32012-11-19 14:55:58 -08005511 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005512 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005513 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005514 // increase sleep time progressively when application underrun condition clears.
5515 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5516 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5517 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005518 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005519 sleepTimeShift--;
5520 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005521 mSleepTimeUs = 0;
5522 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005523 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005524
Eric Laurent81784c32012-11-19 14:55:58 -08005525}
5526
Andy Hungee58e4a2023-07-07 13:47:37 -07005527void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005528{
5529 // If no tracks are ready, sleep once for the duration of an output
5530 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005531 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005532 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005533 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5534 // Using the Monopipe availableToWrite, we estimate the
5535 // sleep time to retry for more data (before we underrun).
5536 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5537 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5538 const size_t pipeFrames = monoPipe->maxFrames();
5539 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5540 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5541 const size_t framesDelay = std::min(
5542 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5543 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5544 pipeFrames, framesLeft, framesDelay);
5545 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5546 } else {
5547 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5548 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5549 mSleepTimeUs = kMinThreadSleepTimeUs;
5550 }
5551 // reduce sleep time in case of consecutive application underruns to avoid
5552 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5553 // duration we would end up writing less data than needed by the audio HAL if
5554 // the condition persists.
5555 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5556 sleepTimeShift++;
5557 }
Eric Laurent81784c32012-11-19 14:55:58 -08005558 }
5559 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005560 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005561 }
5562 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005563 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5564 // before effects processing or output.
5565 if (mMixerBufferValid) {
5566 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005567 if (mType == SPATIALIZER) {
5568 memset(mSinkBuffer, 0, mSinkBufferSize);
5569 }
Andy Hung98ef9782014-03-04 14:46:50 -08005570 } else {
5571 memset(mSinkBuffer, 0, mSinkBufferSize);
5572 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005573 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005574 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5575 "anticipated start");
5576 }
5577 // TODO add standby time extension fct of effect tail
5578}
5579
Andy Hungc5007f82023-08-29 14:26:09 -07005580// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005581PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005582 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005583{
Andy Hungc0691382018-09-12 18:01:57 -07005584 // clean up deleted track ids in AudioMixer before allocating new tracks
5585 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5586 // for each trackId, destroy it in the AudioMixer
5587 if (mAudioMixer->exists(trackId)) {
5588 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005589 }
5590 });
Andy Hungc0691382018-09-12 18:01:57 -07005591 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005592
5593 mixer_state mixerStatus = MIXER_IDLE;
5594 // find out which tracks need to be processed
5595 size_t count = mActiveTracks.size();
5596 size_t mixedTracks = 0;
5597 size_t tracksWithEffect = 0;
5598 // counts only _active_ fast tracks
5599 size_t fastTracks = 0;
5600 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5601
5602 float masterVolume = mMasterVolume;
5603 bool masterMute = mMasterMute;
5604
5605 if (masterMute) {
5606 masterVolume = 0;
5607 }
5608 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005609 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005610 if (chain != 0) {
5611 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005612 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005613 masterVolume = (float)((v + (1 << 23)) >> 24);
5614 chain.clear();
5615 }
5616
5617 // prepare a new state to push
5618 FastMixerStateQueue *sq = NULL;
5619 FastMixerState *state = NULL;
5620 bool didModify = false;
5621 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005622 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005623 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005624 sq = mFastMixer->sq();
5625 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005626 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005627 }
5628
Andy Hung69aed5f2014-02-25 17:24:40 -08005629 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005630 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005631
Andy Hungbd3b2b02018-05-21 10:53:11 -07005632 // DeferredOperations handles statistics after setting mixerStatus.
5633 class DeferredOperations {
5634 public:
Andy Hungea840382020-05-05 21:50:17 -07005635 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5636 : mMixerStatus(mixerStatus)
5637 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005638
5639 // when leaving scope, tally frames properly.
5640 ~DeferredOperations() {
5641 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5642 // because that is when the underrun occurs.
5643 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005644 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005645 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005646 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005647 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005648 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005649 }
5650 }
Andy Hungea840382020-05-05 21:50:17 -07005651 // send the max underrun frames for this mixer period
5652 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005653 }
5654
5655 // tallyUnderrunFrames() is called to update the track counters
5656 // with the number of underrun frames for a particular mixer period.
5657 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005658 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005659 mUnderrunFrames.emplace_back(track, underrunFrames);
5660 }
5661
5662 private:
5663 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005664 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005665 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005666 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005667 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005668
jiabin245cdd92018-12-07 17:55:15 -08005669 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005670 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005671 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005672
5673 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005674 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005675
5676 // process fast tracks
5677 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005678 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5679 "%s(%d): FastTrack(%d) present without FastMixer",
5680 __func__, id(), track->id());
5681
jiabin245cdd92018-12-07 17:55:15 -08005682 if (track->getHapticPlaybackEnabled()) {
5683 noFastHapticTrack = false;
5684 }
Eric Laurent81784c32012-11-19 14:55:58 -08005685
5686 // It's theoretically possible (though unlikely) for a fast track to be created
5687 // and then removed within the same normal mix cycle. This is not a problem, as
5688 // the track never becomes active so it's fast mixer slot is never touched.
5689 // The converse, of removing an (active) track and then creating a new track
5690 // at the identical fast mixer slot within the same normal mix cycle,
5691 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005692 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005693 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005694 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5695 FastTrack *fastTrack = &state->mFastTracks[j];
5696
5697 // Determine whether the track is currently in underrun condition,
5698 // and whether it had a recent underrun.
5699 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5700 FastTrackUnderruns underruns = ftDump->mUnderruns;
5701 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005702 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005703 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005704 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005705 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005706 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005707 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005708 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005709 // don't count underruns that occur while stopping or pausing
5710 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005711 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005712 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5713 recentUnderruns > 0) {
5714 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005715 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005716 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005717 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005718 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005719
5720 // This is similar to the state machine for normal tracks,
5721 // with a few modifications for fast tracks.
5722 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005723 switch (track->state()) {
5724 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005725 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005726 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005727 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005728 }
5729 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005730 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005731 // ramp down is not yet implemented
5732 track->setPaused();
5733 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005734 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005735 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005736 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005737 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005738 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005739 if (recentFull > 0 || recentPartial > 0) {
5740 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005741 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005742 }
5743 if (recentUnderruns == 0) {
5744 // no recent underruns: stay active
5745 break;
5746 }
5747 // there has recently been an underrun of some kind
5748 if (track->sharedBuffer() == 0) {
5749 // were any of the recent underruns "empty" (no frames available)?
5750 if (recentEmpty == 0) {
5751 // no, then ignore the partial underruns as they are allowed indefinitely
5752 break;
5753 }
5754 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005755 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005756 break;
5757 }
5758 // indicate to client process that the track was disabled because of underrun;
5759 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005760 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005761 // remove from active list, but state remains ACTIVE [confusing but true]
5762 isActive = false;
5763 break;
5764 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005765 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005766 case IAfTrackBase::STOPPING_2:
5767 case IAfTrackBase::PAUSED:
5768 case IAfTrackBase::STOPPED:
5769 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005770 // Check for presentation complete if track is inactive
5771 // We have consumed all the buffers of this track.
5772 // This would be incomplete if we auto-paused on underrun
5773 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005774 uint32_t latency = 0;
5775 status_t result = mOutput->stream->getLatency(&latency);
5776 ALOGE_IF(result != OK,
5777 "Error when retrieving output stream latency: %d", result);
5778 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005779 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005780 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5781 // track stays in active list until presentation is complete
5782 break;
5783 }
5784 }
5785 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005786 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005787 }
5788 if (track->isStopped()) {
5789 // Can't reset directly, as fast mixer is still polling this track
5790 // track->reset();
5791 // So instead mark this track as needing to be reset after push with ack
5792 resetMask |= 1 << i;
5793 }
5794 isActive = false;
5795 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005796 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005797 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005798 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005799 }
5800
5801 if (isActive) {
5802 // was it previously inactive?
5803 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005804 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5805 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005806 fastTrack->mBufferProvider = eabp;
5807 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005808 fastTrack->mChannelMask = track->channelMask();
5809 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005810 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005811 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005812 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005813 fastTrack->mGeneration++;
5814 state->mTrackMask |= 1 << j;
5815 didModify = true;
5816 // no acknowledgement required for newly active tracks
5817 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005818 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005819 float volume;
Andy Hung6b137d12024-08-27 22:35:17 +00005820 if (!audioserver_flags::portid_volume_management()) {
5821 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5822 volume = 0.f;
5823 } else {
5824 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5825 }
Eric Laurenteab90452019-06-24 15:17:46 -07005826 } else {
Andy Hung6b137d12024-08-27 22:35:17 +00005827 if (track->isPlaybackRestricted()) {
5828 volume = 0.f;
5829 } else {
5830 volume = masterVolume * track->getPortVolume();
5831 }
Eric Laurenteab90452019-06-24 15:17:46 -07005832 }
Eric Laurenteab90452019-06-24 15:17:46 -07005833 handleVoipVolume_l(&volume);
5834
Eric Laurent81784c32012-11-19 14:55:58 -08005835 // cache the combined master volume and stream type volume for fast mixer; this
5836 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005837 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005838 proxy->framesReleased()).first;
5839 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005840 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005841 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005842 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5843 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Andy Hung6b137d12024-08-27 22:35:17 +00005844 if (!audioserver_flags::portid_volume_management()) {
5845 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5846 /*muteState=*/{masterVolume == 0.f,
5847 mStreamTypes[track->streamType()].volume == 0.f,
5848 mStreamTypes[track->streamType()].mute,
5849 track->isPlaybackRestricted(),
5850 vlf == 0.f && vrf == 0.f,
5851 vh == 0.f});
5852 } else {
5853 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5854 /*muteState=*/{masterVolume == 0.f,
5855 track->getPortVolume() == 0.f,
5856 /* muteFromStreamMuted= */ false,
5857 track->isPlaybackRestricted(),
5858 vlf == 0.f && vrf == 0.f,
5859 vh == 0.f});
5860 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005861 vlf *= volume;
5862 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005863
jiabin220eea12024-05-17 17:55:20 +00005864 if (track->getInternalMute()) {
5865 vlf = 0.f;
5866 vrf = 0.f;
5867 }
5868
jiabin76d94692022-12-15 21:51:21 +00005869 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005870 ++fastTracks;
5871 } else {
5872 // was it previously active?
5873 if (state->mTrackMask & (1 << j)) {
5874 fastTrack->mBufferProvider = NULL;
5875 fastTrack->mGeneration++;
5876 state->mTrackMask &= ~(1 << j);
5877 didModify = true;
5878 // If any fast tracks were removed, we must wait for acknowledgement
5879 // because we're about to decrement the last sp<> on those tracks.
5880 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5881 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005882 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5883 // AudioTrack may start (which may not be with a start() but with a write()
5884 // after underrun) and immediately paused or released. In that case the
5885 // FastTrack state hasn't had time to update.
5886 // TODO Remove the ALOGW when this theory is confirmed.
5887 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005888 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005889 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005890 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005891 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005892 }
5893 tracksToRemove->add(track);
5894 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005895 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005896 }
jiabin245cdd92018-12-07 17:55:15 -08005897 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5898 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5899 didModify = true;
5900 }
Eric Laurent81784c32012-11-19 14:55:58 -08005901 continue;
5902 }
5903
5904 { // local variable scope to avoid goto warning
5905
5906 audio_track_cblk_t* cblk = track->cblk();
5907
5908 // The first time a track is added we wait
5909 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005910 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005911
5912 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005913 // use the trackId as the AudioMixer name.
5914 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005915 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005916 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005917 track->channelMask(),
5918 track->format(),
5919 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005920 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005921 ALOGW("%s(): AudioMixer cannot create track(%d)"
5922 " mask %#x, format %#x, sessionId %d",
5923 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005924 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005925 tracksToRemove->add(track);
5926 track->invalidate(); // consider it dead.
5927 continue;
5928 }
5929 }
5930
Eric Laurent81784c32012-11-19 14:55:58 -08005931 // make sure that we have enough frames to mix one full buffer.
5932 // enforce this condition only once to enable draining the buffer in case the client
5933 // app does not call stop() and relies on underrun to stop:
5934 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5935 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005936 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005937 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5938 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005939
5940 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005941 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005942 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5943 // add frames already consumed but not yet released by the resampler
5944 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005945 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005946
Eric Laurent81784c32012-11-19 14:55:58 -08005947 uint32_t minFrames = 1;
5948 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5949 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005950 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005951 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005952
5953 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005954 if (ATRACE_ENABLED()) {
5955 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005956 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005957 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005958 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005959 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005960 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005961 !track->isPaused() && !track->isTerminated())
5962 {
Andy Hungc0691382018-09-12 18:01:57 -07005963 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005964
5965 mixedTracks++;
5966
Shunkai Yaof4847652024-01-12 00:25:20 +00005967 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005968 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005969 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005970 if (track->mainBuffer() != mSinkBuffer &&
5971 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005972 if (mEffectBufferEnabled) {
5973 mEffectBufferValid = true; // Later can set directly.
5974 }
Eric Laurent81784c32012-11-19 14:55:58 -08005975 chain = getEffectChain_l(track->sessionId());
5976 // Delegate volume control to effect in track effect chain if needed
5977 if (chain != 0) {
5978 tracksWithEffect++;
5979 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005980 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005981 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005982 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005983 }
5984 }
5985
5986
5987 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005988 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005989 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005990 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5991 if (track->state() == IAfTrackBase::RESUMING) {
5992 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005993 // If a new track is paused immediately after start, do not ramp on resume.
5994 if (cblk->mServer != 0) {
5995 param = AudioMixer::RAMP_VOLUME;
5996 }
Eric Laurent81784c32012-11-19 14:55:58 -08005997 }
Andy Hungc0691382018-09-12 18:01:57 -07005998 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005999 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07006000 // FIXME should not make a decision based on mServer
6001 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006002 // If the track is stopped before the first frame was mixed,
6003 // do not apply ramp
6004 param = AudioMixer::RAMP_VOLUME;
6005 }
6006
6007 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07006008 uint32_t vl, vr; // in U8.24 integer format
6009 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07006010 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07006011 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07006012 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07006013 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07006014 track->audioTrackServerProxy()->framesReleased()).first;
Andy Hung6b137d12024-08-27 22:35:17 +00006015 float v;
6016 if (!audioserver_flags::portid_volume_management()) {
6017 v = masterVolume * mStreamTypes[track->streamType()].volume;
6018 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6019 v = 0;
6020 }
6021 } else {
6022 v = masterVolume * track->getPortVolume();
6023 if (track->isPlaybackRestricted()) {
6024 v = 0;
6025 }
Eric Laurenteab90452019-06-24 15:17:46 -07006026 }
Eric Laurenteab90452019-06-24 15:17:46 -07006027 handleVoipVolume_l(&v);
6028
6029 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006030 vl = vr = 0;
6031 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006032 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006033 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006034 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006035 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6036 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006037 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006038 if (vlf > GAIN_FLOAT_UNITY) {
6039 ALOGV("Track left volume out of range: %.3g", vlf);
6040 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006041 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006042 if (vrf > GAIN_FLOAT_UNITY) {
6043 ALOGV("Track right volume out of range: %.3g", vrf);
6044 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006045 }
Andy Hung6b137d12024-08-27 22:35:17 +00006046 if (!audioserver_flags::portid_volume_management()) {
6047 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6048 /*muteState=*/{masterVolume == 0.f,
6049 mStreamTypes[track->streamType()].volume == 0.f,
6050 mStreamTypes[track->streamType()].mute,
6051 track->isPlaybackRestricted(),
6052 vlf == 0.f && vrf == 0.f,
6053 vh == 0.f});
6054 } else {
6055 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6056 /*muteState=*/{masterVolume == 0.f,
6057 track->getPortVolume() == 0.f,
6058 /* muteFromStreamMuted= */ false,
6059 track->isPlaybackRestricted(),
6060 vlf == 0.f && vrf == 0.f,
6061 vh == 0.f});
6062 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006063 // now apply the master volume and stream type volume and shaper volume
6064 vlf *= v * vh;
6065 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006066 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006067 // then derive vl and vr as U8.24 versions for the effect chain
6068 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6069 vl = (uint32_t) (scaleto8_24 * vlf);
6070 vr = (uint32_t) (scaleto8_24 * vrf);
6071 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006072 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006073 // send level comes from shared memory and so may be corrupt
6074 if (sendLevel > MAX_GAIN_INT) {
6075 ALOGV("Track send level out of range: %04X", sendLevel);
6076 sendLevel = MAX_GAIN_INT;
6077 }
Andy Hung6be49402014-05-30 10:42:03 -07006078 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6079 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006080 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006081
jiabin220eea12024-05-17 17:55:20 +00006082 if (track->getInternalMute()) {
6083 vrf = 0.f;
6084 vlf = 0.f;
6085 }
6086
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006087 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006088
Eric Laurent81784c32012-11-19 14:55:58 -08006089 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006090 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006091 // Do not ramp volume if volume is controlled by effect
6092 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006093 // Update remaining floating point volume levels
6094 vlf = (float)vl / (1 << 24);
6095 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006096 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006097 } else {
6098 // force no volume ramp when volume controller was just disabled or removed
6099 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006100 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006101 param = AudioMixer::VOLUME;
6102 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006103 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006104 }
6105
Eric Laurent81784c32012-11-19 14:55:58 -08006106 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006107 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006108 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006109
Andy Hungc0691382018-09-12 18:01:57 -07006110 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6111 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6112 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006113 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006114 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006115 AudioMixer::TRACK,
6116 AudioMixer::FORMAT, (void *)track->format());
6117 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006118 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006119 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006120 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006121
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006122 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006123 mAudioMixer->setParameter(
6124 trackId,
6125 AudioMixer::TRACK,
6126 AudioMixer::MIXER_CHANNEL_MASK,
6127 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6128 } else {
6129 mAudioMixer->setParameter(
6130 trackId,
6131 AudioMixer::TRACK,
6132 AudioMixer::MIXER_CHANNEL_MASK,
6133 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6134 }
6135
Glenn Kastene3aa6592012-12-04 12:22:46 -08006136 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006137 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006138 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006139 if (reqSampleRate == 0) {
6140 reqSampleRate = mSampleRate;
6141 } else if (reqSampleRate > maxSampleRate) {
6142 reqSampleRate = maxSampleRate;
6143 }
Eric Laurent81784c32012-11-19 14:55:58 -08006144 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006145 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006146 AudioMixer::RESAMPLE,
6147 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006148 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006149
Andy Hung8edb8dc2015-03-26 19:13:55 -07006150 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006151 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006152 AudioMixer::TIMESTRETCH,
6153 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006154 // cast away constness for this generic API.
6155 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006156
Andy Hung69aed5f2014-02-25 17:24:40 -08006157 /*
6158 * Select the appropriate output buffer for the track.
6159 *
Andy Hung98ef9782014-03-04 14:46:50 -08006160 * Tracks with effects go into their own effects chain buffer
6161 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006162 *
6163 * Other tracks can use mMixerBuffer for higher precision
6164 * channel accumulation. If this buffer is enabled
6165 * (mMixerBufferEnabled true), then selected tracks will accumulate
6166 * into it.
6167 *
6168 */
6169 if (mMixerBufferEnabled
6170 && (track->mainBuffer() == mSinkBuffer
6171 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006172 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006173 mAudioMixer->setParameter(
6174 trackId,
6175 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006176 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006177 mAudioMixer->setParameter(
6178 trackId,
6179 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006180 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006181 } else {
6182 mAudioMixer->setParameter(
6183 trackId,
6184 AudioMixer::TRACK,
6185 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6186 mAudioMixer->setParameter(
6187 trackId,
6188 AudioMixer::TRACK,
6189 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6190 // TODO: override track->mainBuffer()?
6191 mMixerBufferValid = true;
6192 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006193 } else {
6194 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006195 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006196 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006197 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006198 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006199 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006200 AudioMixer::TRACK,
6201 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6202 }
Eric Laurent81784c32012-11-19 14:55:58 -08006203 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006204 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006205 AudioMixer::TRACK,
6206 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006207 mAudioMixer->setParameter(
6208 trackId,
6209 AudioMixer::TRACK,
6210 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006211 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006212 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006213 trackId,
6214 AudioMixer::TRACK,
6215 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006216 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006217 mAudioMixer->setParameter(
6218 trackId,
6219 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006220 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006221
6222 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006223 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006224
6225 // If one track is ready, set the mixer ready if:
6226 // - the mixer was not ready during previous round OR
6227 // - no other track is not ready
6228 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6229 mixerStatus != MIXER_TRACKS_ENABLED) {
6230 mixerStatus = MIXER_TRACKS_READY;
6231 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006232
6233 // Enable the next few lines to instrument a test for underrun log handling.
6234 // TODO: Remove when we have a better way of testing the underrun log.
6235#if 0
6236 static int i;
6237 if ((++i & 0xf) == 0) {
6238 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6239 }
6240#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006241 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006242 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006243 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006244 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6245 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006246 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006247 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006248 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006249
Eric Laurent81784c32012-11-19 14:55:58 -08006250 // clear effect chain input buffer if an active track underruns to avoid sending
6251 // previous audio buffer again to effects
6252 chain = getEffectChain_l(track->sessionId());
6253 if (chain != 0) {
6254 chain->clearInputBuffer();
6255 }
6256
Andy Hungc0691382018-09-12 18:01:57 -07006257 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006258 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6259 track->isStopped() || track->isPaused()) {
6260 // We have consumed all the buffers of this track.
6261 // Remove it from the list of active tracks.
6262 // TODO: use actual buffer filling status instead of latency when available from
6263 // audio HAL
6264 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006265 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006266 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6267 if (track->isStopped()) {
6268 track->reset();
6269 }
6270 tracksToRemove->add(track);
6271 }
6272 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006273 // No buffers for this track. Give it a few chances to
6274 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006275 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006276 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6277 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006278 tracksToRemove->add(track);
6279 // indicate to client process that the track was disabled because of underrun;
6280 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006281 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006282 // If one track is not ready, mark the mixer also not ready if:
6283 // - the mixer was ready during previous round OR
6284 // - no other track is ready
6285 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6286 mixerStatus != MIXER_TRACKS_READY) {
6287 mixerStatus = MIXER_TRACKS_ENABLED;
6288 }
6289 }
Andy Hungc0691382018-09-12 18:01:57 -07006290 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006291 }
6292
6293 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006294
6295 }
6296
jiabin245cdd92018-12-07 17:55:15 -08006297 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6298 // When there is no fast track playing haptic and FastMixer exists,
6299 // enabling the first FastTrack, which provides mixed data from normal
6300 // tracks, to play haptic data.
6301 FastTrack *fastTrack = &state->mFastTracks[0];
6302 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6303 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6304 didModify = true;
6305 }
6306 }
6307
Eric Laurent81784c32012-11-19 14:55:58 -08006308 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006309 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006310 if (didModify) {
6311 state->mFastTracksGen++;
6312 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6313 if (kUseFastMixer == FastMixer_Dynamic &&
6314 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6315 state->mCommand = FastMixerState::COLD_IDLE;
6316 state->mColdFutexAddr = &mFastMixerFutex;
6317 state->mColdGen++;
6318 mFastMixerFutex = 0;
6319 if (kUseFastMixer == FastMixer_Dynamic) {
6320 mNormalSink = mOutputSink;
6321 }
6322 // If we go into cold idle, need to wait for acknowledgement
6323 // so that fast mixer stops doing I/O.
6324 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6325 pauseAudioWatchdog = true;
6326 }
Eric Laurent81784c32012-11-19 14:55:58 -08006327 }
6328 if (sq != NULL) {
6329 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006330 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6331 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6332 // when bringing the output sink into standby.)
6333 //
6334 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6335 //
6336 // This occurs with BT suspend when we idle the FastMixer with
6337 // active tracks, which may be added or removed.
6338 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006339 }
6340#ifdef AUDIO_WATCHDOG
6341 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6342 mAudioWatchdog->pause();
6343 }
6344#endif
6345
6346 // Now perform the deferred reset on fast tracks that have stopped
6347 while (resetMask != 0) {
6348 size_t i = __builtin_ctz(resetMask);
6349 ALOG_ASSERT(i < count);
6350 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006351 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006352 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6353 track->reset();
6354 }
6355
Andy Hung80d03d22018-04-10 10:32:11 -07006356 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6357 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6358 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6359 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6360 // See also the implementation of destroyTrack_l().
6361 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006362 const int trackId = track->id();
6363 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6364 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006365 }
6366 }
6367
Eric Laurent81784c32012-11-19 14:55:58 -08006368 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006369 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006370
Eric Laurentb3f315a2021-07-13 15:09:05 +02006371 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6372 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006373 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006374 }
6375
6376 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006377 // as long as there are effects we should clear the effects buffer, to avoid
6378 // passing a non-clean buffer to the effect chain
6379 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006380 if (mType == SPATIALIZER) {
6381 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6382 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006383 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006384 // sink or mix buffer must be cleared if all tracks are connected to an
6385 // effect chain as in this case the mixer will not write to the sink or mix buffer
6386 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006387 // always clear sink buffer for spatializer output as the output of the spatializer
6388 // effect will be accumulated into it
6389 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6390 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006391 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006392 if (mMixerBufferValid) {
6393 memset(mMixerBuffer, 0, mMixerBufferSize);
6394 // TODO: In testing, mSinkBuffer below need not be cleared because
6395 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6396 // after mixing.
6397 //
6398 // To enforce this guarantee:
6399 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6400 // (mixedTracks == 0 && fastTracks > 0))
6401 // must imply MIXER_TRACKS_READY.
6402 // Later, we may clear buffers regardless, and skip much of this logic.
6403 }
Andy Hung98ef9782014-03-04 14:46:50 -08006404 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006405 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006406 }
6407
6408 // if any fast tracks, then status is ready
6409 mMixerStatusIgnoringFastTracks = mixerStatus;
6410 if (fastTracks > 0) {
6411 mixerStatus = MIXER_TRACKS_READY;
6412 }
6413 return mixerStatus;
6414}
6415
Andy Hungc5007f82023-08-29 14:26:09 -07006416// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006417uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006418{
6419 uint32_t trackCount = 0;
6420 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006421 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006422 trackCount++;
6423 }
6424 }
6425 return trackCount;
6426}
6427
Andy Hungee58e4a2023-07-07 13:47:37 -07006428bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006429{
Brian Lindahl65e90012022-07-27 18:01:07 +02006430 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6431 // could falsely detect that the frame position has stalled due to underrun because we haven't
6432 // given the Audio HAL enough time to update.
6433 const nsecs_t nowNs = systemTime();
6434 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6435 return mLatchedValue;
6436 }
6437 mPreviousNs = nowNs;
6438 mLatchedValue = false;
6439 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006440 uint64_t position = 0;
6441 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006442 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006443 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006444 if (position != mPreviousPosition) {
6445 mPreviousPosition = position;
6446 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006447 }
6448 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006449 return mLatchedValue;
6450}
6451
Andy Hungee58e4a2023-07-07 13:47:37 -07006452void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006453{
6454 mLatchedValue = true;
6455 mPreviousPosition = 0;
6456 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006457}
6458
Andy Hungc5007f82023-08-29 14:26:09 -07006459// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006460bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006461 audio_channel_mask_t channelMask, audio_format_t format,
6462 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006463{
Andy Hung1bc088a2018-02-09 15:57:31 -08006464 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6465 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006466 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006467 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006468 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006469 ALOGW("%s: invalid format: %#x", __func__, format);
6470 return false;
6471 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006472 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006473 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6474 return false;
6475 }
6476 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006477}
6478
Andy Hungc5007f82023-08-29 14:26:09 -07006479// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006480bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006481 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006482{
Eric Laurent81784c32012-11-19 14:55:58 -08006483 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006484 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006485
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006486 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006487
Eric Laurent10351942014-05-08 18:49:52 -07006488 AudioParameter param = AudioParameter(keyValuePair);
6489 int value;
6490 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6491 reconfig = true;
6492 }
6493 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006494 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006495 status = BAD_VALUE;
6496 } else {
6497 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006498 reconfig = true;
6499 }
Eric Laurent10351942014-05-08 18:49:52 -07006500 }
6501 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006502 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006503 status = BAD_VALUE;
6504 } else {
6505 // no need to save value, since it's constant
6506 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006507 }
Eric Laurent10351942014-05-08 18:49:52 -07006508 }
6509 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6510 // do not accept frame count changes if tracks are open as the track buffer
6511 // size depends on frame count and correct behavior would not be guaranteed
6512 // if frame count is changed after track creation
6513 if (!mTracks.isEmpty()) {
6514 status = INVALID_OPERATION;
6515 } else {
6516 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006517 }
Eric Laurent10351942014-05-08 18:49:52 -07006518 }
6519 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006520 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006521 }
Eric Laurent81784c32012-11-19 14:55:58 -08006522
Eric Laurent10351942014-05-08 18:49:52 -07006523 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006524 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006525 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006526 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6527 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006528 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006529 mThreadMetrics.logEndInterval();
6530 mThreadSnapshot.onEnd();
6531 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006532 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006533 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006534 }
Eric Laurent10351942014-05-08 18:49:52 -07006535 if (status == NO_ERROR && reconfig) {
6536 readOutputParameters_l();
6537 delete mAudioMixer;
6538 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006539 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006540 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006541 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006542 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006543 track->channelMask(),
6544 track->format(),
6545 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006546 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006547 "%s(): AudioMixer cannot create track(%d)"
6548 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006549 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006550 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006551 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006552 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006553 }
Eric Laurent81784c32012-11-19 14:55:58 -08006554 }
6555
Dean Wheatley68918102021-03-19 22:09:19 +11006556 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006557}
6558
6559
Andy Hungee58e4a2023-07-07 13:47:37 -07006560void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006561{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006562 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006563 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006564 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006565 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006566 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6567 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6568 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006569 if (hasFastMixer()) {
6570 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6571
6572 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6573 // while we are dumping it. It may be inconsistent, but it won't mutate!
6574 // This is a large object so we place it on the heap.
6575 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006576 const std::unique_ptr<FastMixerDumpState> copy =
6577 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006578 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006579
6580#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006581 // Similar for state queue
6582 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6583 observerCopy.dump(fd);
6584 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6585 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006586#endif
6587
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006588#ifdef AUDIO_WATCHDOG
6589 if (mAudioWatchdog != 0) {
6590 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6591 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6592 wdCopy.dump(fd);
6593 }
6594#endif
6595
6596 } else {
6597 dprintf(fd, " No FastMixer\n");
6598 }
Eric Laurent90cea102023-05-15 15:08:27 +02006599
6600 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6601 mBluetoothLatencyModesEnabled ? "" : "not ");
6602 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6603 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6604 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006605}
6606
Andy Hungee58e4a2023-07-07 13:47:37 -07006607uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006608{
6609 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6610}
6611
Andy Hungee58e4a2023-07-07 13:47:37 -07006612uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006613{
6614 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6615}
6616
Andy Hungee58e4a2023-07-07 13:47:37 -07006617void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006618{
6619 PlaybackThread::cacheParameters_l();
6620
6621 // FIXME: Relaxed timing because of a certain device that can't meet latency
6622 // Should be reduced to 2x after the vendor fixes the driver issue
6623 // increase threshold again due to low power audio mode. The way this warning
6624 // threshold is calculated and its usefulness should be reconsidered anyway.
6625 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6626}
6627
Andy Hungee58e4a2023-07-07 13:47:37 -07006628void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006629 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006630}
6631
Andy Hungee58e4a2023-07-07 13:47:37 -07006632void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006633 // Only handle latency mode if:
6634 // - mBluetoothLatencyModesEnabled is true
6635 // - the HAL supports latency modes
6636 // - the selected device is Bluetooth LE or A2DP
6637 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6638 return;
6639 }
6640 if (mOutDeviceTypeAddrs.size() != 1
6641 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6642 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6643 return;
6644 }
6645
6646 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6647 if (mSupportedLatencyModes.size() == 1) {
6648 // If the HAL only support one latency mode currently, confirm the choice
6649 latencyMode = mSupportedLatencyModes[0];
6650 } else if (mSupportedLatencyModes.size() > 1) {
6651 // Request low latency if:
6652 // - At least one active track is either:
6653 // - a fast track with gaming usage or
6654 // - a track with acessibility usage
6655 for (const auto& track : mActiveTracks) {
6656 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6657 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6658 latencyMode = AUDIO_LATENCY_MODE_LOW;
6659 break;
6660 }
6661 }
6662 }
6663
6664 if (latencyMode != mSetLatencyMode) {
6665 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6666 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6667 __func__, mId, toString(latencyMode).c_str(), status);
6668 if (status == NO_ERROR) {
6669 mSetLatencyMode = latencyMode;
6670 }
6671 }
6672}
6673
Andy Hungee58e4a2023-07-07 13:47:37 -07006674void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006675
6676 if (mOutput == nullptr || mOutput->stream == nullptr) {
6677 return;
6678 }
6679 std::vector<audio_latency_mode_t> latencyModes;
6680 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6681 if (status != NO_ERROR) {
6682 latencyModes.clear();
6683 }
6684 if (latencyModes != mSupportedLatencyModes) {
6685 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6686 __func__, mId, status, toString(latencyModes).c_str());
6687 mSupportedLatencyModes.swap(latencyModes);
6688 sendHalLatencyModesChangedEvent_l();
6689 }
6690}
6691
Andy Hungee58e4a2023-07-07 13:47:37 -07006692status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006693 std::vector<audio_latency_mode_t>* modes) {
6694 if (modes == nullptr) {
6695 return BAD_VALUE;
6696 }
Andy Hung972bec12023-08-31 16:13:39 -07006697 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006698 *modes = mSupportedLatencyModes;
6699 return NO_ERROR;
6700}
6701
Andy Hungee58e4a2023-07-07 13:47:37 -07006702void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006703 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006704 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006705 if (modes != mSupportedLatencyModes) {
6706 ALOGD("%s: thread(%d) supported latency modes: %s",
6707 __func__, mId, toString(modes).c_str());
6708 mSupportedLatencyModes.swap(modes);
6709 sendHalLatencyModesChangedEvent_l();
6710 }
6711}
6712
Andy Hungee58e4a2023-07-07 13:47:37 -07006713status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006714 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6715 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6716 return INVALID_OPERATION;
6717 }
6718 mBluetoothLatencyModesEnabled.store(enabled);
6719 return NO_ERROR;
6720}
6721
Eric Laurent81784c32012-11-19 14:55:58 -08006722// ----------------------------------------------------------------------------
6723
Andy Hungee58e4a2023-07-07 13:47:37 -07006724/* static */
6725sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006726 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006727 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6728 const audio_offload_info_t& offloadInfo) {
6729 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006730 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006731}
6732
Andy Hung583043b2023-07-17 17:05:00 -07006733DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006734 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6735 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006736 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006737 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006738{
Andy Hung583043b2023-07-17 17:05:00 -07006739 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006740}
6741
Andy Hungee58e4a2023-07-07 13:47:37 -07006742DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006743{
6744}
6745
Andy Hungee58e4a2023-07-07 13:47:37 -07006746void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006747{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006748 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006749 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6750 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6751}
6752
Andy Hungee58e4a2023-07-07 13:47:37 -07006753void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006754{
Andy Hung972bec12023-08-31 16:13:39 -07006755 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006756 if (mMasterBalance != balance) {
6757 mMasterBalance.store(balance);
6758 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6759 broadcast_l();
6760 }
6761}
6762
Andy Hungee58e4a2023-07-07 13:47:37 -07006763void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006764{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006765 float left, right;
6766
Andy Hung333ab962019-05-28 20:23:35 -07006767 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006768 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006769
Andy Hung398ffa22022-12-13 19:19:53 -08006770 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6771 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6772
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006773 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6774 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006775
6776 const int64_t volumeShaperFrames =
6777 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6778 const auto [shaperVolume, shaperActive] =
6779 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006780 mVolumeShaperActive = shaperActive;
6781
Vlad Popae2f5aef2022-07-25 16:00:20 +02006782 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6783 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6784 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6785
6786 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6787
Andy Hung6b137d12024-08-27 22:35:17 +00006788 if (!audioserver_flags::portid_volume_management()) {
6789 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6790 track->isPlaybackRestricted()) {
6791 left = right = 0;
6792 } else {
6793 float typeVolume = mStreamTypes[track->streamType()].volume;
6794 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurent277a37e2024-07-29 18:37:52 +00006795
Andy Hung6b137d12024-08-27 22:35:17 +00006796 if (left > GAIN_FLOAT_UNITY) {
6797 left = GAIN_FLOAT_UNITY;
6798 }
6799 if (right > GAIN_FLOAT_UNITY) {
6800 right = GAIN_FLOAT_UNITY;
6801 }
6802 left *= v;
6803 right *= v;
6804 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006805 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Andy Hung6b137d12024-08-27 22:35:17 +00006806 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6807 right *= mMasterBalanceRight;
6808 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006809 }
Andy Hung6b137d12024-08-27 22:35:17 +00006810 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6811 /*muteState=*/{mMasterMute,
6812 mStreamTypes[track->streamType()].volume == 0.f,
6813 mStreamTypes[track->streamType()].mute,
6814 track->isPlaybackRestricted(),
6815 clientVolumeMute,
6816 shaperVolume == 0.f});
6817 } else {
6818 if (mMasterMute || track->isPlaybackRestricted()) {
6819 left = right = 0;
6820 } else {
6821 float typeVolume = track->getPortVolume();
6822 const float v = mMasterVolume * typeVolume * shaperVolume;
Liana Kazanova (xWF)d3e99d22024-08-23 22:15:51 +00006823
Andy Hung6b137d12024-08-27 22:35:17 +00006824 if (left > GAIN_FLOAT_UNITY) {
6825 left = GAIN_FLOAT_UNITY;
6826 }
6827 if (right > GAIN_FLOAT_UNITY) {
6828 right = GAIN_FLOAT_UNITY;
6829 }
6830 left *= v;
6831 right *= v;
6832 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6833 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6834 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6835 right *= mMasterBalanceRight;
6836 }
6837 }
6838 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6839 /*muteState=*/{mMasterMute,
6840 track->getPortVolume() == 0.f,
6841 /* muteFromStreamMuted= */ false,
6842 track->isPlaybackRestricted(),
6843 clientVolumeMute,
6844 shaperVolume == 0.f});
6845 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006846
Eric Laurentbfb1b832013-01-07 09:53:42 -08006847 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006848 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006849 if (left != mLeftVolFloat || right != mRightVolFloat) {
6850 mLeftVolFloat = left;
6851 mRightVolFloat = right;
6852
Eric Laurentbfb1b832013-01-07 09:53:42 -08006853 // Delegate volume control to effect in track effect chain if needed
6854 // only one effect chain can be present on DirectOutputThread, so if
6855 // there is one, the track is connected to it
6856 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006857 // if effect chain exists, volume is handled by it.
6858 // Convert volumes from float to 8.24
6859 uint32_t vl = (uint32_t)(left * (1 << 24));
6860 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006861 // Direct/Offload effect chains set output volume in setVolume().
6862 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006863 } else {
6864 // otherwise we directly set the volume.
6865 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006866 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006867 }
6868 }
6869}
6870
Andy Hungee58e4a2023-07-07 13:47:37 -07006871void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006872{
Andy Hung8d31fd22023-06-26 19:20:57 -07006873 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6874 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006875
Eric Laurent0f0631e2015-07-06 18:01:25 -07006876 if (previousTrack != 0 && latestTrack != 0) {
6877 if (mType == DIRECT) {
6878 if (previousTrack.get() != latestTrack.get()) {
6879 mFlushPending = true;
6880 }
6881 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006882 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6883 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006884 mFlushPending = true;
6885 }
6886 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006887 } else if (previousTrack == 0) {
6888 // there could be an old track added back during track transition for direct
6889 // output, so always issues flush to flush data of the previous track if it
6890 // was already destroyed with HAL paused, then flush can resume the playback
6891 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006892 }
6893 PlaybackThread::onAddNewTrack_l();
6894}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006895
Andy Hungee58e4a2023-07-07 13:47:37 -07006896PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006897 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006898)
6899{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006900 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006901 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006902 bool doHwPause = false;
6903 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006904
6905 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006906 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006907 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006908 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006909 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006910 continue;
6911 }
6912
Andy Hung8d31fd22023-06-26 19:20:57 -07006913 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006914#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006915 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006916#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006917 // Only consider last track started for volume and mixer state control.
6918 // In theory an older track could underrun and restart after the new one starts
6919 // but as we only care about the transition phase between two tracks on a
6920 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006921 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006922 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006923
Kuowei Li23666472021-01-20 10:23:25 +08006924 if (track->isPausePending()) {
6925 track->pauseAck();
6926 // It is possible a track might have been flushed or stopped.
6927 // Other operations such as flush pending might occur on the next prepare.
6928 if (track->isPausing()) {
6929 track->setPaused();
6930 }
6931 // Always perform pause, as an immediate flush will change
6932 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006933 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006934 doHwPause = true;
6935 mHwPaused = true;
6936 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006937 } else if (track->isFlushPending()) {
6938 track->flushAck();
6939 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006940 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006941 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006942 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006943 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006944 if (last) {
6945 mLeftVolFloat = mRightVolFloat = -1.0;
6946 if (mHwPaused) {
6947 doHwResume = true;
6948 mHwPaused = false;
6949 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006950 }
6951 }
6952
Eric Laurent81784c32012-11-19 14:55:58 -08006953 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006954 // for all its buffers to be filled before processing it.
6955 // Allow draining the buffer in case the client
6956 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006957 // hence the test on (track->retryCount() > 1).
6958 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006959 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6960 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006961 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006962
6963 // target retry count that we will use is based on the time we wait for retries.
6964 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6965 // the retry threshold is when we accept any size for PCM data. This is slightly
6966 // smaller than the retry count so we can push small bits of data without a glitch.
6967 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006968 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006969 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006970 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006971 minFrames = mNormalFrameCount;
6972 } else {
6973 minFrames = 1;
6974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006975
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006976 const size_t framesReady = track->framesReady();
6977 const int trackId = track->id();
6978 if (ATRACE_ENABLED()) {
6979 std::string traceName("nRdy");
6980 traceName += std::to_string(trackId);
6981 ATRACE_INT(traceName.c_str(), framesReady);
6982 }
6983 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006984 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006985 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006986 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006987
Andy Hung8d31fd22023-06-26 19:20:57 -07006988 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6989 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006990 if (last) {
6991 // make sure processVolume_l() will apply new volume even if 0
6992 mLeftVolFloat = mRightVolFloat = -1.0;
6993 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006994 if (!mHwSupportsPause) {
6995 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006996 }
6997 }
6998
6999 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08007000 processVolume_l(track, last);
7001 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007002 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007003 if (previousTrack != 0) {
7004 if (track != previousTrack.get()) {
7005 // Flush any data still being written from last track
7006 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07007007 // Invalidate previous track to force a seek when resuming.
7008 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007009 }
7010 }
7011 mPreviousTrack = track;
7012
Eric Laurentd595b7c2013-04-03 17:27:56 -07007013 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07007014 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08007015 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07007016 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07007017 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007018 doHwResume = true;
7019 mHwPaused = false;
7020 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007021 }
Eric Laurent81784c32012-11-19 14:55:58 -08007022 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007023 // clear effect chain input buffer if the last active track started underruns
7024 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007025 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007026 mEffectChains[0]->clearInputBuffer();
7027 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007028 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007029 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007030 if (last && mHwPaused) {
7031 doHwResume = true;
7032 mHwPaused = false;
7033 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007034 }
7035 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7036 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007037 // We have consumed all the buffers of this track.
7038 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007039 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007040 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007041 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007042 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007043 if (presComplete) {
7044 mOutput->presentationComplete();
7045 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007046 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007047 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007048 }
Eric Laurent81784c32012-11-19 14:55:58 -08007049 if (track->isStopped()) {
7050 track->reset();
7051 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007052 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007053 }
7054 } else {
7055 // No buffers for this track. Give it a few chances to
7056 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007057 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007058 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007059 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007060 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007061 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007062 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007063 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007064 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7065 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007066 tracksToRemove->add(track);
7067 // indicate to client process that the track was disabled because of
7068 // underrun; it will then automatically call start() when data is available
7069 track->disable();
7070 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7071 // unlike mixerthread, HAL can be paused for direct output
7072 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7073 "minFrames = %u, mFormat = %#x",
7074 framesReady, minFrames, mFormat);
7075 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7076 doHwPause = true;
7077 mHwPaused = true;
7078 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007079 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007080 } else if (last) {
7081 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007082 }
7083 }
7084 }
7085 }
7086
Eric Laurentd1f69b02014-12-15 14:33:13 -08007087 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007088 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007089 for (size_t i = 0; i < mTracks.size(); i++) {
7090 if (mTracks[i]->isFlushPending()) {
7091 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007092 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007093 }
7094 }
7095 }
7096
7097 // make sure the pause/flush/resume sequence is executed in the right order.
7098 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7099 // before flush and then resume HW. This can happen in case of pause/flush/resume
7100 // if resume is received before pause is executed.
7101 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007102 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007103 status_t result = mOutput->stream->pause();
7104 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007105 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007106 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007107 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007108 flushHw_l();
7109 }
7110 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007111 status_t result = mOutput->stream->resume();
7112 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007113 }
Eric Laurent81784c32012-11-19 14:55:58 -08007114 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007115 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007116
7117 return mixerStatus;
7118}
7119
Andy Hungee58e4a2023-07-07 13:47:37 -07007120void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007121{
Eric Laurent81784c32012-11-19 14:55:58 -08007122 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007123 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007124 // output audio to hardware
7125 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007126 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007127 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007128 status_t status = mActiveTrack->getNextBuffer(&buffer);
7129 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007130 // no need to pad with 0 for compressed audio
7131 if (audio_has_proportional_frames(mFormat)) {
7132 memset(curBuf, 0, frameCount * mFrameSize);
7133 }
Eric Laurent81784c32012-11-19 14:55:58 -08007134 break;
7135 }
7136 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7137 frameCount -= buffer.frameCount;
7138 curBuf += buffer.frameCount * mFrameSize;
7139 mActiveTrack->releaseBuffer(&buffer);
7140 }
Andy Hung2098f272014-02-27 14:00:06 -08007141 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007142 mSleepTimeUs = 0;
7143 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007144 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007145}
7146
Andy Hungee58e4a2023-07-07 13:47:37 -07007147void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007148{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007149 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007150 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007151 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007152 return;
7153 }
Andy Hung85ba3332021-04-27 17:40:26 -07007154 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7155 mSleepTimeUs = mActiveSleepTimeUs;
7156 } else {
7157 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007158 }
Andy Hung85ba3332021-04-27 17:40:26 -07007159 // Note: In S or later, we do not write zeroes for
7160 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007161}
7162
Andy Hungee58e4a2023-07-07 13:47:37 -07007163void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007164{
7165 {
Andy Hung972bec12023-08-31 16:13:39 -07007166 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007167 for (size_t i = 0; i < mTracks.size(); i++) {
7168 if (mTracks[i]->isFlushPending()) {
7169 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007170 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007171 }
7172 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007173 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007174 flushHw_l();
7175 }
7176 }
7177 PlaybackThread::threadLoop_exit();
7178}
7179
7180// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007181bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007182{
7183 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007184 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007185 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007186
Eric Laurent022a5132024-04-12 17:02:51 +00007187 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007188 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007189 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007190 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007191 const auto& mainTrack = mTracks[mTracks.size() - 1];
7192
7193 trackPaused = mainTrack->isPaused();
7194 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7195 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007196 }
7197
Eric Laurent022a5132024-04-12 17:02:51 +00007198 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007199}
7200
Andy Hungc5007f82023-08-29 14:26:09 -07007201// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007202bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007203 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007204{
7205 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007206 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007207
Eric Laurent10351942014-05-08 18:49:52 -07007208 AudioParameter param = AudioParameter(keyValuePair);
7209 int value;
7210 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007211 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007212 }
Eric Laurent10351942014-05-08 18:49:52 -07007213 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7214 // do not accept frame count changes if tracks are open as the track buffer
7215 // size depends on frame count and correct behavior would not be garantied
7216 // if frame count is changed after track creation
7217 if (!mTracks.isEmpty()) {
7218 status = INVALID_OPERATION;
7219 } else {
7220 reconfig = true;
7221 }
7222 }
7223 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007224 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007225 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007226 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007227 if (!mStandby) {
7228 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007229 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007230 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007231 }
Eric Laurent10351942014-05-08 18:49:52 -07007232 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007233 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007234 }
7235 if (status == NO_ERROR && reconfig) {
7236 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007237 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007238 }
7239 }
7240
Dean Wheatley68918102021-03-19 22:09:19 +11007241 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007242}
7243
Andy Hungee58e4a2023-07-07 13:47:37 -07007244uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007245{
7246 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007247 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007248 time = PlaybackThread::activeSleepTimeUs();
7249 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007250 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007251 }
7252 return time;
7253}
7254
Andy Hungee58e4a2023-07-07 13:47:37 -07007255uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007256{
7257 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007258 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007259 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7260 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007261 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007262 }
7263 return time;
7264}
7265
Andy Hungee58e4a2023-07-07 13:47:37 -07007266uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007267{
7268 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007269 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007270 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7271 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007272 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007273 }
7274 return time;
7275}
7276
Andy Hungee58e4a2023-07-07 13:47:37 -07007277void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007278{
7279 PlaybackThread::cacheParameters_l();
7280
7281 // use shorter standby delay as on normal output to release
7282 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007283 // no delay on outputs with HW A/V sync
7284 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007285 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007286 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007287 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007288 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007289 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007290 }
Eric Laurent81784c32012-11-19 14:55:58 -08007291}
7292
Andy Hungee58e4a2023-07-07 13:47:37 -07007293void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007294{
ziyangch8f194f12021-12-01 13:48:04 -08007295 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007296 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007297 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007298 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007299 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007300 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007301 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007302}
7303
Andy Hungee58e4a2023-07-07 13:47:37 -07007304int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007305 // If a VolumeShaper is active, we must wake up periodically to update volume.
7306 const int64_t NS_PER_MS = 1000000;
7307 return mVolumeShaperActive ?
7308 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7309}
7310
Eric Laurent81784c32012-11-19 14:55:58 -08007311// ----------------------------------------------------------------------------
7312
Andy Hungee58e4a2023-07-07 13:47:37 -07007313AsyncCallbackThread::AsyncCallbackThread(
7314 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007315 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007316 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007317 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007318 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007319 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007320{
7321}
7322
Andy Hungee58e4a2023-07-07 13:47:37 -07007323void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007324{
7325 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7326}
7327
Andy Hungee58e4a2023-07-07 13:47:37 -07007328bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007329{
7330 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007331 uint32_t writeAckSequence;
7332 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007333 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007334
7335 {
Andy Hungc5007f82023-08-29 14:26:09 -07007336 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007337 while (!((mWriteAckSequence & 1) ||
7338 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007339 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007340 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007341 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007342 }
7343
Eric Laurentbfb1b832013-01-07 09:53:42 -08007344 if (exitPending()) {
7345 break;
7346 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007347 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7348 mWriteAckSequence, mDrainSequence);
7349 writeAckSequence = mWriteAckSequence;
7350 mWriteAckSequence &= ~1;
7351 drainSequence = mDrainSequence;
7352 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007353 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007354 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007355 }
7356 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007357 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007358 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007359 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007360 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007361 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007362 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007363 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007364 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007365 if (asyncError != ASYNC_ERROR_NONE) {
7366 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007367 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007368 }
7369 }
7370 }
7371 return false;
7372}
7373
Andy Hungee58e4a2023-07-07 13:47:37 -07007374void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007375{
7376 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007377 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007378 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007379 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007380}
7381
Andy Hungee58e4a2023-07-07 13:47:37 -07007382void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007383{
Andy Hung972bec12023-08-31 16:13:39 -07007384 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007385 // bit 0 is cleared
7386 mWriteAckSequence = sequence << 1;
7387}
7388
Andy Hungee58e4a2023-07-07 13:47:37 -07007389void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007390{
Andy Hung972bec12023-08-31 16:13:39 -07007391 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007392 // ignore unexpected callbacks
7393 if (mWriteAckSequence & 2) {
7394 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007395 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007396 }
7397}
7398
Andy Hungee58e4a2023-07-07 13:47:37 -07007399void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007400{
Andy Hung972bec12023-08-31 16:13:39 -07007401 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007402 // bit 0 is cleared
7403 mDrainSequence = sequence << 1;
7404}
7405
Andy Hungee58e4a2023-07-07 13:47:37 -07007406void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007407{
Andy Hung972bec12023-08-31 16:13:39 -07007408 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007409 // ignore unexpected callbacks
7410 if (mDrainSequence & 2) {
7411 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007412 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007413 }
7414}
7415
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007416void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007417{
Andy Hung972bec12023-08-31 16:13:39 -07007418 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007419 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007420 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007421}
7422
Eric Laurentbfb1b832013-01-07 09:53:42 -08007423
7424// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007425
7426/* static */
7427sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007428 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007429 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7430 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007431 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007432}
7433
Andy Hung583043b2023-07-17 17:05:00 -07007434OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007435 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7436 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007437 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007438 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007439{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007440 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007441 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007442 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007443}
7444
Andy Hungee58e4a2023-07-07 13:47:37 -07007445void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007446{
7447 if (mFlushPending || mHwPaused) {
7448 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007449 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007450 flushHw_l();
7451 } else {
7452 mMixerStatus = MIXER_DRAIN_ALL;
7453 threadLoop_drain();
7454 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007455 if (mUseAsyncWrite) {
7456 ALOG_ASSERT(mCallbackThread != 0);
7457 mCallbackThread->exit();
7458 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007459 PlaybackThread::threadLoop_exit();
7460}
7461
Andy Hungee58e4a2023-07-07 13:47:37 -07007462PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007463 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007464)
7465{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007466 size_t count = mActiveTracks.size();
7467
7468 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007469 bool doHwPause = false;
7470 bool doHwResume = false;
7471
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007472 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007473
Eric Laurentbfb1b832013-01-07 09:53:42 -08007474 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007475 for (const sp<IAfTrack>& t : mActiveTracks) {
7476 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007477#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007478 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007479#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007480 // Only consider last track started for volume and mixer state control.
7481 // In theory an older track could underrun and restart after the new one starts
7482 // but as we only care about the transition phase between two tracks on a
7483 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007484 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007485 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007486
Haynes Mathew George7844f672014-01-15 12:32:55 -08007487 if (track->isInvalid()) {
7488 ALOGW("An invalidated track shouldn't be in active list");
7489 tracksToRemove->add(track);
7490 continue;
7491 }
7492
Andy Hung8d31fd22023-06-26 19:20:57 -07007493 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007494 ALOGW("An idle track shouldn't be in active list");
7495 continue;
7496 }
7497
Kuowei Li23666472021-01-20 10:23:25 +08007498 if (track->isPausePending()) {
7499 track->pauseAck();
7500 // It is possible a track might have been flushed or stopped.
7501 // Other operations such as flush pending might occur on the next prepare.
7502 if (track->isPausing()) {
7503 track->setPaused();
7504 }
7505 // Always perform pause if last, as an immediate flush will change
7506 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007507 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007508 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007509 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007510 mHwPaused = true;
7511 }
7512 // If we were part way through writing the mixbuffer to
7513 // the HAL we must save this until we resume
7514 // BUG - this will be wrong if a different track is made active,
7515 // in that case we want to discard the pending data in the
7516 // mixbuffer and tell the client to present it again when the
7517 // track is resumed
7518 mPausedWriteLength = mCurrentWriteLength;
7519 mPausedBytesRemaining = mBytesRemaining;
7520 mBytesRemaining = 0; // stop writing
7521 }
7522 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007523 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007524 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007525 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007526 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007527 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007528 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007529 track->flushAck();
7530 if (last) {
7531 mFlushPending = true;
7532 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007533 } else if (track->isResumePending()){
7534 track->resumeAck();
7535 if (last) {
7536 if (mPausedBytesRemaining) {
7537 // Need to continue write that was interrupted
7538 mCurrentWriteLength = mPausedWriteLength;
7539 mBytesRemaining = mPausedBytesRemaining;
7540 mPausedBytesRemaining = 0;
7541 }
7542 if (mHwPaused) {
7543 doHwResume = true;
7544 mHwPaused = false;
7545 // threadLoop_mix() will handle the case that we need to
7546 // resume an interrupted write
7547 }
7548 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007549 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007550
Eric Laurent3df841a2016-07-15 15:15:40 -07007551 mLeftVolFloat = mRightVolFloat = -1.0;
7552
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007553 // Do not handle new data in this iteration even if track->framesReady()
7554 mixerStatus = MIXER_TRACKS_ENABLED;
7555 }
7556 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007557 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007558 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007559 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7560 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007561 if (last) {
7562 // make sure processVolume_l() will apply new volume even if 0
7563 mLeftVolFloat = mRightVolFloat = -1.0;
7564 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007565 }
7566
7567 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007568 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007569 if (previousTrack != 0) {
7570 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007571 // Flush any data still being written from last track
7572 mBytesRemaining = 0;
7573 if (mPausedBytesRemaining) {
7574 // Last track was paused so we also need to flush saved
7575 // mixbuffer state and invalidate track so that it will
7576 // re-submit that unwritten data when it is next resumed
7577 mPausedBytesRemaining = 0;
7578 // Invalidate is a bit drastic - would be more efficient
7579 // to have a flag to tell client that some of the
7580 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007581 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007582 }
7583 // flush data already sent to the DSP if changing audio session as audio
7584 // comes from a different source. Also invalidate previous track to force a
7585 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007586 if (previousTrack->sessionId() != track->sessionId()) {
7587 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007588 }
7589 }
7590 }
7591 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007592 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007593 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007594 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007595 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007596 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007597 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007598 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007599 mixerStatus = MIXER_TRACKS_READY;
7600 }
7601 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007602 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007603 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007604 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007605 // Hardware buffer can hold a large amount of audio so we must
7606 // wait for all current track's data to drain before we say
7607 // that the track is stopped.
7608 if (mBytesRemaining == 0) {
7609 // Only start draining when all data in mixbuffer
7610 // has been written
7611 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007612 track->setState(IAfTrackBase::STOPPING_2);
7613 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007614 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7615 if (last && !mStandby) {
7616 // do not modify drain sequence if we are already draining. This happens
7617 // when resuming from pause after drain.
7618 if ((mDrainSequence & 1) == 0) {
7619 mSleepTimeUs = 0;
7620 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7621 mixerStatus = MIXER_DRAIN_TRACK;
7622 mDrainSequence += 2;
7623 }
7624 if (mHwPaused) {
7625 // It is possible to move from PAUSED to STOPPING_1 without
7626 // a resume so we must ensure hardware is running
7627 doHwResume = true;
7628 mHwPaused = false;
7629 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007630 }
7631 }
Eric Laurente93cc032016-05-05 10:15:10 -07007632 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007633 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007634 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007635 }
7636 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007637 // Drain has completed or we are in standby, signal presentation complete
7638 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007639 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007640 mOutput->presentationComplete();
7641 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007642 track->reset();
7643 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007644 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007645 if (!mUseAsyncWrite) {
7646 // If we don't get explicit drain notification we must
7647 // register discontinuity regardless of whether this is
7648 // the previous (!last) or the upcoming (last) track
7649 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007650 mTimestampVerifier.discontinuity(
7651 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007652 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007653 }
7654 } else {
7655 // No buffers for this track. Give it a few chances to
7656 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007657 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007658 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007659 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007660 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007661 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007662 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007663 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7664 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007665 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007666 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007667 // it will then automatically call start() when data is available
7668 track->disable();
7669 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007670 } else if (last){
7671 mixerStatus = MIXER_TRACKS_ENABLED;
7672 }
7673 }
7674 }
7675 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007676 if (track->isReady()) { // check ready to prevent premature start.
7677 processVolume_l(track, last);
7678 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007679 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007680
Eric Laurentea0fade2013-10-04 16:23:48 -07007681 // make sure the pause/flush/resume sequence is executed in the right order.
7682 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7683 // before flush and then resume HW. This can happen in case of pause/flush/resume
7684 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007685 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007686 status_t result = mOutput->stream->pause();
7687 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007688 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007689 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007690 if (mFlushPending) {
7691 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007692 }
Eric Laurentfd477972013-10-25 18:10:40 -07007693 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007694 status_t result = mOutput->stream->resume();
7695 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007696 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007697
Eric Laurentbfb1b832013-01-07 09:53:42 -08007698 // remove all the tracks that need to be...
7699 removeTracks_l(*tracksToRemove);
7700
7701 return mixerStatus;
7702}
7703
Eric Laurentbfb1b832013-01-07 09:53:42 -08007704// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007705bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007706{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007707 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7708 mWriteAckSequence, mDrainSequence);
7709 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007710 return true;
7711 }
7712 return false;
7713}
7714
Andy Hungee58e4a2023-07-07 13:47:37 -07007715bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007716{
Andy Hung972bec12023-08-31 16:13:39 -07007717 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007718 return waitingAsyncCallback_l();
7719}
7720
Andy Hungee58e4a2023-07-07 13:47:37 -07007721void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007722{
Eric Laurente659ef42014-09-29 13:06:46 -07007723 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007724 // Flush anything still waiting in the mixbuffer
7725 mCurrentWriteLength = 0;
7726 mBytesRemaining = 0;
7727 mPausedWriteLength = 0;
7728 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007729 // reset bytes written count to reflect that DSP buffers are empty after flush.
7730 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007731
Eric Laurentbfb1b832013-01-07 09:53:42 -08007732 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007733 // discard any pending drain or write ack by incrementing sequence
7734 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7735 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007736 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007737 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7738 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007739 }
7740}
7741
Andy Hungee58e4a2023-07-07 13:47:37 -07007742void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007743{
Andy Hung972bec12023-08-31 16:13:39 -07007744 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007745 if (PlaybackThread::invalidateTracks_l(streamType)) {
7746 mFlushPending = true;
7747 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007748}
7749
Andy Hungee58e4a2023-07-07 13:47:37 -07007750void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007751 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007752 if (PlaybackThread::invalidateTracks_l(portIds)) {
7753 mFlushPending = true;
7754 }
7755}
7756
Eric Laurentbfb1b832013-01-07 09:53:42 -08007757// ----------------------------------------------------------------------------
7758
Andy Hungee58e4a2023-07-07 13:47:37 -07007759/* static */
7760sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007761 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007762 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007763 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007764}
7765
Andy Hung583043b2023-07-17 17:05:00 -07007766DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007767 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007768 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007769 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007770 mWaitTimeMs(UINT_MAX)
7771{
7772 addOutputTrack(mainThread);
7773}
7774
Andy Hungee58e4a2023-07-07 13:47:37 -07007775DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007776{
7777 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7778 mOutputTracks[i]->destroy();
7779 }
7780}
7781
Andy Hungee58e4a2023-07-07 13:47:37 -07007782void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007783{
7784 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007785 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007786 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007787 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007788 if (mMixerBufferValid) {
7789 memset(mMixerBuffer, 0, mMixerBufferSize);
7790 } else {
7791 memset(mSinkBuffer, 0, mSinkBufferSize);
7792 }
Eric Laurent81784c32012-11-19 14:55:58 -08007793 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007794 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007795 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007796 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007797 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007798}
7799
Andy Hungee58e4a2023-07-07 13:47:37 -07007800void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007801{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007802 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007803 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007804 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007805 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007806 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007807 }
7808 } else if (mBytesWritten != 0) {
7809 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7810 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007811 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007812 } else {
7813 // flush remaining overflow buffers in output tracks
7814 writeFrames = 0;
7815 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007816 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007817 }
7818}
7819
Andy Hungee58e4a2023-07-07 13:47:37 -07007820ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007821{
7822 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007823 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7824
7825 // Consider the first OutputTrack for timestamp and frame counting.
7826
7827 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7828 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7829 // we always claim success.
7830 if (i == 0) {
7831 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7832 ALOGD_IF(correction != 0 && writeFrames != 0,
7833 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7834 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7835 mFramesWritten -= correction;
7836 }
7837
7838 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007839 }
Andy Hungcf10d742020-04-28 15:38:24 -07007840 if (mStandby) {
7841 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007842 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007843 mStandby = false;
7844 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007845 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007846}
7847
Andy Hungee58e4a2023-07-07 13:47:37 -07007848void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007849{
7850 // DuplicatingThread implements standby by stopping all tracks
7851 for (size_t i = 0; i < outputTracks.size(); i++) {
7852 outputTracks[i]->stop();
7853 }
7854}
7855
Andy Hung8a5abfd2023-12-07 19:35:12 -08007856void DuplicatingThread::threadLoop_exit()
7857{
7858 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7859 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7860 // Do so here in the threadLoop_exit().
7861
7862 SortedVector <sp<IAfOutputTrack>> localTracks;
7863 {
7864 audio_utils::lock_guard l(mutex());
7865 localTracks = std::move(mOutputTracks);
7866 mOutputTracks.clear();
jiabinc62d6032024-09-03 23:39:57 +00007867 for (size_t i = 0; i < localTracks.size(); ++i) {
7868 localTracks[i]->destroy();
7869 }
Andy Hung8a5abfd2023-12-07 19:35:12 -08007870 }
7871 localTracks.clear();
7872 outputTracks.clear();
7873 PlaybackThread::threadLoop_exit();
7874}
7875
Andy Hungee58e4a2023-07-07 13:47:37 -07007876void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007877{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007878 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007879
7880 std::stringstream ss;
7881 const size_t numTracks = mOutputTracks.size();
7882 ss << " " << numTracks << " OutputTracks";
7883 if (numTracks > 0) {
7884 ss << ":";
7885 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007886 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007887 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007888 if (thread.get() != nullptr) {
7889 ss << thread.get() << ", " << thread->id();
7890 } else {
7891 ss << "null";
7892 }
7893 ss << ")";
7894 }
7895 }
7896 ss << "\n";
7897 std::string result = ss.str();
7898 write(fd, result.c_str(), result.size());
7899}
7900
Andy Hungee58e4a2023-07-07 13:47:37 -07007901void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007902{
7903 outputTracks = mOutputTracks;
7904}
7905
Andy Hungee58e4a2023-07-07 13:47:37 -07007906void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007907{
7908 outputTracks.clear();
7909}
7910
Andy Hungee58e4a2023-07-07 13:47:37 -07007911void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007912{
Andy Hung972bec12023-08-31 16:13:39 -07007913 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007914 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7915 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7916 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7917 const size_t frameCount =
7918 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7919 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7920 // from different OutputTracks and their associated MixerThreads (e.g. one may
7921 // nearly empty and the other may be dropping data).
7922
Svet Ganov33761132021-05-13 22:51:08 +00007923 // TODO b/182392769: use attribution source util, move to server edge
7924 AttributionSourceState attributionSource = AttributionSourceState();
7925 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007926 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007927 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007928 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007929 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007930 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007931 this,
7932 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007933 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007934 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007935 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007936 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007937 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7938 if (status != NO_ERROR) {
7939 ALOGE("addOutputTrack() initCheck failed %d", status);
7940 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007941 }
Andy Hung6b137d12024-08-27 22:35:17 +00007942 if (!audioserver_flags::portid_volume_management()) {
7943 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7944 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007945 mOutputTracks.add(outputTrack);
7946 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7947 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007948}
7949
Andy Hungee58e4a2023-07-07 13:47:37 -07007950void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007951{
Andy Hung972bec12023-08-31 16:13:39 -07007952 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007953 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7954 if (mOutputTracks[i]->thread() == thread) {
7955 mOutputTracks[i]->destroy();
7956 mOutputTracks.removeAt(i);
7957 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007958 // NO_THREAD_SAFETY_ANALYSIS
7959 // Lambda workaround: as thread != this
7960 // we can safely call the remote thread getOutput.
7961 const bool equalOutput =
7962 [&](){ return thread->getOutput() == mOutput; }();
7963 if (equalOutput) {
7964 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007965 }
Eric Laurent81784c32012-11-19 14:55:58 -08007966 return;
7967 }
7968 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007969 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007970}
7971
Andy Hungc5007f82023-08-29 14:26:09 -07007972// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007973void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007974{
7975 mWaitTimeMs = UINT_MAX;
7976 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007977 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007978 if (strong != 0) {
7979 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7980 if (waitTimeMs < mWaitTimeMs) {
7981 mWaitTimeMs = waitTimeMs;
7982 }
7983 }
7984 }
7985}
7986
Andy Hungee58e4a2023-07-07 13:47:37 -07007987bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007988{
7989 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007990 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007991 if (thread == 0) {
7992 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7993 outputTracks[i].get());
7994 return false;
7995 }
Andy Hung87c693c2023-07-06 20:56:16 -07007996 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007997 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007998 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007999 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
8000 thread.get());
8001 return false;
8002 }
8003 }
8004 return true;
8005}
8006
Andy Hungee58e4a2023-07-07 13:47:37 -07008007void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07008008 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07008009{
Kevin Rocard12381092018-04-11 09:19:59 -07008010 for (auto& outputTrack : outputTracks) { // not mOutputTracks
8011 outputTrack->setMetadatas(metadata.tracks);
8012 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008013}
8014
Andy Hungee58e4a2023-07-07 13:47:37 -07008015uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08008016{
Andy Hung7a6a0f02023-11-29 13:42:08 -08008017 // return half the wait time in microseconds.
8018 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08008019}
8020
Andy Hungee58e4a2023-07-07 13:47:37 -07008021void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008022{
8023 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8024 updateWaitTime_l();
8025
8026 MixerThread::cacheParameters_l();
8027}
8028
Eric Laurentb3f315a2021-07-13 15:09:05 +02008029// ----------------------------------------------------------------------------
8030
Andy Hungee58e4a2023-07-07 13:47:37 -07008031/* static */
8032sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008033 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008034 AudioStreamOut* output,
8035 audio_io_handle_t id,
8036 bool systemReady,
8037 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008038 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008039}
8040
Andy Hung583043b2023-07-17 17:05:00 -07008041SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008042 AudioStreamOut* output,
8043 audio_io_handle_t id,
8044 bool systemReady,
8045 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008046 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008047{
8048}
8049
Andy Hungee58e4a2023-07-07 13:47:37 -07008050void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008051 // if mSupportedLatencyModes is empty, the HAL stream does not support
8052 // latency mode control and we can exit.
8053 if (mSupportedLatencyModes.empty()) {
8054 return;
8055 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008056 // Do not update the HAL latency mode if no track is active
8057 if (mActiveTracks.isEmpty()) {
8058 return;
8059 }
8060
Eric Laurent68a40a82022-05-03 18:15:04 +02008061 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8062 if (mSupportedLatencyModes.size() == 1) {
8063 // If the HAL only support one latency mode currently, confirm the choice
8064 latencyMode = mSupportedLatencyModes[0];
8065 } else if (mSupportedLatencyModes.size() > 1) {
8066 // Request low latency if:
8067 // - The low latency mode is requested by the spatializer controller
8068 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8069 // AND
8070 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008071 for (const auto& track : mActiveTracks) {
8072 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008073 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008074 break;
8075 }
8076 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008077 }
8078
8079 if (latencyMode != mSetLatencyMode) {
8080 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008081 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8082 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008083 if (status == NO_ERROR) {
8084 mSetLatencyMode = latencyMode;
8085 }
8086 }
8087}
8088
Andy Hungee58e4a2023-07-07 13:47:37 -07008089status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008090 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008091 return BAD_VALUE;
8092 }
Andy Hung972bec12023-08-31 16:13:39 -07008093 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008094 mRequestedLatencyMode = mode;
8095 return NO_ERROR;
8096}
8097
Andy Hungee58e4a2023-07-07 13:47:37 -07008098void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008099NO_THREAD_SAFETY_ANALYSIS
8100// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008101{
8102 bool hasVirtualizer = false;
8103 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008104 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008105 {
Andy Hung972bec12023-08-31 16:13:39 -07008106 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008107 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008108 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008109 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008110 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8111 }
8112
8113 finalDownMixer = mFinalDownMixer;
8114 mFinalDownMixer.clear();
8115 }
8116
8117 if (hasVirtualizer) {
8118 if (finalDownMixer != nullptr) {
8119 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008120 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008121 }
8122 finalDownMixer.clear();
8123 } else if (!hasDownMixer) {
8124 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008125 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008126 EFFECT_UIID_DOWNMIX, &descriptors);
8127 if (status != NO_ERROR) {
8128 return;
8129 }
8130 ALOG_ASSERT(!descriptors.empty(),
8131 "%s getDescriptors() returned no error but empty list", __func__);
8132
8133 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8134 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008135 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008136
8137 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8138 ALOGW("%s error creating downmixer %d", __func__, status);
8139 finalDownMixer.clear();
8140 } else {
8141 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008142 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008143 }
8144 }
8145
8146 {
Andy Hung972bec12023-08-31 16:13:39 -07008147 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008148 mFinalDownMixer = finalDownMixer;
8149 }
8150}
8151
Andy Hunge2514462023-12-06 14:59:24 -08008152void SpatializerThread::threadLoop_exit()
8153{
8154 // The Spatializer EffectHandle must be released on the PlaybackThread
8155 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8156 mFinalDownMixer.clear();
8157
8158 PlaybackThread::threadLoop_exit();
8159}
8160
Eric Laurent81784c32012-11-19 14:55:58 -08008161// ----------------------------------------------------------------------------
8162// Record
8163// ----------------------------------------------------------------------------
8164
Andy Hung583043b2023-07-17 17:05:00 -07008165sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008166 AudioStreamIn* input,
8167 audio_io_handle_t id,
8168 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008169 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008170}
8171
Andy Hung583043b2023-07-17 17:05:00 -07008172RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008173 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008174 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008175 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008176 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008177 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008178 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008179 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008180 mActiveTracks(&this->mLocalLog),
8181 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008182 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008183 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008184 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8185 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008186 // mFastCapture below
8187 , mFastCaptureFutex(0)
8188 // mInputSource
8189 // mPipeSink
8190 // mPipeSource
8191 , mPipeFramesP2(0)
8192 // mPipeMemory
8193 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008194 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008195 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008196{
Glenn Kastend7dca052015-03-05 16:05:54 -08008197 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008198 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008199
George Burgess IVa8f90c12020-05-14 11:27:19 -07008200 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008201 mIsMsdDevice = strcmp(
8202 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8203 }
8204
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008205 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008206
Andy Hungc8fddf32018-08-08 18:32:37 -07008207 // TODO: We may also match on address as well as device type for
8208 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008209 // TODO: This property should be ensure that only contains one single device type.
8210 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8211 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008212 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8213 : AUDIO_DEVICE_NONE));
8214
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008215 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008216 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008217 size_t numCounterOffers = 0;
8218 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008219#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008220 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008221#else
8222 (void)
8223#endif
8224 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008225 ALOG_ASSERT(index == 0);
8226
8227 // initialize fast capture depending on configuration
8228 bool initFastCapture;
8229 switch (kUseFastCapture) {
8230 case FastCapture_Never:
8231 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008232 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008233 break;
8234 case FastCapture_Always:
8235 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008236 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008237 break;
8238 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008239 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008240 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008241 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008242 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8243 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8244 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008245 break;
8246 // case FastCapture_Dynamic:
8247 }
8248
8249 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008250 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008251 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008252 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8253 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008254 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008255 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008256 const sp<MemoryDealer> roHeap(readOnlyHeap());
8257 sp<IMemory> pipeMemory;
8258 if ((roHeap == 0) ||
8259 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008260 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008261 ALOGE("not enough memory for pipe buffer size=%zu; "
8262 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8263 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8264 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008265 goto failed;
8266 }
8267 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8268 memset(pipeBuffer, 0, pipeSize);
8269 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008270 const NBAIO_Format offersFast[1] = {format};
8271 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008272 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008273 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008274 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008275 mPipeSink = pipe;
8276 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008277 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008278 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008279 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008280 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008281 mPipeSource = pipeReader;
8282 mPipeFramesP2 = pipeFramesP2;
8283 mPipeMemory = pipeMemory;
8284
8285 // create fast capture
8286 mFastCapture = new FastCapture();
8287 FastCaptureStateQueue *sq = mFastCapture->sq();
8288#ifdef STATE_QUEUE_DUMP
8289 // FIXME
8290#endif
8291 FastCaptureState *state = sq->begin();
8292 state->mCblk = NULL;
8293 state->mInputSource = mInputSource.get();
8294 state->mInputSourceGen++;
8295 state->mPipeSink = pipe;
8296 state->mPipeSinkGen++;
8297 state->mFrameCount = mFrameCount;
8298 state->mCommand = FastCaptureState::COLD_IDLE;
8299 // already done in constructor initialization list
8300 //mFastCaptureFutex = 0;
8301 state->mColdFutexAddr = &mFastCaptureFutex;
8302 state->mColdGen++;
8303 state->mDumpState = &mFastCaptureDumpState;
8304#ifdef TEE_SINK
8305 // FIXME
8306#endif
Andy Hung583043b2023-07-17 17:05:00 -07008307 mFastCaptureNBLogWriter =
8308 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008309 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8310 sq->end();
8311 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8312
8313 // start the fast capture
8314 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8315 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008316 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008317 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008318#ifdef AUDIO_WATCHDOG
8319 // FIXME
8320#endif
8321
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008322 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008323 }
Andy Hung8946a282018-04-19 20:04:56 -07008324#ifdef TEE_SINK
8325 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8326 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8327#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008328failed: ;
8329
8330 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008331}
8332
Andy Hungee58e4a2023-07-07 13:47:37 -07008333RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008334{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008335 if (mFastCapture != 0) {
8336 FastCaptureStateQueue *sq = mFastCapture->sq();
8337 FastCaptureState *state = sq->begin();
8338 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8339 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8340 if (old == -1) {
8341 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8342 }
8343 }
8344 state->mCommand = FastCaptureState::EXIT;
8345 sq->end();
8346 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8347 mFastCapture->join();
8348 mFastCapture.clear();
8349 }
Andy Hung583043b2023-07-17 17:05:00 -07008350 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8351 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008352 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008353}
8354
Andy Hungee58e4a2023-07-07 13:47:37 -07008355void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008356{
Glenn Kastend7dca052015-03-05 16:05:54 -08008357 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008358}
8359
Andy Hungee58e4a2023-07-07 13:47:37 -07008360void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008361{
8362 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008363 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008364 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008365 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008366 track->invalidate();
8367 }
8368 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008369 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008370}
8371
Andy Hungee58e4a2023-07-07 13:47:37 -07008372bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008373{
Eric Laurent81784c32012-11-19 14:55:58 -08008374 nsecs_t lastWarning = 0;
8375
8376 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008377
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008378reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008379 {
Andy Hung972bec12023-08-31 16:13:39 -07008380 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008381 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008382 }
8383
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008384 // used to request a deferred sleep, to be executed later while mutex is unlocked
8385 uint32_t sleepUs = 0;
8386
Andy Hung95c94a22023-10-20 16:41:18 -07008387 // timestamp correction enable is determined under lock, used in processing step.
8388 bool timestampCorrectionEnabled = false;
8389
Andy Hung446f4df2019-02-21 12:26:41 -08008390 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8391
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008392 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008393 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008394 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8395 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008396 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008397 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008398
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008399 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008400 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008401
Glenn Kasten735f45f2014-08-18 15:51:59 -07008402 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008403 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008404
Glenn Kasten735f45f2014-08-18 15:51:59 -07008405 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008406 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008407
Eric Laurent33403f02020-05-29 18:35:06 -07008408 bool silenceFastCapture = false;
8409
Andy Hungc5007f82023-08-29 14:26:09 -07008410 { // scope for mutex()
8411 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008412
Eric Laurent021cf962014-05-13 10:18:14 -07008413 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008414
Eric Laurent000a4192014-01-29 15:17:32 -08008415 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008416 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008417 if (exitPending()) {
8418 break;
8419 }
8420
Eric Laurent5c25d562016-07-13 17:17:45 -07008421 // sleep with mutex unlocked
8422 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008423 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008424 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008425 ATRACE_END();
8426 sleepUs = 0;
8427 continue;
8428 }
8429
Glenn Kasten2b806402013-11-20 16:37:38 -08008430 // if no active track(s), then standby and release wakelock
8431 size_t size = mActiveTracks.size();
8432 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008433 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008434 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008435 releaseWakeLock_l();
8436 ALOGV("RecordThread: loop stopping");
8437 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008438 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008439 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008440 goto reacquire_wakelock;
8441 }
8442
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008443 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008444 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008445 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008446 if (activeTrack) { // ensure track release is outside lock.
8447 oldActiveTracks.emplace_back(std::move(activeTrack));
8448 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008449 activeTrack = mActiveTracks[i];
8450 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008451 if (activeTrack->isFastTrack()) {
8452 ALOG_ASSERT(fastTrackToRemove == 0);
8453 fastTrackToRemove = activeTrack;
8454 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008455 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008456 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008457 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008458 continue;
8459 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008460
Andy Hung8d31fd22023-06-26 19:20:57 -07008461 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008462 switch (activeTrackState) {
8463
Andy Hung8d31fd22023-06-26 19:20:57 -07008464 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008465 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008466 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008467 if (activeTrack->isFastTrack()) {
8468 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8469 // Keep a ref on fast track to wait for FastCapture thread to get updated
8470 // state before potential track removal
8471 fastTrackToRemove = activeTrack;
8472 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008473 doBroadcast = true;
8474 size--;
8475 continue;
8476
Andy Hung8d31fd22023-06-26 19:20:57 -07008477 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008478 sleepUs = 10000;
8479 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008480 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008481 continue;
8482
Andy Hung8d31fd22023-06-26 19:20:57 -07008483 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008485 if (mStandby) {
8486 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008487 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008488 mStandby = false;
8489 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008490 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008491 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008492 break;
8493
Andy Hung8d31fd22023-06-26 19:20:57 -07008494 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008495 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008496 break;
8497
Andy Hung8d31fd22023-06-26 19:20:57 -07008498 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8499 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8500 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008501 default:
Andy Hungce685402018-10-05 17:23:27 -07008502 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8503 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008504 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008505
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008506 if (activeTrack->isFastTrack()) {
8507 ALOG_ASSERT(!mFastTrackAvail);
8508 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008509 // if the active fast track is silenced either:
8510 // 1) silence the whole capture from fast capture buffer if this is
8511 // the only active track
8512 // 2) invalidate this track: this will cause the client to reconnect and possibly
8513 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008514 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008515 if (activeTrack->isSilenced()) {
8516 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008517 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008518 } else {
8519 silenceFastCapture = true;
8520 }
8521 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008522 // Invalidate fast tracks if access to audio history is required as this is not
8523 // possible with fast tracks. Once the fast track has been invalidated, no new
8524 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8525 if (mMaxSharedAudioHistoryMs != 0) {
8526 invalidate = true;
8527 }
8528 if (invalidate) {
8529 activeTrack->invalidate();
8530 ALOG_ASSERT(fastTrackToRemove == 0);
8531 fastTrackToRemove = activeTrack;
8532 removeTrack_l(activeTrack);
8533 mActiveTracks.remove(activeTrack);
8534 size--;
8535 continue;
8536 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008537 fastTrack = activeTrack;
8538 }
Eric Laurent33403f02020-05-29 18:35:06 -07008539
8540 activeTracks.add(activeTrack);
8541 i++;
8542
Glenn Kasten9e982352013-08-14 14:39:50 -07008543 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008544
Andy Hungab65b182023-09-06 19:41:47 -07008545 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008546
Kevin Rocard069c2712018-03-29 19:09:14 -07008547 updateMetadata_l();
8548
Eric Laurent5c25d562016-07-13 17:17:45 -07008549 if (allStopped) {
8550 standbyIfNotAlreadyInStandby();
8551 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008552 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008553 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008554 }
8555
8556 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008557 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008558 if (sleepUs == 0) {
8559 sleepUs = kRecordThreadSleepUs;
8560 }
8561 continue;
8562 }
8563 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008564
Andy Hung95c94a22023-10-20 16:41:18 -07008565 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008566 lockEffectChains_l(effectChains);
8567 }
8568
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008569 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008570
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008571 size_t size = effectChains.size();
8572 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008573 // thread mutex is not locked, but effect chain is locked
8574 effectChains[i]->process_l();
8575 }
8576
Glenn Kasten735f45f2014-08-18 15:51:59 -07008577 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008578 if (mFastCapture != 0) {
8579 FastCaptureStateQueue *sq = mFastCapture->sq();
8580 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008581 bool didModify = false;
8582 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008583 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8584 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8585 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8586 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8587 if (old == -1) {
8588 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8589 }
8590 }
8591 state->mCommand = FastCaptureState::READ_WRITE;
8592#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008593 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008594 FastThreadDumpState::kSamplingNforLowRamDevice :
8595 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008596#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008597 didModify = true;
8598 }
8599 audio_track_cblk_t *cblkOld = state->mCblk;
8600 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8601 if (cblkNew != cblkOld) {
8602 state->mCblk = cblkNew;
8603 // block until acked if removing a fast track
8604 if (cblkOld != NULL) {
8605 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8606 }
8607 didModify = true;
8608 }
jiabin01c8f562018-07-19 17:47:28 -07008609 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8610 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8611 if (state->mFastPatchRecordBufferProvider != abp) {
8612 state->mFastPatchRecordBufferProvider = abp;
8613 state->mFastPatchRecordFormat = fastTrack == 0 ?
8614 AUDIO_FORMAT_INVALID : fastTrack->format();
8615 didModify = true;
8616 }
Eric Laurent33403f02020-05-29 18:35:06 -07008617 if (state->mSilenceCapture != silenceFastCapture) {
8618 state->mSilenceCapture = silenceFastCapture;
8619 didModify = true;
8620 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008621 sq->end(didModify);
8622 if (didModify) {
8623 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008624#if 0
8625 if (kUseFastCapture == FastCapture_Dynamic) {
8626 mNormalSource = mPipeSource;
8627 }
8628#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008629 }
8630 }
8631
Glenn Kasten735f45f2014-08-18 15:51:59 -07008632 // now run the fast track destructor with thread mutex unlocked
8633 fastTrackToRemove.clear();
8634
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008635 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8636 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8637 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8638 // If destination is non-contiguous, first read past the nominal end of buffer, then
8639 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008640
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008641 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008642 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008643 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008644
8645 // If an NBAIO source is present, use it to read the normal capture's data
8646 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008647 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008648
8649 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8650 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8651 // we immediately retry the read() to get data and prevent another overflow.
8652 for (int retries = 0; retries <= 2; ++retries) {
8653 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8654 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8655 framesToRead);
8656 if (framesRead != OVERRUN) break;
8657 }
8658
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008659 const ssize_t availableToRead = mPipeSource->availableToRead();
8660 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008661 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008662 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008663 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8664 "more frames to read than fifo size, %zd > %zu",
8665 availableToRead, mPipeFramesP2);
8666 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8667 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8668 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8669 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008670 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8671 }
8672 if (framesRead < 0) {
8673 status_t status = (status_t) framesRead;
8674 switch (status) {
8675 case OVERRUN:
8676 ALOGW("overrun on read from pipe");
8677 framesRead = 0;
8678 break;
8679 case NEGOTIATE:
8680 ALOGE("re-negotiation is needed");
8681 framesRead = -1; // Will cause an attempt to recover.
8682 break;
8683 default:
8684 ALOGE("unknown error %d on read from pipe", status);
8685 break;
8686 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008687 }
8688 // otherwise use the HAL / AudioStreamIn directly
8689 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008690 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008691 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008692 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008693 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008694 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008695 if (result < 0) {
8696 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008697 } else {
8698 framesRead = bytesRead / mFrameSize;
8699 }
8700 }
8701
Andy Hung446f4df2019-02-21 12:26:41 -08008702 const int64_t lastIoEndNs = systemTime(); // end IO timing
8703
Andy Hung3f0c9022016-01-15 17:49:46 -08008704 // Update server timestamp with server stats
8705 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008706 if (framesRead >= 0) {
8707 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8708 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8709 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008710
8711 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008712 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008713 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008714 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008715 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8716 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8717 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008718 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008719 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8720
8721 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008722 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008723 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008724 id(), (long long)time, (long long)position);
8725 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8726 position = correctedTimestamp.mFrames;
8727 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008728 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008729 id(), (long long)time, (long long)position);
8730 }
8731
Andy Hung3f0c9022016-01-15 17:49:46 -08008732 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8733 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8734 // Note: In general record buffers should tend to be empty in
8735 // a properly running pipeline.
8736 //
8737 // Also, it is not advantageous to call get_presentation_position during the read
8738 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008739 } else {
8740 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008741 }
8742 }
Andy Hunge6c37112019-02-26 17:38:10 -08008743
8744 // From the timestamp, input read latency is negative output write latency.
8745 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008746 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008747 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8748 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8749 mLatencyMs.add(latencyMs);
8750 }
8751
Andy Hung3f0c9022016-01-15 17:49:46 -08008752 // Use this to track timestamp information
8753 // ALOGD("%s", mTimestamp.toString().c_str());
8754
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008755 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008756 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008757 // Force input into standby so that it tries to recover at next read attempt
8758 inputStandBy();
8759 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008760 }
8761 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008762 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008763 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008764 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008765 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008766
Andy Hung8946a282018-04-19 20:04:56 -07008767#ifdef TEE_SINK
8768 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8769#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008770 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008771 {
8772 size_t part1 = mRsmpInFramesP2 - rear;
8773 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008774 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008775 (framesRead - part1) * mFrameSize);
8776 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008777 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008778 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008779
8780 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008781
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008782 // loop over each active track
8783 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008784 if (activeTrack) { // ensure track release is outside lock.
8785 oldActiveTracks.emplace_back(std::move(activeTrack));
8786 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008787 activeTrack = activeTracks[i];
8788
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008789 // skip fast tracks, as those are handled directly by FastCapture
8790 if (activeTrack->isFastTrack()) {
8791 continue;
8792 }
8793
Andy Hung73c02e42015-03-29 01:13:58 -07008794 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008795 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8796
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008797 enum {
8798 OVERRUN_UNKNOWN,
8799 OVERRUN_TRUE,
8800 OVERRUN_FALSE
8801 } overrun = OVERRUN_UNKNOWN;
8802
8803 // loop over getNextBuffer to handle circular sink
8804 for (;;) {
8805
Andy Hung8d31fd22023-06-26 19:20:57 -07008806 activeTrack->sinkBuffer().frameCount = ~0;
8807 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8808 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008809 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8810
Andy Hung73c02e42015-03-29 01:13:58 -07008811 // check available frames and handle overrun conditions
8812 // if the record track isn't draining fast enough.
8813 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008814 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008815 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008816 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008817 overrun = OVERRUN_TRUE;
8818 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008819 if (framesOut == 0 || framesIn == 0) {
8820 break;
8821 }
8822
Andy Hung6770c6f2015-04-07 13:43:36 -07008823 // Don't allow framesOut to be larger than what is possible with resampling
8824 // from framesIn.
8825 // This isn't strictly necessary but helps limit buffer resizing in
8826 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008827 if (audio_is_linear_pcm(activeTrack->format())) {
8828 framesOut = min(framesOut,
8829 destinationFramesPossible(
8830 framesIn, mSampleRate, activeTrack->sampleRate()));
8831 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008832
8833 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008834 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008835 // straight from RecordThread buffer to RecordTrack buffer.
8836 AudioBufferProvider::Buffer buffer;
8837 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008838 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008839 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008840 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008841 ALOGV_IF(buffer.frameCount != framesOut,
8842 "%s() read less than expected (%zu vs %zu)",
8843 __func__, buffer.frameCount, framesOut);
8844 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008845 memcpy(activeTrack->sinkBuffer().raw,
8846 buffer.raw, buffer.frameCount * mFrameSize);
8847 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008848 } else {
8849 framesOut = 0;
8850 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008851 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008852 }
8853 } else {
8854 // process frames from the RecordThread buffer provider to the RecordTrack
8855 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008856 framesOut = activeTrack->recordBufferConverter()->convert(
8857 activeTrack->sinkBuffer().raw,
8858 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008859 framesOut);
8860 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008861
8862 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8863 overrun = OVERRUN_FALSE;
8864 }
8865
Andy Hung93bb5732023-05-04 21:16:34 -07008866 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8867 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008868 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008869 if (framesToDrop == 0) {
8870 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008871 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008872 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008873 // Sanitize before releasing if the track has no access to the source data
8874 // An idle UID receives silence from non virtual devices until active
8875 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008876 memset(activeTrack->sinkBuffer().raw,
8877 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008878 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008879 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008880 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008881 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008882 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008883 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008884 }
8885 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008886
8887 switch (overrun) {
8888 case OVERRUN_TRUE:
8889 // client isn't retrieving buffers fast enough
8890 if (!activeTrack->setOverflow()) {
8891 nsecs_t now = systemTime();
8892 // FIXME should lastWarning per track?
8893 if ((now - lastWarning) > kWarningThrottleNs) {
8894 ALOGW("RecordThread: buffer overflow");
8895 lastWarning = now;
8896 }
8897 }
8898 break;
8899 case OVERRUN_FALSE:
8900 activeTrack->clearOverflow();
8901 break;
8902 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008903 break;
8904 }
8905
Andy Hung3f0c9022016-01-15 17:49:46 -08008906 // update frame information and push timestamp out
8907 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008908 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008909 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8910 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008911 }
8912
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008913unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008914 // enable changes in effect chain
8915 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008916 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008917 if (audio_has_proportional_frames(mFormat)
8918 && loopCount == lastLoopCountRead + 1) {
8919 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8920 const double jitterMs =
8921 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8922 {framesRead, readPeriodNs},
8923 {0, 0} /* lastTimestamp */, mSampleRate);
8924 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8925
Andy Hung972bec12023-08-31 16:13:39 -07008926 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008927 mIoJitterMs.add(jitterMs);
8928 mProcessTimeMs.add(processMs);
8929 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008930 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008931 // update timing info.
8932 mLastIoBeginNs = lastIoBeginNs;
8933 mLastIoEndNs = lastIoEndNs;
8934 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008935 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008936 mThreadloopExecutor.process(); // process any remaining deferred actions.
8937 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008938
Glenn Kasten93e471f2013-08-19 08:40:07 -07008939 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008940
8941 {
Andy Hung972bec12023-08-31 16:13:39 -07008942 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008943 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008944 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008945 track->invalidate();
8946 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008947 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008948 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008949 }
8950
8951 releaseWakeLock();
8952
8953 ALOGV("RecordThread %p exiting", this);
8954 return false;
8955}
8956
Andy Hungee58e4a2023-07-07 13:47:37 -07008957void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008958{
8959 if (!mStandby) {
8960 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008961 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008962 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008963 mStandby = true;
8964 }
8965}
8966
Andy Hungee58e4a2023-07-07 13:47:37 -07008967void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008968{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008969 // Idle the fast capture if it's currently running
8970 if (mFastCapture != 0) {
8971 FastCaptureStateQueue *sq = mFastCapture->sq();
8972 FastCaptureState *state = sq->begin();
8973 if (!(state->mCommand & FastCaptureState::IDLE)) {
8974 state->mCommand = FastCaptureState::COLD_IDLE;
8975 state->mColdFutexAddr = &mFastCaptureFutex;
8976 state->mColdGen++;
8977 mFastCaptureFutex = 0;
8978 sq->end();
8979 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8980 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8981#if 0
8982 if (kUseFastCapture == FastCapture_Dynamic) {
8983 // FIXME
8984 }
8985#endif
8986#ifdef AUDIO_WATCHDOG
8987 // FIXME
8988#endif
8989 } else {
8990 sq->end(false /*didModify*/);
8991 }
8992 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008993 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008994 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008995
8996 // If going into standby, flush the pipe source.
8997 if (mPipeSource.get() != nullptr) {
8998 const ssize_t flushed = mPipeSource->flush();
8999 if (flushed > 0) {
9000 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
9001 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
9002 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
9003 }
9004 }
Eric Laurent81784c32012-11-19 14:55:58 -08009005}
9006
Andy Hungc5007f82023-08-29 14:26:09 -07009007// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009008sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07009009 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009010 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009011 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08009012 audio_format_t format,
9013 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08009014 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08009015 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009016 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009017 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00009018 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07009019 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08009020 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08009021 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009022 audio_port_handle_t portId,
9023 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009024{
Glenn Kasten74935e42013-12-19 08:56:45 -08009025 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009026 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009027 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009028 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009029 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009030 audio_input_flags_t requestedFlags = *flags;
9031 uint32_t sampleRate;
9032
9033 lStatus = initCheck();
9034 if (lStatus != NO_ERROR) {
9035 ALOGE("createRecordTrack_l() audio driver not initialized");
9036 goto Exit;
9037 }
9038
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009039 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9040 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9041 lStatus = BAD_VALUE;
9042 goto Exit;
9043 }
9044
Eric Laurentec376dc2021-04-08 20:41:22 +02009045 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009046 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009047 lStatus = PERMISSION_DENIED;
9048 goto Exit;
9049 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009050 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009051 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009052 lStatus = BAD_VALUE;
9053 goto Exit;
9054 }
9055 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009056 if (*pSampleRate == 0) {
9057 *pSampleRate = mSampleRate;
9058 }
9059 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009060
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009061 // special case for FAST flag considered OK if fast capture is present and access to
9062 // audio history is not required
9063 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009064 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9065 }
9066
Eric Laurentf14db3c2017-12-08 14:20:36 -08009067 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009068 if ((*flags & inputFlags) != *flags) {
9069 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9070 " input flags (%08x)",
9071 *flags, inputFlags);
9072 *flags = (audio_input_flags_t)(*flags & inputFlags);
9073 }
Eric Laurent81784c32012-11-19 14:55:58 -08009074
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009075 // client expresses a preference for FAST and no access to audio history,
9076 // but we get the final say
9077 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009078 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009079 // we formerly checked for a callback handler (non-0 tid),
9080 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009081 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009082 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009083 // Frame count is not specified (0), or is less than or equal the pipe depth.
9084 // It is OK to provide a higher capacity than requested.
9085 // We will force it to mPipeFramesP2 below.
9086 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009087 // PCM data
9088 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009089 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009090 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009091 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009092 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009093 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009094 hasFastCapture() &&
9095 // there are sufficient fast track slots available
9096 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009097 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009098 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009099 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009100 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009101 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009102 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009103 audio_input_flags_t old = *flags;
9104 chain->checkInputFlagCompatibility(flags);
9105 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009106 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9107 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009108 }
9109 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009110 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009111 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9112 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009113 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009114 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9115 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009116 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009117 this, frameCount, mFrameCount, mPipeFramesP2,
9118 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009119 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009120 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009121 }
9122 }
9123
Eric Laurentf14db3c2017-12-08 14:20:36 -08009124 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9125 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9126 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9127 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9128 lStatus = BAD_TYPE;
9129 goto Exit;
9130 }
9131
Glenn Kasten74105912014-07-03 12:28:53 -07009132 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009133 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009134 // fast track: frame count is exactly the pipe depth
9135 frameCount = mPipeFramesP2;
9136 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009137 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009138 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009139 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9140 // or 20 ms if there is a fast capture
9141 // TODO This could be a roundupRatio inline, and const
9142 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9143 * sampleRate + mSampleRate - 1) / mSampleRate;
9144 // minimum number of notification periods is at least kMinNotifications,
9145 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9146 static const size_t kMinNotifications = 3;
9147 static const uint32_t kMinMs = 30;
9148 // TODO This could be a roundupRatio inline
9149 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9150 // TODO This could be a roundupRatio inline
9151 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9152 maxNotificationFrames;
9153 const size_t minFrameCount = maxNotificationFrames *
9154 max(kMinNotifications, minNotificationsByMs);
9155 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009156 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9157 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009158 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009159 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009160 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009161 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009162
Andy Hungc5007f82023-08-29 14:26:09 -07009163 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009164 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009165 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009166 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009167 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009168 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009169 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009170 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009171 }
Eric Laurent81784c32012-11-19 14:55:58 -08009172
Andy Hung8d31fd22023-06-26 19:20:57 -07009173 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009174 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009175 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009176 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009177 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009178
Glenn Kasten03003332013-08-06 15:40:54 -07009179 lStatus = track->initCheck();
9180 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009181 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009182 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009183 goto Exit;
9184 }
9185 mTracks.add(track);
9186
Eric Laurent05067782016-06-01 18:27:28 -07009187 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009188 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9189 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9190 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009191 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009192 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009193
9194 if (maxSharedAudioHistoryMs != 0) {
9195 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9196 }
Eric Laurent81784c32012-11-19 14:55:58 -08009197 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009198
Eric Laurent81784c32012-11-19 14:55:58 -08009199 lStatus = NO_ERROR;
9200
9201Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009202 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009203 return track;
9204}
9205
Andy Hungee58e4a2023-07-07 13:47:37 -07009206status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009207 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009208 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009209{
9210 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9211 sp<ThreadBase> strongMe = this;
9212 status_t status = NO_ERROR;
9213
9214 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009215 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009216 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009217 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009218 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009219 event, triggerSession,
9220 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009221 }
9222
9223 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009224 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009225 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009226 if (recordTrack->isInvalid()) {
9227 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009228 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9229 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009230 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009231 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009232 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009233 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9234 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009235 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009236 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009237 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009238 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009239 }
9240 return status;
9241 }
9242
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009243 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9244 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9245 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009246 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009247 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009248 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009249 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009250 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009251 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009252 if (recordTrack->isInvalid()) {
9253 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009254 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9255 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009256 // STARTING_2 forces destroy to call stopInput.
9257 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009258 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9259 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009260 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009261 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009262 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009263 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009264 // Someone else has changed state, let them take over,
9265 // leave mState in the new state.
9266 recordTrack->clearSyncStartEvent();
9267 return INVALID_OPERATION;
9268 }
9269 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009270 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009271 ALOGW("%s(%d): startInput failed, status %d",
9272 __func__, recordTrack->id(), status);
9273 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9274 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009275 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009276 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009277 return status;
9278 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009279 sendIoConfigEvent_l(
9280 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009281 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009282
9283 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9284
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009285 // Catch up with current buffer indices if thread is already running.
9286 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9287 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9288 // see previously buffered data before it called start(), but with greater risk of overrun.
9289
Andy Hung8d31fd22023-06-26 19:20:57 -07009290 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009291 if (!recordTrack->isDirect()) {
9292 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009293 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009294 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009295 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009296 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009297 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009298 return status;
9299 }
Eric Laurent81784c32012-11-19 14:55:58 -08009300}
9301
Andy Hungee58e4a2023-07-07 13:47:37 -07009302void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009303{
Andy Hungee58e4a2023-07-07 13:47:37 -07009304 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009305
9306 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009307 sp<IAfTrackBase> ptr =
9308 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9309 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009310 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009311 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009312 }
Eric Laurent81784c32012-11-19 14:55:58 -08009313 }
9314}
9315
Andy Hungee58e4a2023-07-07 13:47:37 -07009316bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009317 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009318 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009319 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009320 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009321 return false;
9322 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009323 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009324 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009325
Andy Hungabfab202019-03-07 19:45:54 -08009326 // NOTE: Waiting here is important to keep stop synchronous.
9327 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009328 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009329 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009330 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009331 }
Andy Hungce685402018-10-05 17:23:27 -07009332
Andy Hung8d31fd22023-06-26 19:20:57 -07009333 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009334 ALOGV("Record stopped OK");
9335 return true;
9336 }
Andy Hungce685402018-10-05 17:23:27 -07009337
9338 // don't handle anything - we've been invalidated or restarted and in a different state
9339 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009340 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009341 return false;
9342}
9343
Andy Hungee58e4a2023-07-07 13:47:37 -07009344bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009345{
9346 return false;
9347}
9348
Andy Hungee58e4a2023-07-07 13:47:37 -07009349status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009350{
9351#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9352 if (!isValidSyncEvent(event)) {
9353 return BAD_VALUE;
9354 }
9355
Glenn Kastend848eb42016-03-08 13:42:11 -08009356 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009357 status_t ret = NAME_NOT_FOUND;
9358
Andy Hung972bec12023-08-31 16:13:39 -07009359 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009360
9361 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009362 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009363 if (eventSession == track->sessionId()) {
9364 (void) track->setSyncEvent(event);
9365 ret = NO_ERROR;
9366 }
9367 }
9368 return ret;
9369#else
9370 return BAD_VALUE;
9371#endif
9372}
9373
Andy Hungee58e4a2023-07-07 13:47:37 -07009374status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009375 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009376{
9377 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009378 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009379 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009380 return NO_INIT;
9381 }
jiabin9ff780e2018-03-19 18:19:52 -07009382 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9383 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009384}
9385
Andy Hungee58e4a2023-07-07 13:47:37 -07009386status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009387 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009388{
Paul McLean12340082019-03-19 09:35:05 -06009389 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009390 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009391 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009392 return NO_INIT;
9393 }
Paul McLean12340082019-03-19 09:35:05 -06009394 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009395}
9396
Andy Hungee58e4a2023-07-07 13:47:37 -07009397status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009398{
Paul McLean12340082019-03-19 09:35:05 -06009399 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009400 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009401 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009402 return NO_INIT;
9403 }
Paul McLean12340082019-03-19 09:35:05 -06009404 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009405}
9406
Andy Hungee58e4a2023-07-07 13:47:37 -07009407status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009408 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9409 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009410 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009411 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9412}
9413
Andy Hungee58e4a2023-07-07 13:47:37 -07009414status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009415 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9416 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009417
Eric Laurentec376dc2021-04-08 20:41:22 +02009418 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9419 return BAD_VALUE;
9420 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009421
9422 if (sharedAudioStartMs < 0
9423 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009424 return BAD_VALUE;
9425 }
9426
Eric Laurent2407ce32021-04-26 14:56:03 +02009427 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9428 // As we cannot detect more than one wraparound, only accept values up current write position
9429 // after one wraparound
9430 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9431 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009432 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009433 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9434 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009435 // Bring the start frame position within the input buffer to match the documented
9436 // "best effort" behavior of the API.
9437 if (sharedOffset < 0) {
9438 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009439 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009440 sharedAudioStartFrames =
9441 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009442 }
9443
Eric Laurentec376dc2021-04-08 20:41:22 +02009444 mSharedAudioPackageName = sharedAudioPackageName;
9445 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009446 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009447 } else {
9448 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009449 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009450 }
9451 return NO_ERROR;
9452}
9453
Andy Hungee58e4a2023-07-07 13:47:37 -07009454void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009455 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9456 mSharedAudioStartFrames = -1;
9457 mSharedAudioPackageName = "";
9458}
9459
Andy Hungee58e4a2023-07-07 13:47:37 -07009460ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009461{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009462 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009463 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009464 }
9465 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009466 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009467 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009468 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009469 }
9470 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009471 MetadataUpdate change;
9472 change.recordMetadataUpdate = metadata.tracks;
9473 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009474}
9475
Andy Hungc5007f82023-08-29 14:26:09 -07009476// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009477void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009478{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009479 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009480 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009481
Eric Laurent81784c32012-11-19 14:55:58 -08009482 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009483 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009484 removeTrack_l(track);
9485 }
9486}
9487
Andy Hungee58e4a2023-07-07 13:47:37 -07009488void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009489{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009490 String8 result;
9491 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009492 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009493
Eric Laurent81784c32012-11-19 14:55:58 -08009494 mTracks.remove(track);
9495 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009496 if (track->isFastTrack()) {
9497 ALOG_ASSERT(!mFastTrackAvail);
9498 mFastTrackAvail = true;
9499 }
Eric Laurent81784c32012-11-19 14:55:58 -08009500}
9501
Andy Hungee58e4a2023-07-07 13:47:37 -07009502void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009503{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009504 AudioStreamIn *input = mInput;
9505 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9506 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009507 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009508 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009509 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009510 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009511 }
Andy Hungbfa64962017-06-12 14:43:19 -07009512
9513 if (input != nullptr) {
9514 dprintf(fd, " Hal stream dump:\n");
9515 (void)input->stream->dump(fd);
9516 }
9517
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009518 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009519 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009520
Glenn Kasten2f90c512015-12-02 11:40:09 -08009521 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9522 // while we are dumping it. It may be inconsistent, but it won't mutate!
9523 // This is a large object so we place it on the heap.
9524 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009525 const std::unique_ptr<FastCaptureDumpState> copy =
9526 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009527 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009528}
9529
Andy Hungee58e4a2023-07-07 13:47:37 -07009530void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009531{
Eric Laurent81784c32012-11-19 14:55:58 -08009532 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009533 size_t numtracks = mTracks.size();
9534 size_t numactive = mActiveTracks.size();
9535 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009536 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009537 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009538 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009539 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009540 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009541 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009542 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009543 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009544 if (track != 0) {
9545 bool active = mActiveTracks.indexOf(track) >= 0;
9546 if (active) {
9547 numactiveseen++;
9548 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009549 result.append(prefix);
9550 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009551 }
Eric Laurent81784c32012-11-19 14:55:58 -08009552 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009553 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009554 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009555 }
9556
Marco Nelissenb2208842014-02-07 14:00:50 -08009557 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009558 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009559 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009560 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009561 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009562 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009563 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009564 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009565 result.append(prefix);
9566 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009567 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009568 }
Eric Laurent81784c32012-11-19 14:55:58 -08009569
9570 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009571 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009572}
9573
Andy Hungee58e4a2023-07-07 13:47:37 -07009574void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009575{
Andy Hung972bec12023-08-31 16:13:39 -07009576 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009577 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009578 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009579 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009580 track->setSilenced(silenced);
9581 }
9582 }
9583}
Andy Hung73c02e42015-03-29 01:13:58 -07009584
Andy Hung8d31fd22023-06-26 19:20:57 -07009585void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009586{
Andy Hung87c693c2023-07-06 20:56:16 -07009587 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009588 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009589 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009590 const int32_t rear = recordThread->mRsmpInRear;
9591 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009592 if (mRecordTrack->startFrames() >= 0) {
9593 int32_t startFrames = mRecordTrack->startFrames();
9594 // Accept a recent wraparound of mRsmpInRear
9595 if (startFrames <= rear) {
9596 deltaFrames = rear - startFrames;
9597 } else {
9598 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009599 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009600 // start frame cannot be further in the past than start of resampling buffer
9601 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9602 deltaFrames = recordThread->mRsmpInFrames;
9603 }
9604 }
9605 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009606}
9607
Andy Hung8d31fd22023-06-26 19:20:57 -07009608void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009609 size_t *framesAvailable, bool *hasOverrun)
9610{
Andy Hung87c693c2023-07-06 20:56:16 -07009611 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009612 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009613 const int32_t rear = recordThread->mRsmpInRear;
9614 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009615 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009616
9617 size_t framesIn;
9618 bool overrun = false;
9619 if (filled < 0) {
9620 // should not happen, but treat like a massive overrun and re-sync
9621 framesIn = 0;
9622 mRsmpInFront = rear;
9623 overrun = true;
9624 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9625 framesIn = (size_t) filled;
9626 } else {
9627 // client is not keeping up with server, but give it latest data
9628 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009629 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9630 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009631 overrun = true;
9632 }
9633 if (framesAvailable != NULL) {
9634 *framesAvailable = framesIn;
9635 }
9636 if (hasOverrun != NULL) {
9637 *hasOverrun = overrun;
9638 }
9639}
9640
Eric Laurent81784c32012-11-19 14:55:58 -08009641// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009642status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009643 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009644{
Andy Hung87c693c2023-07-06 20:56:16 -07009645 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009646 if (threadBase == 0) {
9647 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009648 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009649 return NOT_ENOUGH_DATA;
9650 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009651 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009652 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009653 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009654 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009655 // FIXME should not be P2 (don't want to increase latency)
9656 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009657 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009658 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009659
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009660 front &= recordThread->mRsmpInFramesP2 - 1;
9661 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009662 if (part1 > (size_t) filled) {
9663 part1 = filled;
9664 }
9665 size_t ask = buffer->frameCount;
9666 ALOG_ASSERT(ask > 0);
9667 if (part1 > ask) {
9668 part1 = ask;
9669 }
9670 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009671 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009672 buffer->raw = NULL;
9673 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009674 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009675 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009676 }
9677
Andy Hung57446612015-04-19 23:56:46 -07009678 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009679 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009680 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009681 return NO_ERROR;
9682}
9683
9684// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009685void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009686 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009687{
Hongwei Wang95e37682019-04-12 11:13:36 -07009688 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009689 if (stepCount == 0) {
9690 return;
9691 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009692 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009693 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009694 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009695 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009696 buffer->frameCount = 0;
9697}
9698
Andy Hungee58e4a2023-07-07 13:47:37 -07009699void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009700{
Andy Hung972bec12023-08-31 16:13:39 -07009701 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009702 checkBtNrec_l();
9703}
9704
Andy Hungee58e4a2023-07-07 13:47:37 -07009705void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009706{
9707 // disable AEC and NS if the device is a BT SCO headset supporting those
9708 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009709 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009710 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009711 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9712 for (size_t i = 0; i < mEffectChains.size(); i++) {
9713 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9714 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9715 }
9716 }
9717}
9718
Andy Hung97a893e2015-03-29 01:03:07 -07009719
Andy Hungee58e4a2023-07-07 13:47:37 -07009720bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009721 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009722{
9723 bool reconfig = false;
9724
Eric Laurent10351942014-05-08 18:49:52 -07009725 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009726
Eric Laurent10351942014-05-08 18:49:52 -07009727 audio_format_t reqFormat = mFormat;
9728 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009729 // 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 +08009730 [[maybe_unused]] audio_channel_mask_t channelMask =
9731 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009732
9733 AudioParameter param = AudioParameter(keyValuePair);
9734 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009735
9736 // scope for AutoPark extends to end of method
9737 AutoPark<FastCapture> park(mFastCapture);
9738
Eric Laurent10351942014-05-08 18:49:52 -07009739 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9740 // channel count change can be requested. Do we mandate the first client defines the
9741 // HAL sampling rate and channel count or do we allow changes on the fly?
9742 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9743 samplingRate = value;
9744 reconfig = true;
9745 }
9746 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009747 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009748 status = BAD_VALUE;
9749 } else {
9750 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009751 reconfig = true;
9752 }
Eric Laurent10351942014-05-08 18:49:52 -07009753 }
9754 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9755 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009756 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009757 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009758 status = BAD_VALUE;
9759 } else {
9760 channelMask = mask;
9761 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009762 }
Eric Laurent10351942014-05-08 18:49:52 -07009763 }
9764 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9765 // do not accept frame count changes if tracks are open as the track buffer
9766 // size depends on frame count and correct behavior would not be guaranteed
9767 // if frame count is changed after track creation
9768 if (mActiveTracks.size() > 0) {
9769 status = INVALID_OPERATION;
9770 } else {
9771 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009772 }
Eric Laurent10351942014-05-08 18:49:52 -07009773 }
9774 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009775 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009776 }
9777 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9778 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009779 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009780 }
Glenn Kastene198c362013-08-13 09:13:36 -07009781
Eric Laurent10351942014-05-08 18:49:52 -07009782 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009783 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009784 if (status == INVALID_OPERATION) {
9785 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009786 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009787 }
9788 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009789 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009790 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9791 if (mInput->stream->getAudioProperties(&config) == OK &&
9792 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9793 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009794 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009795 status = NO_ERROR;
9796 }
Eric Laurent81784c32012-11-19 14:55:58 -08009797 }
Eric Laurent10351942014-05-08 18:49:52 -07009798 if (status == NO_ERROR) {
9799 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009800 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009801 }
9802 }
Eric Laurent81784c32012-11-19 14:55:58 -08009803 }
Eric Laurent10351942014-05-08 18:49:52 -07009804
Eric Laurent81784c32012-11-19 14:55:58 -08009805 return reconfig;
9806}
9807
Andy Hungee58e4a2023-07-07 13:47:37 -07009808String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009809{
Andy Hung972bec12023-08-31 16:13:39 -07009810 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009811 if (initCheck() == NO_ERROR) {
9812 String8 out_s8;
9813 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9814 return out_s8;
9815 }
Eric Laurent81784c32012-11-19 14:55:58 -08009816 }
Andy Hung920f6572022-10-06 12:09:49 -07009817 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009818}
9819
Andy Hungab65b182023-09-06 19:41:47 -07009820void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009821 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009822 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009823 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009824 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009825 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009826 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009827 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9828 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009829 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009830 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009831 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009832 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009833 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009834 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009835 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009836 break;
9837 }
Andy Hungab65b182023-09-06 19:41:47 -07009838 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009839}
9840
Andy Hungee58e4a2023-07-07 13:47:37 -07009841void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009842{
Dean Wheatley6c009512023-10-23 09:34:14 +11009843 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9844 mSampleRate = audioConfig.sample_rate;
9845 mChannelMask = audioConfig.channel_mask;
9846 if (!audio_is_input_channel(mChannelMask)) {
9847 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9848 }
9849
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009850 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009851
9852 // Get actual HAL format.
9853 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9854 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9855 // Get format from the shim, which will be different than the HAL format
9856 // if recording compressed audio from IEC61937 wrapped sources.
9857 mFormat = audioConfig.format;
9858 if (!audio_is_valid_format(mFormat)) {
9859 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9860 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009861 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009862 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9863 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009864 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009865 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009866 ALOGI("HAL format %#x is not linear pcm", mFormat);
9867 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009868 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009869 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9870 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009871 result = mInput->stream->getBufferSize(&mBufferSize);
9872 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009873 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009874 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9875 "mBufferSize=%zu, mFrameCount=%zu",
9876 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009877
Eric Laurentec376dc2021-04-08 20:41:22 +02009878 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9879 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009880 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009881
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009882 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9883 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009884
9885 audio_input_flags_t flags = mInput->flags;
9886 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9887 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009888 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009889 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9890 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9891 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9892 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9893 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9894 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009895}
9896
Andy Hungee58e4a2023-07-07 13:47:37 -07009897uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009898{
Andy Hung972bec12023-08-31 16:13:39 -07009899 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009900 uint32_t result;
9901 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9902 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009903 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009904 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009905}
9906
Andy Hungee58e4a2023-07-07 13:47:37 -07009907KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009908{
Glenn Kastend848eb42016-03-08 13:42:11 -08009909 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009910 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009911 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009912 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009913 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009914 if (ids.indexOfKey(sessionId) < 0) {
9915 ids.add(sessionId, true);
9916 }
9917 }
9918 return ids;
9919}
9920
Andy Hungee58e4a2023-07-07 13:47:37 -07009921AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009922{
Andy Hung972bec12023-08-31 16:13:39 -07009923 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009924 AudioStreamIn *input = mInput;
9925 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009926 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009927 return input;
9928}
9929
Andy Hungc5007f82023-08-29 14:26:09 -07009930// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009931sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009932{
9933 if (mInput == NULL) {
9934 return NULL;
9935 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009936 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009937}
9938
Andy Hungee58e4a2023-07-07 13:47:37 -07009939status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009940{
Eric Laurent81784c32012-11-19 14:55:58 -08009941 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009942 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009943 chain->setInBuffer(NULL);
9944 chain->setOutBuffer(NULL);
9945
9946 checkSuspendOnAddEffectChain_l(chain);
9947
Eric Laurent1b928682014-10-02 19:41:47 -07009948 // make sure enabled pre processing effects state is communicated to the HAL as we
9949 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009950 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009951
Eric Laurent81784c32012-11-19 14:55:58 -08009952 mEffectChains.add(chain);
9953
9954 return NO_ERROR;
9955}
9956
Andy Hungee58e4a2023-07-07 13:47:37 -07009957size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009958{
9959 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009960
9961 for (size_t i = 0; i < mEffectChains.size(); i++) {
9962 if (chain == mEffectChains[i]) {
9963 mEffectChains.removeAt(i);
9964 break;
9965 }
Eric Laurent81784c32012-11-19 14:55:58 -08009966 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009967 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009968}
9969
Andy Hungee58e4a2023-07-07 13:47:37 -07009970status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009971 audio_patch_handle_t *handle)
9972{
9973 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009974
9975 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009976 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009977 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009978 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009979 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009980 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009981 }
9982
Eric Laurentd8365c52017-07-16 15:27:05 -07009983 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009984
9985 // store new source and send to effects
9986 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9987 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009988 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009989 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009990 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009991 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009992
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009993 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009994 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9995 status = hwDevice->createAudioPatch(patch->num_sources,
9996 patch->sources,
9997 patch->num_sinks,
9998 patch->sinks,
9999 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010000 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010001 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
10002 patch->sinks[0].ext.mix.usecase.source,
10003 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -070010004 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -070010005 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010006
jiabinc52b1ff2019-10-31 17:20:42 -070010007 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -070010008 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -070010009 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -070010010 }
Eric Laurent296fb132015-05-01 11:38:42 -070010011
Andy Hungc2b11cb2020-04-22 09:04:01 -070010012 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -070010013 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -070010014 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -070010015 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -070010016 // also dispatch to active AudioRecords
10017 for (const auto &track : mActiveTracks) {
10018 track->logEndInterval();
10019 track->logBeginInterval(pathSourcesAsString);
10020 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010021 // Force meteadata update after a route change
10022 mActiveTracks.setHasChanged();
10023
Eric Laurent1c333e22014-05-20 10:48:17 -070010024 return status;
10025}
10026
Andy Hungee58e4a2023-07-07 13:47:37 -070010027status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010028{
10029 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010030
jiabinc52b1ff2019-10-31 17:20:42 -070010031 mPatch = audio_patch{};
10032 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010033
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010034 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010035 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10036 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010037 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010038 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010039 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010040 // Force meteadata update after a route change
10041 mActiveTracks.setHasChanged();
10042
Eric Laurent1c333e22014-05-20 10:48:17 -070010043 return status;
10044}
10045
Andy Hungee58e4a2023-07-07 13:47:37 -070010046void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010047{
Andy Hung972bec12023-08-31 16:13:39 -070010048 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010049 mOutDevices = outDevices;
10050 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10051 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010052 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010053 }
10054}
10055
Andy Hungee58e4a2023-07-07 13:47:37 -070010056int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010057{
10058 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010059 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010060 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010061 int32_t oldestFront = mRsmpInRear;
10062 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010063 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010064 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010065 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010066 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010067 if (filled > maxFilled) {
10068 oldestFront = front;
10069 maxFilled = filled;
10070 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010071 }
Andy Hung920f6572022-10-06 12:09:49 -070010072 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010073 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10074 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010075 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010076}
10077
Andy Hungee58e4a2023-07-07 13:47:37 -070010078void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010079{
10080 if (offset == 0) {
10081 return;
10082 }
10083 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010084 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010085 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010086 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010087 }
10088}
10089
Andy Hungee58e4a2023-07-07 13:47:37 -070010090void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010091{
10092 // This is the formula for calculating the temporary buffer size.
10093 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10094 // 1 full output buffer, regardless of the alignment of the available input.
10095 // The value is somewhat arbitrary, and could probably be even larger.
10096 // A larger value should allow more old data to be read after a track calls start(),
10097 // without increasing latency.
10098 //
10099 // Note this is independent of the maximum downsampling ratio permitted for capture.
10100 size_t minRsmpInFrames = mFrameCount * 7;
10101
10102 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10103 // capture history available to another client using the same session ID:
10104 // dimension the resampler input buffer accordingly.
10105
10106 // Get oldest client read position: getOldestFront_l() must be called before altering
10107 // mRsmpInRear, or mRsmpInFrames
10108 int32_t previousFront = getOldestFront_l();
10109 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10110 int32_t previousRear = mRsmpInRear;
10111 mRsmpInRear = 0;
10112
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010113 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010114 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010115 "resizeInputBuffer_l() called with invalid max shared history %d",
10116 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010117 if (maxSharedAudioHistoryMs != 0) {
10118 // resizeInputBuffer_l should never be called with a non zero shared history if the
10119 // buffer was not already allocated
10120 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10121 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10122 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10123 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010124 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010125 return;
10126 }
10127 mRsmpInFrames = rsmpInFrames;
10128 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010129 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010130 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10131 // initialized
10132 if (mRsmpInFrames < minRsmpInFrames) {
10133 mRsmpInFrames = minRsmpInFrames;
10134 }
10135 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10136
10137 // TODO optimize audio capture buffer sizes ...
10138 // Here we calculate the size of the sliding buffer used as a source
10139 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10140 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10141 // be better to have it derived from the pipe depth in the long term.
10142 // The current value is higher than necessary. However it should not add to latency.
10143
10144 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10145 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10146
10147 void *rsmpInBuffer;
10148 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10149 // if posix_memalign fails, will segv here.
10150 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10151
10152 // Copy audio history if any from old buffer before freeing it
10153 if (previousRear != 0) {
10154 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10155 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10156
10157 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10158 previousFront &= previousRsmpInFramesP2 - 1;
10159 size_t part1 = previousRsmpInFramesP2 - previousFront;
10160 if (part1 > (size_t) unread) {
10161 part1 = unread;
10162 }
10163 if (part1 != 0) {
10164 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10165 part1 * mFrameSize);
10166 mRsmpInRear = part1;
10167 part1 = unread - part1;
10168 if (part1 != 0) {
10169 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10170 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10171 mRsmpInRear += part1;
10172 }
10173 }
10174 // Update front for all clients according to new rear
10175 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10176 } else {
10177 mRsmpInRear = 0;
10178 }
10179 free(mRsmpInBuffer);
10180 mRsmpInBuffer = rsmpInBuffer;
10181}
10182
Andy Hungee58e4a2023-07-07 13:47:37 -070010183void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010184{
Andy Hung972bec12023-08-31 16:13:39 -070010185 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010186 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010187 if (record->getSource()) {
10188 mSource = record->getSource();
10189 }
Eric Laurent83b88082014-06-20 18:31:16 -070010190}
10191
Andy Hungee58e4a2023-07-07 13:47:37 -070010192void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010193{
Andy Hung972bec12023-08-31 16:13:39 -070010194 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010195 if (mSource == record->getSource()) {
10196 mSource = mInput;
10197 }
Eric Laurent83b88082014-06-20 18:31:16 -070010198 destroyTrack_l(record);
10199}
10200
Andy Hungee58e4a2023-07-07 13:47:37 -070010201void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010202{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010203 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010204 config->role = AUDIO_PORT_ROLE_SINK;
10205 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10206 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010207 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10208 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10209 config->flags.input = mInput->flags;
10210 }
Eric Laurent83b88082014-06-20 18:31:16 -070010211}
Eric Laurent1c333e22014-05-20 10:48:17 -070010212
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213// ----------------------------------------------------------------------------
10214// Mmap
10215// ----------------------------------------------------------------------------
10216
Andy Hung7aa7d102023-07-07 15:58:48 -070010217// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10218// MmapPlaybackThread or MmapCaptureThread instance.
10219class MmapThreadHandle : public MmapStreamInterface {
10220public:
10221 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10222 ~MmapThreadHandle() override;
10223
10224 // MmapStreamInterface virtuals
10225 status_t createMmapBuffer(int32_t minSizeFrames,
10226 struct audio_mmap_buffer_info* info) final;
10227 status_t getMmapPosition(struct audio_mmap_position* position) final;
10228 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10229 status_t start(const AudioClient& client,
10230 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10231 status_t stop(audio_port_handle_t handle) final;
10232 status_t standby() final;
10233 status_t reportData(const void* buffer, size_t frameCount) final;
10234private:
10235 const sp<IAfMmapThread> mThread;
10236};
10237
10238/* static */
10239sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10240 const sp<IAfMmapThread>& mmapThread) {
10241 return sp<MmapThreadHandle>::make(mmapThread);
10242}
10243
10244MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010245 : mThread(thread)
10246{
Phil Burk9fabbf82017-08-03 12:02:00 -070010247 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010248}
10249
Andy Hung7aa7d102023-07-07 15:58:48 -070010250// MmapStreamInterface could be directly implemented by MmapThread excepting this
10251// special handling on adapter dtor.
10252MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253{
Phil Burk9fabbf82017-08-03 12:02:00 -070010254 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010255}
10256
Andy Hung7aa7d102023-07-07 15:58:48 -070010257status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 struct audio_mmap_buffer_info *info)
10259{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010260 return mThread->createMmapBuffer(minSizeFrames, info);
10261}
10262
Andy Hung7aa7d102023-07-07 15:58:48 -070010263status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010264{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265 return mThread->getMmapPosition(position);
10266}
10267
Andy Hung7aa7d102023-07-07 15:58:48 -070010268status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010269 int64_t *timeNanos) {
10270 return mThread->getExternalPosition(position, timeNanos);
10271}
10272
Andy Hung7aa7d102023-07-07 15:58:48 -070010273status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010274 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010275{
jiabind1f1cb62020-03-24 11:57:57 -070010276 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010277}
10278
Andy Hung7aa7d102023-07-07 15:58:48 -070010279status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010280{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010281 return mThread->stop(handle);
10282}
10283
Andy Hung7aa7d102023-07-07 15:58:48 -070010284status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010285{
Eric Laurent18b57012017-02-13 16:23:52 -080010286 return mThread->standby();
10287}
10288
Andy Hung7aa7d102023-07-07 15:58:48 -070010289status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10290{
jiabinfc791ee2023-02-15 19:43:40 +000010291 return mThread->reportData(buffer, frameCount);
10292}
10293
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294
Andy Hungee58e4a2023-07-07 13:47:37 -070010295MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010296 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010297 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010298 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010299 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010300 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010301 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010302 mActiveTracks(&this->mLocalLog),
10303 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10304 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010305{
Eric Laurent18b57012017-02-13 16:23:52 -080010306 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010307 readHalParameters_l();
10308}
10309
Andy Hungee58e4a2023-07-07 13:47:37 -070010310void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010311{
10312 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10313}
10314
Andy Hungee58e4a2023-07-07 13:47:37 -070010315void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316{
Andy Hung8d31fd22023-06-26 19:20:57 -070010317 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010318 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010319 {
Andy Hung972bec12023-08-31 16:13:39 -070010320 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010321 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010322 activeTracks.add(t);
10323 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010324 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010325 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010326 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327 stop(t->portId());
10328 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010329 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010330 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010331 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010332 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010333 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010334 }
10335}
10336
10337
Andy Hung8d672e02023-09-15 18:19:28 -070010338void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339 audio_stream_type_t streamType __unused,
10340 audio_session_t sessionId,
10341 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010342 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010343 audio_port_handle_t portId)
10344{
10345 mAttr = *attr;
10346 mSessionId = sessionId;
10347 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010348 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349 mPortId = portId;
10350}
10351
Andy Hungee58e4a2023-07-07 13:47:37 -070010352status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010353 struct audio_mmap_buffer_info *info)
10354{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010355 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010356 if (mHalStream == 0) {
10357 return NO_INIT;
10358 }
Eric Laurent18b57012017-02-13 16:23:52 -080010359 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010360 return mHalStream->createMmapBuffer(minSizeFrames, info);
10361}
10362
Andy Hungee58e4a2023-07-07 13:47:37 -070010363status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010364{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010365 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010366 if (mHalStream == 0) {
10367 return NO_INIT;
10368 }
10369 return mHalStream->getMmapPosition(position);
10370}
10371
Andy Hungee58e4a2023-07-07 13:47:37 -070010372status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010373{
Eric Laurentdda206a2022-07-08 17:28:35 +020010374 // The HAL must receive track metadata before starting the stream
10375 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010376 status_t ret = mHalStream->start();
10377 if (ret != NO_ERROR) {
10378 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10379 return ret;
10380 }
Andy Hungcf10d742020-04-28 15:38:24 -070010381 if (mStandby) {
10382 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010383 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010384 mStandby = false;
10385 }
Eric Laurent331679c2018-04-16 17:03:16 -070010386 return NO_ERROR;
10387}
10388
Andy Hungee58e4a2023-07-07 13:47:37 -070010389status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010390 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010391 audio_port_handle_t *handle)
10392{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010393 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010394 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010395 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010396 if (mHalStream == 0) {
10397 return NO_INIT;
10398 }
10399
10400 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401
Eric Laurentdda206a2022-07-08 17:28:35 +020010402 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010403 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010404 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010405 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010406 }
10407
10408 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10409
10410 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010411 AttributionSourceState adjAttributionSource;
10412 if (!com::android::media::audio::audioserver_permissions()) {
10413 adjAttributionSource = afutils::checkAttributionSourcePackage(
10414 client.attributionSource);
10415 } else {
10416 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10417 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10418 client.attributionSource,
10419 mAfThreadCallback->getPermissionProvider()
10420 );
10421 if (!validatedRes.has_value()) {
10422 ALOGE("MMAP client package validation fail: %s",
10423 validatedRes.error().toString8().c_str());
10424 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10425 }
10426 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10427 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010428
Andy Hung3f49ebb2023-09-19 14:48:41 -070010429 const auto localSessionId = mSessionId;
10430 auto localAttr = mAttr;
Andy Hung6b137d12024-08-27 22:35:17 +000010431 float volume = 0.0f;
Eric Laurenta54f1282017-07-01 19:39:32 -070010432 if (isOutput()) {
10433 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10434 config.sample_rate = mSampleRate;
10435 config.channel_mask = mChannelMask;
10436 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010437 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010438 audio_output_flags_t flags =
10439 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010440 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010441 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010442 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010443 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010444 mutex().unlock();
10445 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10446 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010447 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010448 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010449 &config,
10450 flags,
10451 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010452 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010453 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010454 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +000010455 &isBitPerfect,
10456 &volume);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010457 mutex().lock();
10458 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010459 ALOGD_IF(!secondaryOutputs.empty(),
10460 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010461 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010462 audio_config_base_t config;
10463 config.sample_rate = mSampleRate;
10464 config.channel_mask = mChannelMask;
10465 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010466 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010467 mutex().unlock();
10468 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010469 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010470 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010471 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010472 &config,
10473 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10474 &deviceId,
10475 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010476 mutex().lock();
10477 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010478 }
10479 // APM should not chose a different input or output stream for the same set of attributes
10480 // and audo configuration
10481 if (ret != NO_ERROR || io != mId) {
10482 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10483 __FUNCTION__, ret, io, mId);
10484 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010485 }
10486
10487 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010488 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010489 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010490 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010491 } else {
jiabin09609032022-06-15 19:26:01 +000010492 {
10493 // Add the track record before starting input so that the silent status for the
10494 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010495 setClientSilencedState_l(portId, false /*silenced*/);
10496 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010497 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010498 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010499 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010500 }
10501
10502 // abort if start is rejected by audio policy manager
10503 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010504 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010505 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010506 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010507 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010508 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010509 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010510 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010511 }
Andy Hungc5007f82023-08-29 14:26:09 -070010512 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010513 } else {
10514 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010515 }
jiabin09609032022-06-15 19:26:01 +000010516 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010517 return PERMISSION_DENIED;
10518 }
10519
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010520 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010521 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10522 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010523 mChannelMask, mSessionId, isOutput(),
10524 client.attributionSource,
Andy Hung6b137d12024-08-27 22:35:17 +000010525 IPCThreadState::self()->getCallingPid(), portId,
10526 volume);
jiabin09609032022-06-15 19:26:01 +000010527 if (!isOutput()) {
10528 track->setSilenced_l(isClientSilenced_l(portId));
10529 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010530
Eric Laurent4eb58f12018-12-07 16:41:02 -080010531 if (isOutput()) {
10532 // force volume update when a new track is added
10533 mHalVolFloat = -1.0f;
10534 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010535 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010536 if (t->isSilenced_l()
10537 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010538 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010539 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010540 }
10541 }
10542
Eric Laurent6acd1d42017-01-04 14:23:29 -080010543 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010544 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010546 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547 chain->incTrackCnt();
10548 chain->incActiveTrackCnt();
10549 }
10550
Andy Hungc2b11cb2020-04-22 09:04:01 -070010551 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010553
10554 if (mActiveTracks.size() == 1) {
10555 ret = exitStandby_l();
10556 }
10557
Eric Laurent6acd1d42017-01-04 14:23:29 -080010558 broadcast_l();
10559
Eric Laurentdda206a2022-07-08 17:28:35 +020010560 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010561
Eric Laurentdda206a2022-07-08 17:28:35 +020010562 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563}
10564
Andy Hungee58e4a2023-07-07 13:47:37 -070010565status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010566{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010568 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010569
10570 if (mHalStream == 0) {
10571 return NO_INIT;
10572 }
10573
Eric Laurenta54f1282017-07-01 19:39:32 -070010574 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010575 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010576 return NO_ERROR;
10577 }
10578
Andy Hung8d31fd22023-06-26 19:20:57 -070010579 sp<IAfMmapTrack> track;
10580 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581 if (handle == t->portId()) {
10582 track = t;
10583 break;
10584 }
10585 }
10586 if (track == 0) {
10587 return BAD_VALUE;
10588 }
10589
10590 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010591 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010592
Andy Hungc5007f82023-08-29 14:26:09 -070010593 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010594 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010595 AudioSystem::stopOutput(track->portId());
10596 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010597 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010598 AudioSystem::stopInput(track->portId());
10599 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010600 }
Andy Hungc5007f82023-08-29 14:26:09 -070010601 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010602
Andy Hung116bc262023-06-20 18:56:17 -070010603 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010604 if (chain != 0) {
10605 chain->decActiveTrackCnt();
10606 chain->decTrackCnt();
10607 }
10608
Eric Laurentdda206a2022-07-08 17:28:35 +020010609 if (mActiveTracks.isEmpty()) {
10610 mHalStream->stop();
10611 }
10612
Eric Laurent6acd1d42017-01-04 14:23:29 -080010613 broadcast_l();
10614
Eric Laurent6acd1d42017-01-04 14:23:29 -080010615 return NO_ERROR;
10616}
10617
Andy Hungee58e4a2023-07-07 13:47:37 -070010618status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010619NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010620{
10621 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010622 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010623
10624 if (mHalStream == 0) {
10625 return NO_INIT;
10626 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010627 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010628 return INVALID_OPERATION;
10629 }
10630 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010631 if (!mStandby) {
10632 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010633 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010634 mStandby = true;
10635 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010636 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010637 return NO_ERROR;
10638}
10639
Andy Hungee58e4a2023-07-07 13:47:37 -070010640status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010641 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10642 return INVALID_OPERATION;
10643}
10644
Andy Hungee58e4a2023-07-07 13:47:37 -070010645void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010646{
10647 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10648 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10649 mFormat = mHALFormat;
10650 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10651 result = mHalStream->getFrameSize(&mFrameSize);
10652 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010653 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10654 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010655 result = mHalStream->getBufferSize(&mBufferSize);
10656 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10657 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010658
Andy Hungcf10d742020-04-28 15:38:24 -070010659 // TODO: make a readHalParameters call?
10660 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010661 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010662 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010663 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10664 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10665 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10666 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10667 /*
10668 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10669 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10670 (int32_t)mHapticChannelMask)
10671 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10672 (int32_t)mHapticChannelCount)
10673 */
10674 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010675 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010676 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10677 (int32_t)mFrameCount) // sic - added HAL
10678 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679}
10680
Andy Hungee58e4a2023-07-07 13:47:37 -070010681bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010682{
Andy Hungab65b182023-09-06 19:41:47 -070010683 {
10684 audio_utils::unique_lock _l(mutex());
10685 checkSilentMode_l();
10686 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010687
10688 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10689
10690 while (!exitPending())
10691 {
Andy Hung116bc262023-06-20 18:56:17 -070010692 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010693
Andy Hung13850be2019-03-14 11:33:09 -070010694 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010695 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010696
Eric Laurent6acd1d42017-01-04 14:23:29 -080010697 if (mSignalPending) {
10698 // A signal was raised while we were unlocked
10699 mSignalPending = false;
10700 } else {
10701 if (mConfigEvents.isEmpty()) {
10702 // we're about to wait, flush the binder command buffer
10703 IPCThreadState::self()->flushCommands();
10704
10705 if (exitPending()) {
10706 break;
10707 }
10708
Eric Laurent6acd1d42017-01-04 14:23:29 -080010709 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010710 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010711 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010712 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010713
10714 checkSilentMode_l();
10715
10716 continue;
10717 }
10718 }
10719
10720 processConfigEvents_l();
10721
10722 processVolume_l();
10723
10724 checkInvalidTracks_l();
10725
Andy Hungab65b182023-09-06 19:41:47 -070010726 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727
Kevin Rocard069c2712018-03-29 19:09:14 -070010728 updateMetadata_l();
10729
Eric Laurent6acd1d42017-01-04 14:23:29 -080010730 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010731 } // release Thread lock
10732
Eric Laurent6acd1d42017-01-04 14:23:29 -080010733 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010734 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010735 }
Andy Hung13850be2019-03-14 11:33:09 -070010736
10737 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010738 unlockEffectChains(effectChains);
10739 // Effect chains will be actually deleted here if they were removed from
10740 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010741 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010742 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010743 mThreadloopExecutor.process(); // process any remaining deferred actions.
10744 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745
10746 threadLoop_exit();
10747
10748 if (!mStandby) {
10749 threadLoop_standby();
10750 mStandby = true;
10751 }
10752
Eric Laurent6acd1d42017-01-04 14:23:29 -080010753 ALOGV("Thread %p type %d exiting", this, mType);
10754 return false;
10755}
10756
Andy Hungc5007f82023-08-29 14:26:09 -070010757// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010758bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010759 status_t& status)
10760{
10761 AudioParameter param = AudioParameter(keyValuePair);
10762 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010763 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010764 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010765 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010766 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010767 if (sendToHal) {
10768 status = mHalStream->setParameters(keyValuePair);
10769 } else {
10770 status = NO_ERROR;
10771 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010772
10773 return false;
10774}
10775
Andy Hungee58e4a2023-07-07 13:47:37 -070010776String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010777{
Andy Hung972bec12023-08-31 16:13:39 -070010778 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779 String8 out_s8;
10780 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10781 return out_s8;
10782 }
Andy Hung920f6572022-10-06 12:09:49 -070010783 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010784}
10785
Andy Hungab65b182023-09-06 19:41:47 -070010786void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010787 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010788 sp<AudioIoDescriptor> desc;
10789 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 switch (event) {
10791 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010792 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010794 isInput = true;
10795 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010796 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010797 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010799 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10800 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010801 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010802 case AUDIO_INPUT_CLOSED:
10803 case AUDIO_OUTPUT_CLOSED:
10804 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010805 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010806 break;
10807 }
Andy Hungab65b182023-09-06 19:41:47 -070010808 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010809}
10810
Andy Hungee58e4a2023-07-07 13:47:37 -070010811status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010812 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010813NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814{
10815 status_t status = NO_ERROR;
10816
10817 // store new device and send to effects
10818 audio_devices_t type = AUDIO_DEVICE_NONE;
10819 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010820 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10821 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10822 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010823 if (isOutput()) {
10824 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010825 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10826 && !mAudioHwDev->supportsAudioPatches(),
10827 "Enumerated device type(%#x) must not be used "
10828 "as it does not support audio patches",
10829 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010830 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010831 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10832 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833 }
10834 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010835 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836 } else {
10837 type = patch->sources[0].ext.device.type;
10838 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010839 numDevices = mPatch.num_sources;
10840 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010841 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842 }
10843
10844 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010845 if (isOutput()) {
10846 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10847 } else {
10848 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10849 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010850 }
10851
jiabinc52b1ff2019-10-31 17:20:42 -070010852 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853 // store new source and send to effects
10854 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10855 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10856 for (size_t i = 0; i < mEffectChains.size(); i++) {
10857 mEffectChains[i]->setAudioSource_l(mAudioSource);
10858 }
10859 }
10860 }
10861
jiabin78b86f22024-02-22 00:39:29 +000010862 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10863 // okay to notify the client earlier before the new patch creation.
10864 if (mDeviceId != deviceId) {
10865 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10866 // The aaudioservice handle the routing changed event asynchronously. In that case,
10867 // it is safe to hold the lock here.
10868 callback->onRoutingChanged(deviceId);
10869 }
10870 }
10871
Eric Laurent6acd1d42017-01-04 14:23:29 -080010872 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010873 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10874 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010875 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010876 audio_port_config port;
10877 std::optional<audio_source_t> source;
10878 if (isOutput()) {
10879 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010880 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010881 port = patch->sources[0];
10882 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010883 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010884 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885 *handle = AUDIO_PATCH_HANDLE_NONE;
10886 }
10887
jiabinc52b1ff2019-10-31 17:20:42 -070010888 if (numDevices == 0 || mDeviceId != deviceId) {
10889 if (isOutput()) {
10890 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10891 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010892 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010893 } else {
10894 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10895 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10896 }
jiabinc52b1ff2019-10-31 17:20:42 -070010897 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010898 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010899 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010900 // Force meteadata update after a route change
10901 mActiveTracks.setHasChanged();
10902
Eric Laurent6acd1d42017-01-04 14:23:29 -080010903 return status;
10904}
10905
Andy Hungee58e4a2023-07-07 13:47:37 -070010906status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010907{
10908 status_t status = NO_ERROR;
10909
jiabinc52b1ff2019-10-31 17:20:42 -070010910 mPatch = audio_patch{};
10911 mOutDeviceTypeAddrs.clear();
10912 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010913
10914 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10915 supportsAudioPatches : false;
10916
10917 if (supportsAudioPatches) {
10918 status = mHalDevice->releaseAudioPatch(handle);
10919 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010920 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010921 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010922 // Force meteadata update after a route change
10923 mActiveTracks.setHasChanged();
10924
Eric Laurent6acd1d42017-01-04 14:23:29 -080010925 return status;
10926}
10927
Andy Hungee58e4a2023-07-07 13:47:37 -070010928void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010929NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010930{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010931 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010932 if (isOutput()) {
10933 config->role = AUDIO_PORT_ROLE_SOURCE;
10934 config->ext.mix.hw_module = mAudioHwDev->handle();
10935 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10936 } else {
10937 config->role = AUDIO_PORT_ROLE_SINK;
10938 config->ext.mix.hw_module = mAudioHwDev->handle();
10939 config->ext.mix.usecase.source = mAudioSource;
10940 }
10941}
10942
Andy Hungee58e4a2023-07-07 13:47:37 -070010943status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010944{
10945 audio_session_t session = chain->sessionId();
10946
10947 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10948 // Attach all tracks with same session ID to this chain.
10949 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010950 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010951 if (session == track->sessionId()) {
10952 chain->incTrackCnt();
10953 chain->incActiveTrackCnt();
10954 }
10955 }
10956
10957 chain->setThread(this);
10958 chain->setInBuffer(nullptr);
10959 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010960 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010961
10962 mEffectChains.add(chain);
10963 checkSuspendOnAddEffectChain_l(chain);
10964 return NO_ERROR;
10965}
10966
Andy Hungee58e4a2023-07-07 13:47:37 -070010967size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010968{
10969 audio_session_t session = chain->sessionId();
10970
10971 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10972
10973 for (size_t i = 0; i < mEffectChains.size(); i++) {
10974 if (chain == mEffectChains[i]) {
10975 mEffectChains.removeAt(i);
10976 // detach all active tracks from the chain
10977 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010978 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010979 if (session == track->sessionId()) {
10980 chain->decActiveTrackCnt();
10981 chain->decTrackCnt();
10982 }
10983 }
10984 break;
10985 }
10986 }
10987 return mEffectChains.size();
10988}
10989
Andy Hungee58e4a2023-07-07 13:47:37 -070010990void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010991{
10992 mHalStream->standby();
10993}
10994
Andy Hungee58e4a2023-07-07 13:47:37 -070010995void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010996{
Phil Burk7dce7282017-09-27 13:51:41 -070010997 // Do not call callback->onTearDown() because it is redundant for thread exit
10998 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010999}
11000
Andy Hungee58e4a2023-07-07 13:47:37 -070011001status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011002{
11003 return BAD_VALUE;
11004}
11005
Andy Hungee58e4a2023-07-07 13:47:37 -070011006bool MmapThread::isValidSyncEvent(
11007 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011008{
11009 return false;
11010}
11011
Andy Hungee58e4a2023-07-07 13:47:37 -070011012status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080011013 const effect_descriptor_t *desc, audio_session_t sessionId)
11014{
11015 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080011016 if (audio_is_global_session(sessionId)) {
11017 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080011018 desc->name, mThreadName);
11019 return BAD_VALUE;
11020 }
11021
11022 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11023 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11024 desc->name);
11025 return BAD_VALUE;
11026 }
11027 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011028 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11029 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011030 return BAD_VALUE;
11031 }
11032
11033 // Only allow effects without processing load or latency
11034 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11035 return BAD_VALUE;
11036 }
11037
Andy Hung116bc262023-06-20 18:56:17 -070011038 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011039 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11040 return BAD_VALUE;
11041 }
11042
Eric Laurent6acd1d42017-01-04 14:23:29 -080011043 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011044}
11045
Andy Hungee58e4a2023-07-07 13:47:37 -070011046void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011047{
Andy Hung8d31fd22023-06-26 19:20:57 -070011048 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011049 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011050 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11051 // The aaudioservice handle the routing changed event asynchronously. In that case,
11052 // it is safe to hold the lock here.
11053 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
11054 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011055 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11056 mNoCallbackWarningCount++;
11057 }
11058 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 }
11060 }
11061}
11062
Andy Hungee58e4a2023-07-07 13:47:37 -070011063void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011064{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011065 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11066 mAttr.content_type, mAttr.usage, mAttr.source);
11067 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011068 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011069 dprintf(fd, " No active clients\n");
11070 }
11071}
11072
Andy Hungee58e4a2023-07-07 13:47:37 -070011073void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011074{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011075 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011076 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011077 dprintf(fd, " %zu Tracks\n", numtracks);
11078 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011079 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011080 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011081 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011082 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011083 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011084 result.append(prefix);
11085 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011086 }
11087 } else {
11088 dprintf(fd, "\n");
11089 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011090 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011091}
11092
Andy Hungee58e4a2023-07-07 13:47:37 -070011093/* static */
11094sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011095 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011096 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011097 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011098}
11099
11100MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011101 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011102 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011103 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011104 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011105 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011106{
11107 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11108 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011109 mMasterVolume = afThreadCallback->masterVolume_l();
11110 mMasterMute = afThreadCallback->masterMute_l();
Andy Hung6b137d12024-08-27 22:35:17 +000011111 if (!audioserver_flags::portid_volume_management()) {
11112 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11113 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11114 mStreamTypes[stream].volume = 0.0f;
11115 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11116 }
11117 // Audio patch and call assistant volume are always max
11118 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11119 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11120 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11121 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011122 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011123 if (mAudioHwDev) {
11124 if (mAudioHwDev->canSetMasterVolume()) {
11125 mMasterVolume = 1.0;
11126 }
11127
11128 if (mAudioHwDev->canSetMasterMute()) {
11129 mMasterMute = false;
11130 }
11131 }
11132}
11133
Andy Hungee58e4a2023-07-07 13:47:37 -070011134void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011135 audio_stream_type_t streamType,
11136 audio_session_t sessionId,
11137 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011138 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011139 audio_port_handle_t portId)
11140{
Andy Hung8d672e02023-09-15 18:19:28 -070011141 audio_utils::lock_guard l(mutex());
11142 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011143 mStreamType = streamType;
11144}
11145
Andy Hungee58e4a2023-07-07 13:47:37 -070011146AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011147{
Andy Hung972bec12023-08-31 16:13:39 -070011148 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011149 AudioStreamOut *output = mOutput;
11150 mOutput = NULL;
11151 return output;
11152}
11153
Andy Hungee58e4a2023-07-07 13:47:37 -070011154void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011155{
Andy Hung972bec12023-08-31 16:13:39 -070011156 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011157 // Don't apply master volume in SW if our HAL can do it for us.
11158 if (mAudioHwDev &&
11159 mAudioHwDev->canSetMasterVolume()) {
11160 mMasterVolume = 1.0;
11161 } else {
11162 mMasterVolume = value;
11163 }
11164}
11165
Andy Hungee58e4a2023-07-07 13:47:37 -070011166void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011167{
Andy Hung972bec12023-08-31 16:13:39 -070011168 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011169 // Don't apply master mute in SW if our HAL can do it for us.
11170 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11171 mMasterMute = false;
11172 } else {
11173 mMasterMute = muted;
11174 }
11175}
11176
Andy Hungee58e4a2023-07-07 13:47:37 -070011177void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011178{
Andy Hung972bec12023-08-31 16:13:39 -070011179 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011180 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011181 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011182 broadcast_l();
11183 }
11184}
11185
Andy Hungee58e4a2023-07-07 13:47:37 -070011186float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011187{
Andy Hung972bec12023-08-31 16:13:39 -070011188 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011189 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011190}
11191
Andy Hungee58e4a2023-07-07 13:47:37 -070011192void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011193{
Andy Hung972bec12023-08-31 16:13:39 -070011194 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011195 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011196 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011197 broadcast_l();
11198 }
11199}
11200
Andy Hung6b137d12024-08-27 22:35:17 +000011201status_t MmapPlaybackThread::setPortsVolume(
11202 const std::vector<audio_port_handle_t>& portIds, float volume) {
11203 audio_utils::lock_guard _l(mutex());
11204 for (const auto& portId : portIds) {
11205 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11206 if (portId == track->portId()) {
11207 track->setPortVolume(volume);
11208 break;
11209 }
11210 }
11211 }
11212 broadcast_l();
11213 return NO_ERROR;
11214}
11215
Andy Hungee58e4a2023-07-07 13:47:37 -070011216void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011217{
Andy Hung972bec12023-08-31 16:13:39 -070011218 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011219 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011220 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011221 track->invalidate();
11222 }
11223 broadcast_l();
11224 }
11225}
11226
Andy Hungee58e4a2023-07-07 13:47:37 -070011227void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011228{
Andy Hung972bec12023-08-31 16:13:39 -070011229 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011230 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011231 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011232 if (portIds.find(track->portId()) != portIds.end()) {
11233 track->invalidate();
11234 trackMatch = true;
11235 portIds.erase(track->portId());
11236 }
11237 if (portIds.empty()) {
11238 break;
11239 }
11240 }
11241 if (trackMatch) {
11242 broadcast_l();
11243 }
11244}
11245
Andy Hungee58e4a2023-07-07 13:47:37 -070011246void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011247NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011248{
Andy Hung6b137d12024-08-27 22:35:17 +000011249 float volume = 0;
11250 if (!audioserver_flags::portid_volume_management()) {
11251 if (mMasterMute || streamMuted_l()) {
11252 volume = 0;
11253 } else {
11254 volume = mMasterVolume * streamVolume_l();
11255 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011256 } else {
Andy Hung6b137d12024-08-27 22:35:17 +000011257 if (mMasterMute) {
11258 volume = 0;
11259 } else {
11260 // All mmap tracks are declared with the same audio attributes to the audio policy
11261 // manager. Hence, they follow the same routing / volume group. Any change of volume
11262 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11263 size_t numtracks = mActiveTracks.size();
11264 if (numtracks) {
11265 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11266 }
11267 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011268 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011269 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011270 // Convert volumes from float to 8.24
11271 uint32_t vol = (uint32_t)(volume * (1 << 24));
11272
11273 // Delegate volume control to effect in track effect chain if needed
11274 // only one effect chain can be present on DirectOutputThread, so if
11275 // there is one, the track is connected to it
11276 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011277 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011278 volume = (float)vol / (1 << 24);
11279 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011280 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011281 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11282 mHalVolFloat = volume; // HW volume control worked, so update value.
11283 mNoCallbackWarningCount = 0;
11284 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011285 sp<MmapStreamCallback> callback = mCallback.promote();
11286 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011287 mHalVolFloat = volume; // SW volume control worked, so update value.
11288 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011289 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011290 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011291 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011292 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011293 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11294 ALOGW("Could not set MMAP stream volume: no volume callback!");
11295 mNoCallbackWarningCount++;
11296 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011297 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011298 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011299 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011300 track->setMetadataHasChanged();
Andy Hung6b137d12024-08-27 22:35:17 +000011301 if (!audioserver_flags::portid_volume_management()) {
11302 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11303 /*muteState=*/{mMasterMute,
11304 streamVolume_l() == 0.f,
11305 streamMuted_l(),
11306 // TODO(b/241533526): adjust logic to include mute from AppOps
11307 false /*muteFromPlaybackRestricted*/,
11308 false /*muteFromClientVolume*/,
11309 false /*muteFromVolumeShaper*/});
11310 } else {
11311 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11312 /*muteState=*/{mMasterMute,
11313 track->getPortVolume() == 0.f,
11314 /* muteFromStreamMuted= */ false,
11315 // TODO(b/241533526): adjust logic to include mute from AppOps
11316 false /*muteFromPlaybackRestricted*/,
11317 false /*muteFromClientVolume*/,
11318 false /*muteFromVolumeShaper*/});
11319 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011320 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011321 }
11322}
11323
Andy Hungee58e4a2023-07-07 13:47:37 -070011324ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011325{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011326 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011327 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011328 }
11329 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011330 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011331 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011332 playback_track_metadata_v7_t trackMetadata;
11333 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011334 .usage = track->attributes().usage,
11335 .content_type = track->attributes().content_type,
11336 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011337 };
11338 trackMetadata.channel_mask = track->channelMask(),
11339 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11340 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011341 }
11342 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011343
11344 MetadataUpdate change;
11345 change.playbackMetadataUpdate = metadata.tracks;
11346 return change;
11347};
Kevin Rocard069c2712018-03-29 19:09:14 -070011348
Andy Hungee58e4a2023-07-07 13:47:37 -070011349void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011350{
11351 if (!mMasterMute) {
11352 char value[PROPERTY_VALUE_MAX];
11353 if (property_get("ro.audio.silent", value, "0") > 0) {
11354 char *endptr;
11355 unsigned long ul = strtoul(value, &endptr, 0);
11356 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011357 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011358 // The setprop command will not allow a property to be changed after
11359 // the first time it is set, so we don't have to worry about un-muting.
11360 setMasterMute_l(true);
11361 }
11362 }
11363 }
11364}
11365
Andy Hungee58e4a2023-07-07 13:47:37 -070011366void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011367{
11368 MmapThread::toAudioPortConfig(config);
11369 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11370 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11371 config->flags.output = mOutput->flags;
11372 }
11373}
11374
Andy Hungee58e4a2023-07-07 13:47:37 -070011375status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011376 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011377{
11378 if (mOutput == nullptr) {
11379 return NO_INIT;
11380 }
11381 struct timespec timestamp;
11382 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11383 if (status == NO_ERROR) {
11384 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11385 }
11386 return status;
11387}
11388
Andy Hungee58e4a2023-07-07 13:47:37 -070011389status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011390 // Send to MelProcessor for sound dose measurement.
11391 auto processor = mMelProcessor.load();
11392 if (processor) {
11393 processor->process(buffer, frameCount * mFrameSize);
11394 }
11395
jiabinfc791ee2023-02-15 19:43:40 +000011396 return NO_ERROR;
11397}
11398
Andy Hungc5007f82023-08-29 14:26:09 -070011399// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011400void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011401 const sp<audio_utils::MelProcessor>& processor)
11402{
11403 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011404 mMelProcessor.store(processor);
11405 if (processor) {
11406 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011407 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011408
11409 // no need to update output format for MMapPlaybackThread since it is
11410 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011411}
11412
Andy Hungc5007f82023-08-29 14:26:09 -070011413// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011414void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011415{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011416 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11417 auto melProcessor = mMelProcessor.load();
11418 if (melProcessor != nullptr) {
11419 melProcessor->pause();
11420 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011421}
11422
Andy Hungee58e4a2023-07-07 13:47:37 -070011423void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011424{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011425 MmapThread::dumpInternals_l(fd, args);
Andy Hung6b137d12024-08-27 22:35:17 +000011426 if (!audioserver_flags::portid_volume_management()) {
11427 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11428 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11429 } else {
11430 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11431 }
11432 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011433 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11434}
11435
Andy Hungee58e4a2023-07-07 13:47:37 -070011436/* static */
11437sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011438 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011439 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011440 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011441}
11442
11443MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011444 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011445 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011446 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011447 mInput(input)
11448{
11449 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11450 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11451}
11452
Andy Hungee58e4a2023-07-07 13:47:37 -070011453status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011454{
Phil Burkf054fc32018-12-06 09:45:59 -080011455 {
11456 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011457 if (mInput != nullptr && mInput->stream != nullptr) {
11458 mInput->stream->setGain(1.0f);
11459 }
11460 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011461 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011462}
11463
Andy Hungee58e4a2023-07-07 13:47:37 -070011464AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011465{
Andy Hung972bec12023-08-31 16:13:39 -070011466 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011467 AudioStreamIn *input = mInput;
11468 mInput = NULL;
11469 return input;
11470}
Kevin Rocard069c2712018-03-29 19:09:14 -070011471
Andy Hungee58e4a2023-07-07 13:47:37 -070011472void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011473{
11474 bool changed = false;
11475 bool silenced = false;
11476
11477 sp<MmapStreamCallback> callback = mCallback.promote();
11478 if (callback == 0) {
11479 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11480 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11481 mNoCallbackWarningCount++;
11482 }
11483 }
11484
11485 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11486 // track is silenced and unmute otherwise
11487 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11488 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11489 changed = true;
11490 silenced = mActiveTracks[i]->isSilenced_l();
11491 }
11492 }
11493
11494 if (changed) {
11495 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11496 }
11497}
11498
Andy Hungee58e4a2023-07-07 13:47:37 -070011499ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011500{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011501 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011502 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011503 }
11504 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011505 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011506 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011507 record_track_metadata_v7_t trackMetadata;
11508 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011509 .source = track->attributes().source,
11510 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011511 };
11512 trackMetadata.channel_mask = track->channelMask(),
11513 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11514 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011515 }
11516 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011517 MetadataUpdate change;
11518 change.recordMetadataUpdate = metadata.tracks;
11519 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011520}
11521
Andy Hungee58e4a2023-07-07 13:47:37 -070011522void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011523{
Andy Hung972bec12023-08-31 16:13:39 -070011524 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011525 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011526 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011527 mActiveTracks[i]->setSilenced_l(silenced);
11528 broadcast_l();
11529 }
11530 }
jiabin09609032022-06-15 19:26:01 +000011531 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011532}
11533
Andy Hungee58e4a2023-07-07 13:47:37 -070011534void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011535{
11536 MmapThread::toAudioPortConfig(config);
11537 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11538 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11539 config->flags.input = mInput->flags;
11540 }
11541}
11542
Andy Hungee58e4a2023-07-07 13:47:37 -070011543status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011544 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011545{
11546 if (mInput == nullptr) {
11547 return NO_INIT;
11548 }
11549 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11550}
11551
jiabinc658e452022-10-21 20:52:21 +000011552// ----------------------------------------------------------------------------
11553
Andy Hungee58e4a2023-07-07 13:47:37 -070011554/* static */
11555sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011556 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011557 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011558 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011559}
11560
Andy Hung583043b2023-07-17 17:05:00 -070011561BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011562 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011563 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011564
Andy Hungee58e4a2023-07-07 13:47:37 -070011565PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011566 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011567 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11568 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011569 float volumeLeft = 1.0f;
11570 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011571 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11572 bitPerfectTrack != nullptr) {
11573 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011574 mAudioMixer->setParameter(
11575 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11576 mAudioMixer->setParameter(
11577 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11578 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011579 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011580 mIsBitPerfect = true;
11581 } else {
11582 mIsBitPerfect = false;
11583 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11584 // active.
11585 for (const auto& track : mActiveTracks) {
11586 const int trackId = track->id();
11587 mAudioMixer->setParameter(
11588 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11589 }
11590 }
jiabin76d94692022-12-15 21:51:21 +000011591 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11592 mVolumeLeft = volumeLeft;
11593 mVolumeRight = volumeRight;
11594 setVolumeForOutput_l(volumeLeft, volumeRight);
11595 }
jiabinc658e452022-10-21 20:52:21 +000011596 return result;
11597}
11598
Andy Hungee58e4a2023-07-07 13:47:37 -070011599void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011600 MixerThread::threadLoop_mix();
11601 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11602}
11603
jiabin220eea12024-05-17 17:55:20 +000011604void BitPerfectThread::setTracksInternalMute(
11605 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11606 for (auto& track : mTracks) {
11607 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11608 track->setInternalMute(it->second);
11609 tracksInternalMute->erase(it);
11610 }
11611 }
11612}
11613
11614sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11615 if (com::android::media::audioserver::
11616 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11617 sp<IAfTrack> bitPerfectTrack = nullptr;
11618 bool allOtherTracksMuted = true;
11619 // Return the bit perfect track if all other tracks are muted
11620 for (const auto& track : mActiveTracks) {
11621 if (track->isBitPerfect()) {
11622 bitPerfectTrack = track;
11623 } else if (track->getFinalVolume() != 0.f) {
11624 allOtherTracksMuted = false;
11625 if (bitPerfectTrack != nullptr) {
11626 break;
11627 }
11628 }
11629 }
11630 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11631 } else {
11632 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11633 return mActiveTracks[0];
11634 }
11635 }
11636 return nullptr;
11637}
11638
Glenn Kasten63238ef2015-03-02 15:50:29 -080011639} // namespace android