blob: f9c820fdb688ab15629baeafdda4418b295f18c2 [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:
Eric Laurentb62d0362021-10-26 17:40:18 +02001585 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1586 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1587 // 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) {
1590 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1591 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001592 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001593 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1594 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001595 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001596 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1597 break;
1598 }
1599 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1600 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1601 __func__, desc->name);
1602 return BAD_VALUE;
1603 }
1604 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1605 // only post processing on output stage session
1606 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1607 ALOGW("%s: non post processing effect %s not allowed on device session",
1608 __func__, desc->name);
1609 return BAD_VALUE;
1610 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001611 }
1612 break;
jiabinc658e452022-10-21 20:52:21 +00001613 case BIT_PERFECT:
1614 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1615 // Allow HW accelerated effects of tunnel type
1616 break;
1617 }
1618 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1619 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1620 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1621 // 3) there is any bit-perfect track with the given session id.
1622 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1623 sessionId == AUDIO_SESSION_DEVICE) {
1624 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1625 __func__, desc->name, mThreadName);
1626 return BAD_VALUE;
1627 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1628 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1629 __func__, desc->name, sessionId);
1630 return BAD_VALUE;
1631 }
1632 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001633 default:
1634 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1635 }
1636
1637 return NO_ERROR;
1638}
1639
Andy Hungc5007f82023-08-29 14:26:09 -07001640// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001641sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001642 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001643 const sp<IEffectClient>& effectClient,
1644 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001645 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001646 effect_descriptor_t *desc,
1647 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001648 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001649 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001650 bool probe,
1651 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001652{
Andy Hung116bc262023-06-20 18:56:17 -07001653 sp<IAfEffectModule> effect;
1654 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001655 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001656 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001657 bool chainCreated = false;
1658 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001659 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001660
1661 lStatus = initCheck();
1662 if (lStatus != NO_ERROR) {
1663 ALOGW("createEffect_l() Audio driver not initialized.");
1664 goto Exit;
1665 }
1666
Eric Laurent81784c32012-11-19 14:55:58 -08001667 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1668
Andy Hungc5007f82023-08-29 14:26:09 -07001669 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001670 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001671
Eric Laurent4c415062016-06-17 16:14:16 -07001672 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001673 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001674 goto Exit;
1675 }
1676
Eric Laurent81784c32012-11-19 14:55:58 -08001677 // check for existing effect chain with the requested audio session
1678 chain = getEffectChain_l(sessionId);
1679 if (chain == 0) {
1680 // create a new chain for this session
1681 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001682 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001683 addEffectChain_l(chain);
1684 chain->setStrategy(getStrategyForSession_l(sessionId));
1685 chainCreated = true;
1686 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001687 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001688 }
1689
1690 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1691
1692 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001693 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001694 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001695 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001696 if (lStatus != NO_ERROR) {
1697 goto Exit;
1698 }
1699 effectCreated = true;
1700
jiabinc52b1ff2019-10-31 17:20:42 -07001701 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001702 effect->setDevices(outDeviceTypeAddrs());
1703 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001704 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001705 effect->setAudioSource(mAudioSource);
1706 }
jiabin1319f5a2021-03-30 22:21:24 +00001707 if (effect->isHapticGenerator()) {
1708 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1709 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001710 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001711 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001712 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001713 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001714 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001715 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001716 }
1717 }
Eric Laurent81784c32012-11-19 14:55:58 -08001718 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001719 handle = IAfEffectHandle::create(
1720 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001721 lStatus = handle->initCheck();
1722 if (lStatus == OK) {
1723 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001724 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001725 }
Eric Laurent81784c32012-11-19 14:55:58 -08001726 if (enabled != NULL) {
1727 *enabled = (int)effect->isEnabled();
1728 }
1729 }
1730
1731Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001732 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001733 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001734 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001735 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001736 }
Eric Laurent81784c32012-11-19 14:55:58 -08001737 if (chainCreated) {
1738 removeEffectChain_l(chain);
1739 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001740 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001741 }
1742
Glenn Kasten9156ef32013-08-06 15:39:08 -07001743 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001744 return handle;
1745}
1746
Andy Hungee58e4a2023-07-07 13:47:37 -07001747void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001748 bool unpinIfLast)
1749{
1750 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001751 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001752 {
Andy Hung972bec12023-08-31 16:13:39 -07001753 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001754 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001755 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001756 return;
1757 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001758 effect = effectBase->asEffectModule();
1759 if (effect == nullptr) {
1760 return;
1761 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001762 // restore suspended effects if the disconnected handle was enabled and the last one.
1763 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1764 if (remove) {
1765 removeEffect_l(effect, true);
1766 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001767 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001768 }
1769 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001770 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001771 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001772 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001773 }
1774 }
1775}
1776
Andy Hungee58e4a2023-07-07 13:47:37 -07001777void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001778 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001779 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001780 broadcast_l();
1781 }
1782 if (!effect->isOffloadable()) {
1783 if (mType == ThreadBase::OFFLOAD) {
1784 PlaybackThread *t = (PlaybackThread *)this;
1785 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1786 }
1787 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001788 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001789 }
1790 }
1791}
1792
Andy Hungee58e4a2023-07-07 13:47:37 -07001793void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001794 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001795 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001796 broadcast_l();
1797 }
1798}
1799
Andy Hungee58e4a2023-07-07 13:47:37 -07001800sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001801 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001802{
Andy Hung972bec12023-08-31 16:13:39 -07001803 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001804 return getEffect_l(sessionId, effectId);
1805}
1806
Andy Hungee58e4a2023-07-07 13:47:37 -07001807sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001808 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001809{
Andy Hung116bc262023-06-20 18:56:17 -07001810 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001811 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1812}
1813
Andy Hungee58e4a2023-07-07 13:47:37 -07001814std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001815{
Andy Hung116bc262023-06-20 18:56:17 -07001816 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001817 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001818}
1819
Andy Hung972bec12023-08-31 16:13:39 -07001820// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1821// ThreadBase::mutex() held
1822status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001823{
1824 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001825 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001826 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001827 bool chainCreated = false;
1828
Eric Laurent5baf2af2013-09-12 17:37:00 -07001829 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001830 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1831 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001832
Eric Laurent81784c32012-11-19 14:55:58 -08001833 if (chain == 0) {
1834 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001835 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001836 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001837 addEffectChain_l(chain);
1838 chain->setStrategy(getStrategyForSession_l(sessionId));
1839 chainCreated = true;
1840 }
Andy Hung972bec12023-08-31 16:13:39 -07001841 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001842
1843 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001844 ALOGW("%s: %p effect %s already present in chain %p",
1845 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001846 return BAD_VALUE;
1847 }
1848
Shunkai Yaod125e402024-01-20 03:19:06 +00001849 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001850
Shunkai Yao29d10572024-03-19 04:31:47 +00001851 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001852 if (status != NO_ERROR) {
1853 if (chainCreated) {
1854 removeEffectChain_l(chain);
1855 }
1856 return status;
1857 }
1858
jiabin8f278ee2019-11-11 12:16:27 -08001859 effect->setDevices(outDeviceTypeAddrs());
1860 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001861 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001862 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001863
Eric Laurent81784c32012-11-19 14:55:58 -08001864 return NO_ERROR;
1865}
1866
Andy Hungee58e4a2023-07-07 13:47:37 -07001867void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001868
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001869 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001870 effect_descriptor_t desc = effect->desc();
1871 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1872 detachAuxEffect_l(effect->id());
1873 }
1874
Andy Hung116bc262023-06-20 18:56:17 -07001875 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001876 if (chain != 0) {
1877 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001878 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001879 removeEffectChain_l(chain);
1880 }
1881 } else {
1882 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1883 }
1884}
1885
Shunkai Yaof4847652024-01-12 00:25:20 +00001886void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1887 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001888{
1889 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001890 for (const auto& effectChain : effectChains) {
1891 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001892 }
1893}
1894
Shunkai Yaof4847652024-01-12 00:25:20 +00001895void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1896 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001897{
Shunkai Yaof4847652024-01-12 00:25:20 +00001898 for (const auto& effectChain : effectChains) {
1899 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001900 }
1901}
1902
Andy Hungee58e4a2023-07-07 13:47:37 -07001903sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001904{
Andy Hung972bec12023-08-31 16:13:39 -07001905 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001906 return getEffectChain_l(sessionId);
1907}
1908
Andy Hungee58e4a2023-07-07 13:47:37 -07001909sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001910 const
Eric Laurent81784c32012-11-19 14:55:58 -08001911{
1912 size_t size = mEffectChains.size();
1913 for (size_t i = 0; i < size; i++) {
1914 if (mEffectChains[i]->sessionId() == sessionId) {
1915 return mEffectChains[i];
1916 }
1917 }
1918 return 0;
1919}
1920
Andy Hungee58e4a2023-07-07 13:47:37 -07001921void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001922{
Andy Hung972bec12023-08-31 16:13:39 -07001923 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001924 size_t size = mEffectChains.size();
1925 for (size_t i = 0; i < size; i++) {
1926 mEffectChains[i]->setMode_l(mode);
1927 }
1928}
1929
Andy Hungee58e4a2023-07-07 13:47:37 -07001930void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001931{
1932 config->type = AUDIO_PORT_TYPE_MIX;
1933 config->ext.mix.handle = mId;
1934 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001935 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001936 config->channel_mask = mChannelMask;
1937 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1938 AUDIO_PORT_CONFIG_FORMAT;
1939}
1940
Andy Hungee58e4a2023-07-07 13:47:37 -07001941void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001942{
Andy Hung972bec12023-08-31 16:13:39 -07001943 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001944 if (mSystemReady) {
1945 return;
1946 }
1947 mSystemReady = true;
1948
1949 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1950 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1951 }
1952 mPendingConfigEvents.clear();
1953}
1954
Andy Hungdae27702016-10-31 14:01:16 -07001955template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001956ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001957 ssize_t index = mActiveTracks.indexOf(track);
1958 if (index >= 0) {
1959 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1960 return index;
1961 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001962 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001963 mActiveTracksGeneration++;
1964 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001965 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001966 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001967 return mActiveTracks.add(track);
1968}
1969
1970template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001971ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001972 ssize_t index = mActiveTracks.remove(track);
1973 if (index < 0) {
1974 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1975 return index;
1976 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001977 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001978 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001979 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001980 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001981 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001982#ifdef TEE_SINK
1983 track->dumpTee(-1 /* fd */, "_REMOVE");
1984#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001985 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001986 return index;
1987}
1988
1989template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001990void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001991 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001992 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001993 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001994 }
1995 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001996 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001997 mActiveTracks.clear();
1998 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001999}
2000
2001template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07002002void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07002003 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002004 // Updates ActiveTracks client uids to the thread wakelock.
2005 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2006 thread->updateWakeLockUids_l(getWakeLockUids());
2007 mLastActiveTracksGeneration = mActiveTracksGeneration;
2008 }
Andy Hungdae27702016-10-31 14:01:16 -07002009}
Eric Laurent83b88082014-06-20 18:31:16 -07002010
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002011template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002012bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002013 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002014 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002015
2016 for (const sp<T> &track : mActiveTracks) {
2017 // Do not short-circuit as all hasChanged states must be reset
2018 // as all the metadata are going to be sent
2019 hasChanged |= track->readAndClearHasChanged();
2020 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002021 return hasChanged;
2022}
2023
2024template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002025void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002026 const char *funcName, const sp<T> &track) const {
2027 if (mLocalLog != nullptr) {
2028 String8 result;
2029 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002030 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002031 }
2032}
2033
Andy Hungee58e4a2023-07-07 13:47:37 -07002034void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002035{
2036 // Thread could be blocked waiting for async
2037 // so signal it to handle state changes immediately
2038 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2039 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2040 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002041 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002042}
2043
Andy Hungd0979812019-02-21 15:51:44 -08002044// Call only from threadLoop() or when it is idle.
2045// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002046void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002047NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002048{
2049 // Do not log if we have no stats.
2050 // We choose the timestamp verifier because it is the most likely item to be present.
2051 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2052 if (nstats == 0) {
2053 return;
2054 }
2055
2056 // Don't log more frequently than once per 12 hours.
2057 // We use BOOTTIME to include suspend time.
2058 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2059 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2060 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2061 return;
2062 }
2063
2064 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2065 mLastRecordedTimeNs = timeNs;
2066
Ray Essickf27e9872019-12-07 06:28:46 -08002067 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002068
2069#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2070
2071 // thread configuration
2072 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2073 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2074 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2075 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2076 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2077 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2078 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002079 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2080 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002081
2082 // thread statistics
2083 if (mIoJitterMs.getN() > 0) {
2084 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2085 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2086 }
2087 if (mProcessTimeMs.getN() > 0) {
2088 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2089 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2090 }
2091 const auto tsjitter = mTimestampVerifier.getJitterMs();
2092 if (tsjitter.getN() > 0) {
2093 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2094 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2095 }
2096 if (mLatencyMs.getN() > 0) {
2097 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2098 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2099 }
Robert Wu06db0a32021-08-10 19:05:34 +00002100 if (mMonopipePipeDepthStats.getN() > 0) {
2101 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2102 mMonopipePipeDepthStats.getMean());
2103 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2104 mMonopipePipeDepthStats.getStdDev());
2105 }
Andy Hungd0979812019-02-21 15:51:44 -08002106
2107 item->selfrecord();
2108}
2109
Andy Hungee58e4a2023-07-07 13:47:37 -07002110product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002111{
Andy Hung583043b2023-07-17 17:05:00 -07002112 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002113 return PRODUCT_STRATEGY_NONE;
2114 }
2115 return AudioSystem::getStrategyForStream(stream);
2116}
2117
Andy Hungc5007f82023-08-29 14:26:09 -07002118// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002119void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002120 const sp<audio_utils::MelProcessor>& /*processor*/)
2121{
2122 // Do nothing
2123 ALOGW("%s: ThreadBase does not support CSD", __func__);
2124}
2125
Andy Hungc5007f82023-08-29 14:26:09 -07002126// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002127void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002128{
2129 // Do nothing
2130 ALOGW("%s: ThreadBase does not support CSD", __func__);
2131}
2132
Eric Laurent81784c32012-11-19 14:55:58 -08002133// ----------------------------------------------------------------------------
2134// Playback
2135// ----------------------------------------------------------------------------
2136
Andy Hung583043b2023-07-17 17:05:00 -07002137PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002138 AudioStreamOut* output,
2139 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002140 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002141 bool systemReady,
2142 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002143 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002144 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002145 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002146 mMixerBuffer(NULL),
2147 mMixerBufferSize(0),
2148 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2149 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002150 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002151 mEffectBuffer(NULL),
2152 mEffectBufferSize(0),
2153 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2154 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002155 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002156 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002157 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002158 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002159 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002160 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002161 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002162 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002163 mMixerStatus(MIXER_IDLE),
2164 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002165 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166 mBytesRemaining(0),
2167 mCurrentWriteLength(0),
2168 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002169 mWriteAckSequence(0),
2170 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002171 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002172 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002173 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002174 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002175 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002176 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002177 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002178{
Glenn Kastend7dca052015-03-05 16:05:54 -08002179 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002180 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002181
Andy Hungc5007f82023-08-29 14:26:09 -07002182 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002183 // it would be safer to explicitly pass initial masterVolume/masterMute as
2184 // parameter.
2185 //
2186 // If the HAL we are using has support for master volume or master mute,
2187 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2188 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002189 mMasterVolume = afThreadCallback->masterVolume_l();
2190 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002191 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002192 if (mOutput->audioHwDev->canSetMasterVolume()) {
2193 mMasterVolume = 1.0;
2194 }
2195
2196 if (mOutput->audioHwDev->canSetMasterMute()) {
2197 mMasterMute = false;
2198 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002199 mIsMsdDevice = strcmp(
2200 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002201 }
2202
Eric Laurentf1f22e72021-07-13 14:04:14 +02002203 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2204 mMixerChannelMask = mixerConfig->channel_mask;
2205 }
2206
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002207 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002208
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002209 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002210 && mMixerChannelMask != mChannelMask) {
2211 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2212 mChannelMask, mMixerChannelMask);
2213 }
2214
Andy Hungc8fddf32018-08-08 18:32:37 -07002215 // TODO: We may also match on address as well as device type for
2216 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002217 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002218 // TODO: This property should be ensure that only contains one single device type.
2219 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2220 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002221 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2222 : AUDIO_DEVICE_NONE));
2223 }
Andy Hung6b137d12024-08-27 22:35:17 +00002224 if (!audioserver_flags::portid_volume_management()) {
2225 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2226 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2227 mStreamTypes[stream].volume = 0.0f;
2228 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2229 }
2230 // Audio patch and call assistant volume are always max
2231 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2232 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2233 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2234 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002235 }
Eric Laurent81784c32012-11-19 14:55:58 -08002236}
2237
Andy Hungee58e4a2023-07-07 13:47:37 -07002238PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002239{
Andy Hung583043b2023-07-17 17:05:00 -07002240 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002241 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002242 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002243 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002244 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002245}
2246
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002247// Thread virtuals
2248
Andy Hungee58e4a2023-07-07 13:47:37 -07002249void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002250{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002251 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002252 ALOGE("The stream is not open yet"); // This should not happen.
2253 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002254 // Callbacks take strong or weak pointers as a parameter.
2255 // Since PlaybackThread passes itself as a callback handler, it can only
2256 // be done outside of the constructor. Creating weak and especially strong
2257 // pointers to a refcounted object in its own constructor is strongly
2258 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2259 // Even if a function takes a weak pointer, it is possible that it will
2260 // need to convert it to a strong pointer down the line.
2261 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2262 mOutput->stream->setCallback(this) == OK) {
2263 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002264 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002265 }
2266
jiabinf6eb4c32020-02-25 14:06:25 -08002267 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002268 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002269 }
2270 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002271 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002272 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002273}
2274
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002275// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002276void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002277{
2278 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002279 status_t result = mOutput->stream->exit();
2280 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002281}
2282
Andy Hungee58e4a2023-07-07 13:47:37 -07002283void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002284{
Eric Laurent81784c32012-11-19 14:55:58 -08002285 String8 result;
Andy Hung6b137d12024-08-27 22:35:17 +00002286 if (!audioserver_flags::portid_volume_management()) {
2287 result.appendFormat(" Stream volumes in dB: ");
2288 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2289 const stream_type_t *st = &mStreamTypes[i];
2290 if (i > 0) {
2291 result.appendFormat(", ");
2292 }
2293 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2294 if (st->mute) {
2295 result.append("M");
2296 }
Eric Laurent81784c32012-11-19 14:55:58 -08002297 }
2298 }
2299 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002300 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002301 result.clear();
2302
Eric Laurent81784c32012-11-19 14:55:58 -08002303 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2304 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002305 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002306 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002307
2308 size_t numtracks = mTracks.size();
2309 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002310 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002311 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002312 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002313 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002314 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002315 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002316 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002317 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002318 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002319 if (track != 0) {
2320 bool active = mActiveTracks.indexOf(track) >= 0;
2321 if (active) {
2322 numactiveseen++;
2323 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002324 result.append(prefix);
2325 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002326 }
2327 }
2328 } else {
2329 result.append("\n");
2330 }
2331 if (numactiveseen != numactive) {
2332 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002333 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002334 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002335 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002336 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002337 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002338 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002339 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002340 result.append(prefix);
2341 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002342 }
2343 }
2344 }
2345
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002346 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002347}
2348
Andy Hungee58e4a2023-07-07 13:47:37 -07002349void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002350{
Andy Hung04cb8f72020-03-20 13:44:33 -07002351 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002352 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002353 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2354 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002355 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2356 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2357 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2358 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002359 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002360 dprintf(fd, " Total writes: %d\n", mNumWrites);
2361 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2362 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002363 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002364 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002365 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002366 AudioStreamOut *output = mOutput;
2367 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002368 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002369 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002370 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2371 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2372 if (mPipeSink.get() != nullptr) {
2373 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2374 }
2375 if (output != nullptr) {
2376 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002377 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002378 }
Eric Laurent81784c32012-11-19 14:55:58 -08002379}
2380
Andy Hungc5007f82023-08-29 14:26:09 -07002381// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002382sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002383 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002384 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002385 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002386 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002387 audio_format_t format,
2388 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002389 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002390 size_t *pNotificationFrameCount,
2391 uint32_t notificationsPerBuffer,
2392 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002393 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002394 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002395 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002396 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002397 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002398 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002399 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002400 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002401 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002402 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002403 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00002404 audio_output_flags_t *afTrackFlags,
2405 float volume)
Eric Laurent81784c32012-11-19 14:55:58 -08002406{
Glenn Kasten74935e42013-12-19 08:56:45 -08002407 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002408 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002409 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002410 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002411 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002412 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002413 uint32_t sampleRate;
2414
2415 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2416 lStatus = BAD_VALUE;
2417 goto Exit;
2418 }
Eric Laurent21da6472017-11-09 16:29:26 -08002419
2420 if (*pSampleRate == 0) {
2421 *pSampleRate = mSampleRate;
2422 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002423 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002424
2425 // special case for FAST flag considered OK if fast mixer is present
2426 if (hasFastMixer()) {
2427 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2428 }
2429
2430 // Check if requested flags are compatible with output stream flags
2431 if ((*flags & outputFlags) != *flags) {
2432 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2433 *flags, outputFlags);
2434 *flags = (audio_output_flags_t)(*flags & outputFlags);
2435 }
Eric Laurent81784c32012-11-19 14:55:58 -08002436
jiabinc658e452022-10-21 20:52:21 +00002437 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002438 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002439 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002440 if (chain.get() != nullptr) {
2441 // Bit-perfect is required according to the configuration and preferred mixer
2442 // attributes, but it is not in the output flag from the client's request. Explicitly
2443 // adding bit-perfect flag to check the compatibility
2444 audio_output_flags_t flagsToCheck =
2445 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2446 chain->checkOutputFlagCompatibility(&flagsToCheck);
2447 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2448 ALOGE("%s cannot create track as there is data-processing effect attached to "
2449 "given session id(%d)", __func__, sessionId);
2450 lStatus = BAD_VALUE;
2451 goto Exit;
2452 }
2453 *flags = flagsToCheck;
2454 }
2455 }
2456
Eric Laurent81784c32012-11-19 14:55:58 -08002457 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002458 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002459 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002460 // PCM data
2461 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002462 // TODO: extract as a data library function that checks that a computationally
2463 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002464 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002465 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2466 (channelMask == AUDIO_CHANNEL_OUT_MONO
2467 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002468 // hardware sample rate
2469 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002470 // normal mixer has an associated fast mixer
2471 hasFastMixer() &&
2472 // there are sufficient fast track slots available
2473 (mFastTrackAvailMask != 0)
2474 // FIXME test that MixerThread for this fast track has a capable output HAL
2475 // FIXME add a permission test also?
2476 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002477 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2478 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002479 // read the fast track multiplier property the first time it is needed
2480 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2481 if (ok != 0) {
2482 ALOGE("%s pthread_once failed: %d", __func__, ok);
2483 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002484 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002485 }
Eric Laurent4c415062016-06-17 16:14:16 -07002486
2487 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002488 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002489 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002490 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002491 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002492 AUDIO_SESSION_OUTPUT_STAGE,
2493 AUDIO_SESSION_OUTPUT_MIX,
2494 sessionId,
2495 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002496 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002497 if (chain.get() != nullptr) {
2498 audio_output_flags_t old = *flags;
2499 chain->checkOutputFlagCompatibility(flags);
2500 if (old != *flags) {
2501 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2502 (int)session, (int)old, (int)*flags);
2503 }
Eric Laurent4c415062016-06-17 16:14:16 -07002504 }
2505 }
2506 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002507 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002508 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2509 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002510 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002511 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002512 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002513 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002514 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002515 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002516 audio_is_linear_pcm(format), channelMask, sampleRate,
2517 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002518 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002519 }
2520 }
Eric Laurent21da6472017-11-09 16:29:26 -08002521
2522 if (!audio_has_proportional_frames(format)) {
2523 if (sharedBuffer != 0) {
2524 // Same comment as below about ignoring frameCount parameter for set()
2525 frameCount = sharedBuffer->size();
2526 } else if (frameCount == 0) {
2527 frameCount = mNormalFrameCount;
2528 }
2529 if (notificationFrameCount != frameCount) {
2530 notificationFrameCount = frameCount;
2531 }
2532 } else if (sharedBuffer != 0) {
2533 // FIXME: Ensure client side memory buffers need
2534 // not have additional alignment beyond sample
2535 // (e.g. 16 bit stereo accessed as 32 bit frame).
2536 size_t alignment = audio_bytes_per_sample(format);
2537 if (alignment & 1) {
2538 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2539 alignment = 1;
2540 }
2541 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2542 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2543 if (channelCount > 1) {
2544 // More than 2 channels does not require stronger alignment than stereo
2545 alignment <<= 1;
2546 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002547 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002548 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002549 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002550 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002551 goto Exit;
2552 }
Eric Laurent21da6472017-11-09 16:29:26 -08002553
2554 // When initializing a shared buffer AudioTrack via constructors,
2555 // there's no frameCount parameter.
2556 // But when initializing a shared buffer AudioTrack via set(),
2557 // there _is_ a frameCount parameter. We silently ignore it.
2558 frameCount = sharedBuffer->size() / frameSize;
2559 } else {
2560 size_t minFrameCount = 0;
2561 // For fast tracks we try to respect the application's request for notifications per buffer.
2562 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2563 if (notificationsPerBuffer > 0) {
2564 // Avoid possible arithmetic overflow during multiplication.
2565 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2566 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2567 notificationsPerBuffer, mFrameCount);
2568 } else {
2569 minFrameCount = mFrameCount * notificationsPerBuffer;
2570 }
2571 }
2572 } else {
2573 // For normal PCM streaming tracks, update minimum frame count.
2574 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2575 // cover audio hardware latency.
2576 // This is probably too conservative, but legacy application code may depend on it.
2577 // If you change this calculation, also review the start threshold which is related.
2578 uint32_t latencyMs = latency_l();
2579 if (latencyMs == 0) {
2580 ALOGE("Error when retrieving output stream latency");
2581 lStatus = UNKNOWN_ERROR;
2582 goto Exit;
2583 }
2584
2585 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2586 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2587
Eric Laurent81784c32012-11-19 14:55:58 -08002588 }
Eric Laurent21da6472017-11-09 16:29:26 -08002589 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002590 frameCount = minFrameCount;
2591 }
Eric Laurent81784c32012-11-19 14:55:58 -08002592 }
Eric Laurent21da6472017-11-09 16:29:26 -08002593
2594 // Make sure that application is notified with sufficient margin before underrun.
2595 // The client can divide the AudioTrack buffer into sub-buffers,
2596 // and expresses its desire to server as the notification frame count.
2597 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2598 size_t maxNotificationFrames;
2599 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2600 // notify every HAL buffer, regardless of the size of the track buffer
2601 maxNotificationFrames = mFrameCount;
2602 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002603 // Triple buffer the notification period for a triple buffered mixer period;
2604 // otherwise, double buffering for the notification period is fine.
2605 //
2606 // TODO: This should be moved to AudioTrack to modify the notification period
2607 // on AudioTrack::setBufferSizeInFrames() changes.
2608 const int nBuffering =
2609 (uint64_t{frameCount} * mSampleRate)
2610 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2611
Eric Laurent21da6472017-11-09 16:29:26 -08002612 maxNotificationFrames = frameCount / nBuffering;
2613 // If client requested a fast track but this was denied, then use the smaller maximum.
2614 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2615 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2616 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2617 maxNotificationFrames = maxNotificationFramesFastDenied;
2618 }
2619 }
2620 }
2621 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2622 if (notificationFrameCount == 0) {
2623 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2624 maxNotificationFrames, frameCount);
2625 } else {
2626 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2627 notificationFrameCount, maxNotificationFrames, frameCount);
2628 }
2629 notificationFrameCount = maxNotificationFrames;
2630 }
2631 }
2632
Glenn Kasten74935e42013-12-19 08:56:45 -08002633 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002634 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002635
Glenn Kastenc3df8382014-03-13 15:05:25 -07002636 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002637 case BIT_PERFECT:
2638 if (isBitPerfect) {
2639 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2640 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2641 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2642 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2643 mChannelMask);
2644 lStatus = BAD_VALUE;
2645 goto Exit;
2646 }
2647 }
2648 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002649
2650 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002651 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002652 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002653 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2654 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002655 sampleRate, format, channelMask, mOutput, mFormat);
2656 lStatus = BAD_VALUE;
2657 goto Exit;
2658 }
2659 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002660 break;
2661
2662 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002663 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002664 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2665 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002666 sampleRate, format, channelMask, mOutput, mFormat);
2667 lStatus = BAD_VALUE;
2668 goto Exit;
2669 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002670 break;
2671
2672 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002673 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002674 ALOGE("createTrack_l() Bad parameter: format %#x \""
2675 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002676 format, mOutput, mFormat);
2677 lStatus = BAD_VALUE;
2678 goto Exit;
2679 }
Andy Hungcd044842014-08-07 11:04:34 -07002680 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002681 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2682 lStatus = BAD_VALUE;
2683 goto Exit;
2684 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002685 break;
2686
Eric Laurent81784c32012-11-19 14:55:58 -08002687 }
2688
2689 lStatus = initCheck();
2690 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002691 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002692 goto Exit;
2693 }
2694
Andy Hungc5007f82023-08-29 14:26:09 -07002695 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002696 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002697
2698 // all tracks in same audio session must share the same routing strategy otherwise
2699 // conflicts will happen when tracks are moved from one output to another by audio policy
2700 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002701 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002702 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002703 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002704 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002705 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002706 if (sessionId == t->sessionId() && strategy != actual) {
2707 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2708 strategy, actual);
2709 lStatus = BAD_VALUE;
2710 goto Exit;
2711 }
2712 }
2713 }
2714
Deeraj Soman2b515232024-05-14 12:58:24 +05302715 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2716 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002717 // dynamic audio policy.
2718 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302719 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002720 audio_output_flags_t trackFlags = *flags;
2721 if (mType == DIRECT) {
2722 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302723 } else if (mType == OFFLOAD) {
2724 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2725 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002726 }
jiabin94ed47c2023-07-27 23:34:20 +00002727 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002728
Andy Hung8d31fd22023-06-26 19:20:57 -07002729 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002730 channelMask, frameCount,
2731 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002732 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002733 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Andy Hung6b137d12024-08-27 22:35:17 +00002734 speed, isSpatialized, isBitPerfect, volume);
Glenn Kasten03003332013-08-06 15:40:54 -07002735
Glenn Kasten03003332013-08-06 15:40:54 -07002736 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2737 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002738 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002739 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002740 goto Exit;
2741 }
2742 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002743 {
Andy Hung972bec12023-08-31 16:13:39 -07002744 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002745 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002746 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002747 }
2748 }
Eric Laurent81784c32012-11-19 14:55:58 -08002749
Andy Hung116bc262023-06-20 18:56:17 -07002750 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002751 if (chain != 0) {
2752 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2753 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002754 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002755 chain->incTrackCnt();
2756 }
2757
Eric Laurent05067782016-06-01 18:27:28 -07002758 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002759 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2760 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2761 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002762 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002763 }
2764 }
2765
2766 lStatus = NO_ERROR;
2767
2768Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002769 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002770 return track;
2771}
2772
Andy Hung1bc088a2018-02-09 15:57:31 -08002773template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002774ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002775{
Andy Hungc0691382018-09-12 18:01:57 -07002776 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002777 const ssize_t index = mTracks.remove(track);
2778 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002779 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002780 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002781 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002782 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002783 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002784 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002785 }
2786 return index;
2787}
2788
Andy Hungee58e4a2023-07-07 13:47:37 -07002789uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002790{
2791 return latency;
2792}
2793
Andy Hungee58e4a2023-07-07 13:47:37 -07002794uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002795{
Andy Hung972bec12023-08-31 16:13:39 -07002796 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002797 return latency_l();
2798}
Andy Hungee58e4a2023-07-07 13:47:37 -07002799uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002800NO_THREAD_SAFETY_ANALYSIS
2801// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002802{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002803 uint32_t latency;
2804 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2805 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002806 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002807 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002808}
2809
Andy Hungee58e4a2023-07-07 13:47:37 -07002810void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002811{
Andy Hung972bec12023-08-31 16:13:39 -07002812 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002813 // Don't apply master volume in SW if our HAL can do it for us.
2814 if (mOutput && mOutput->audioHwDev &&
2815 mOutput->audioHwDev->canSetMasterVolume()) {
2816 mMasterVolume = 1.0;
2817 } else {
2818 mMasterVolume = value;
2819 }
2820}
2821
Andy Hungee58e4a2023-07-07 13:47:37 -07002822void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002823{
2824 mMasterBalance.store(balance);
2825}
2826
Andy Hungee58e4a2023-07-07 13:47:37 -07002827void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002828{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002829 if (isDuplicating()) {
2830 return;
2831 }
Andy Hung972bec12023-08-31 16:13:39 -07002832 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002833 // Don't apply master mute in SW if our HAL can do it for us.
2834 if (mOutput && mOutput->audioHwDev &&
2835 mOutput->audioHwDev->canSetMasterMute()) {
2836 mMasterMute = false;
2837 } else {
2838 mMasterMute = muted;
2839 }
2840}
2841
Andy Hungee58e4a2023-07-07 13:47:37 -07002842void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002843{
Andy Hung972bec12023-08-31 16:13:39 -07002844 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002845 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002846 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002847}
2848
Andy Hungee58e4a2023-07-07 13:47:37 -07002849void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002850{
Andy Hung972bec12023-08-31 16:13:39 -07002851 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002852 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002853 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002854}
2855
Andy Hungee58e4a2023-07-07 13:47:37 -07002856float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002857{
Andy Hung972bec12023-08-31 16:13:39 -07002858 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002859 return mStreamTypes[stream].volume;
2860}
2861
Andy Hung6b137d12024-08-27 22:35:17 +00002862status_t PlaybackThread::setPortsVolume(
2863 const std::vector<audio_port_handle_t>& portIds, float volume) {
2864 audio_utils::lock_guard _l(mutex());
2865 for (const auto& portId : portIds) {
2866 for (size_t i = 0; i < mTracks.size(); i++) {
2867 sp<IAfTrack> track = mTracks[i].get();
2868 if (portId == track->portId()) {
2869 track->setPortVolume(volume);
2870 break;
2871 }
2872 }
2873 }
2874 broadcast_l();
2875 return NO_ERROR;
2876}
2877
Andy Hungee58e4a2023-07-07 13:47:37 -07002878void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002879{
2880 mOutput->stream->setVolume(left, right);
2881}
2882
Andy Hungc5007f82023-08-29 14:26:09 -07002883// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002884status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002885{
2886 status_t status = ALREADY_EXISTS;
2887
Eric Laurent81784c32012-11-19 14:55:58 -08002888 if (mActiveTracks.indexOf(track) < 0) {
2889 // the track is newly added, make sure it fills up all its
2890 // buffers before playing. This is to ensure the client will
2891 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002892 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002893 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002894 // Because the track is not on the ActiveTracks,
2895 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002896 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002897 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002898 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002899 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002900 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002901 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002902 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002903 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002904 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905 }
2906 return INVALID_OPERATION;
2907 }
2908 // abort if start is rejected by audio policy manager
2909 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002910 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2911 // current playback thread is reopened, which may happen when clients set preferred
2912 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2913 // immediately.
2914 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002915 }
2916#ifdef ADD_BATTERY_DATA
2917 // to track the speaker usage
2918 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2919#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002920 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002921 }
2922
Eric Laurent51716182016-02-29 18:00:56 -08002923 // set retry count for buffer fill
2924 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002925 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002926 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002927 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002928 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002929 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002930 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002931 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002932 track->retryCount() = kMaxTrackStartupRetries;
2933 track->fillingStatus() =
2934 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002935 }
2936
Andy Hung116bc262023-06-20 18:56:17 -07002937 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002938 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2939 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002940 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002941 // Unlock due to VibratorService will lock for this call and will
2942 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002943 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002944 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002945 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002946 std::optional<media::AudioVibratorInfo> vibratorInfo;
2947 {
2948 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2949 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002950 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002951 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002952 }
Andy Hungc5007f82023-08-29 14:26:09 -07002953 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002954 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002955 if (vibratorInfo) {
2956 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2957 }
2958
jiabin57303cc2018-12-18 15:45:57 -08002959 // Haptic playback should be enabled by vibrator service.
2960 if (track->getHapticPlaybackEnabled()) {
2961 // Disable haptic playback of all active track to ensure only
2962 // one track playing haptic if current track should play haptic.
2963 for (const auto &t : mActiveTracks) {
2964 t->setHapticPlaybackEnabled(false);
2965 }
jiabin245cdd92018-12-07 17:55:15 -08002966 }
jiabine70bc7f2020-06-30 22:07:55 -07002967
2968 // Set haptic intensity for effect
2969 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002970 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002971 }
jiabin245cdd92018-12-07 17:55:15 -08002972 }
2973
Andy Hung8d31fd22023-06-26 19:20:57 -07002974 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002975 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002976
2977 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2978 // all key changes are complete. It is possible that the threadLoop will begin
2979 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002980 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002981
Eric Laurentd0107bc2013-06-11 14:38:48 -07002982 if (chain != 0) {
2983 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2984 track->sessionId());
2985 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002986 }
2987
Andy Hungc2b11cb2020-04-22 09:04:01 -07002988 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002989 status = NO_ERROR;
2990 }
2991
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002992 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002993 return status;
2994}
2995
Andy Hungee58e4a2023-07-07 13:47:37 -07002996bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002997{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002998 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002999 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003000 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07003001 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003002 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08003003 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07003004 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07003005 if (track->isPausePending()) {
3006 track->pauseAck();
3007 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003008 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003009 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003010
3011 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003012}
3013
Andy Hungee58e4a2023-07-07 13:47:37 -07003014void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003015{
3016 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003017
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003018 String8 result;
3019 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003020 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003021
Eric Laurent81784c32012-11-19 14:55:58 -08003022 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003023 {
Andy Hung972bec12023-08-31 16:13:39 -07003024 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003025 mAudioTrackCallbacks.erase(track);
3026 }
Eric Laurent81784c32012-11-19 14:55:58 -08003027 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003028 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003029 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003030 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3031 mFastTrackAvailMask |= 1 << index;
3032 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003033 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003034 }
Andy Hung116bc262023-06-20 18:56:17 -07003035 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003036 if (chain != 0) {
3037 chain->decTrackCnt();
3038 }
3039}
3040
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003041std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3042{
3043 std::set<int32_t> result;
3044 for (const auto& t : mTracks) {
3045 if (t->isExternalTrack()) {
3046 result.insert(t->portId());
3047 }
3048 }
3049 return result;
3050}
3051
3052std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3053{
3054 audio_utils::lock_guard _l(mutex());
3055 return getTrackPortIds_l();
3056}
3057
Andy Hungee58e4a2023-07-07 13:47:37 -07003058String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003059{
Andy Hung972bec12023-08-31 16:13:39 -07003060 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003061 String8 out_s8;
3062 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3063 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003064 }
Andy Hung920f6572022-10-06 12:09:49 -07003065 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003066}
3067
Andy Hungee58e4a2023-07-07 13:47:37 -07003068status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003069 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003070 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003071 return NO_INIT;
3072 }
3073 return mOutput->stream->selectPresentation(presentationId, programId);
3074}
3075
Andy Hungab65b182023-09-06 19:41:47 -07003076void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003077 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003078 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003079 sp<AudioIoDescriptor> desc;
3080 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003081 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003082 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003083 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003084 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003085 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3086 mSampleRate, mFormat, mChannelMask,
3087 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3088 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003089 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003090 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003091 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003092 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003093 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003094 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003095 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003096 break;
3097 }
Andy Hungab65b182023-09-06 19:41:47 -07003098 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003099}
3100
Andy Hungee58e4a2023-07-07 13:47:37 -07003101void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003102{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003103 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003104}
3105
Andy Hungee58e4a2023-07-07 13:47:37 -07003106void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003107{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003108 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003109}
3110
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003111void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003112{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003113 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003114}
3115
Andy Hungee58e4a2023-07-07 13:47:37 -07003116void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003117 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003118{
Andy Hungee58e4a2023-07-07 13:47:37 -07003119 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003120 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003121 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003122 if (playbackThread == nullptr) {
3123 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3124 return;
3125 }
3126
jiabinf6eb4c32020-02-25 14:06:25 -08003127 audio_utils::metadata::Data metadata =
3128 audio_utils::metadata::dataFromByteString(metadataBs);
3129 if (metadata.empty()) {
3130 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3131 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3132 (int)metadataBs.size());
3133 return;
3134 }
3135
3136 audio_utils::metadata::ByteString metaDataStr =
3137 audio_utils::metadata::byteStringFromData(metadata);
3138 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003139 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003140 for (const auto& callbackPair : mAudioTrackCallbacks) {
3141 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003142 }
3143 }).detach();
3144}
3145
Andy Hungee58e4a2023-07-07 13:47:37 -07003146void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003147{
Andy Hung972bec12023-08-31 16:13:39 -07003148 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003149 // reject out of sequence requests
3150 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3151 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003152 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003153 }
3154}
3155
Andy Hungee58e4a2023-07-07 13:47:37 -07003156void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003157{
Andy Hung972bec12023-08-31 16:13:39 -07003158 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003159 // reject out of sequence requests
3160 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003161 // Register discontinuity when HW drain is completed because that can cause
3162 // the timestamp frame position to reset to 0 for direct and offload threads.
3163 // (Out of sequence requests are ignored, since the discontinuity would be handled
3164 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003165 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003166 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003167 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003168 }
3169}
3170
Andy Hungee58e4a2023-07-07 13:47:37 -07003171void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003172NO_THREAD_SAFETY_ANALYSIS
3173// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003174{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003175 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003176 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3177 mSampleRate = audioConfig.sample_rate;
3178 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003179 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003180 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003181 }
Andy Hung81994d62023-07-20 21:44:14 -07003182 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003183 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3184 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003185 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003186
3187 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3188 mMixerChannelMask = mChannelMask;
3189 }
3190
Andy Hunge5412692014-05-16 11:25:07 -07003191 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003192 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003193
Eric Laurentf1f22e72021-07-13 14:04:14 +02003194 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3195
Phil Burkca5e6142015-07-14 09:42:29 -07003196 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003197 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003198 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003199 // Get format from the shim, which will be different than the HAL format
3200 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003201 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003202 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003203 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003204 }
Andy Hung81994d62023-07-20 21:44:14 -07003205 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003206 LOG_FATAL("HAL format %#x not supported for mixed output",
3207 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003208 }
Phil Burk062e67a2015-02-11 13:40:50 -08003209 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003210 result = mOutput->stream->getBufferSize(&mBufferSize);
3211 LOG_ALWAYS_FATAL_IF(result != OK,
3212 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003213 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003214 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003215 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003216 mFrameCount);
3217 }
3218
Eric Laurentd1f69b02014-12-15 14:33:13 -08003219 mHwSupportsPause = false;
3220 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003221 bool supportsPause = false, supportsResume = false;
3222 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3223 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003224 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003225 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003226 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003227 } else if (supportsResume) {
3228 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003229 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003230 }
3231 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003232 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3233 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3234 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003235
Andy Hungfbfc3952015-01-15 13:33:51 -08003236 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3237 // For best precision, we use float instead of the associated output
3238 // device format (typically PCM 16 bit).
3239
3240 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3241 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3242 mBufferSize = mFrameSize * mFrameCount;
3243
3244 // TODO: We currently use the associated output device channel mask and sample rate.
3245 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3246 // (if a valid mask) to avoid premature downmix.
3247 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3248 // instead of the output device sample rate to avoid loss of high frequency information.
3249 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3250 }
3251
Andy Hung09a50072014-02-27 14:30:47 -08003252 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003253 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003254 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003255 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3256 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003257 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3258 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003259
Eric Laurent81784c32012-11-19 14:55:58 -08003260 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3261 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3262 maxNormalFrameCount = maxNormalFrameCount & ~15;
3263 if (maxNormalFrameCount < minNormalFrameCount) {
3264 maxNormalFrameCount = minNormalFrameCount;
3265 }
3266 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3267 if (multiplier <= 1.0) {
3268 multiplier = 1.0;
3269 } else if (multiplier <= 2.0) {
3270 if (2 * mFrameCount <= maxNormalFrameCount) {
3271 multiplier = 2.0;
3272 } else {
3273 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3274 }
3275 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003276 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003277 }
3278 }
3279 mNormalFrameCount = multiplier * mFrameCount;
3280 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003281 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003282 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3283 }
Andy Hungab65b182023-09-06 19:41:47 -07003284 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3285 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003286
Andy Hung08fb1742015-05-31 23:22:10 -07003287 // Check if we want to throttle the processing to no more than 2x normal rate
3288 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003289 mThreadThrottleTimeMs = 0;
3290 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003291 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3292
Andy Hung010a1a12014-03-13 13:57:33 -07003293 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3294 // Originally this was int16_t[] array, need to remove legacy implications.
3295 free(mSinkBuffer);
3296 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003297
Andy Hung5b10a202014-03-13 13:59:29 -07003298 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3299 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3300 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003301 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003302
Andy Hung69aed5f2014-02-25 17:24:40 -08003303 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3304 // drives the output.
3305 free(mMixerBuffer);
3306 mMixerBuffer = NULL;
3307 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003308 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003309 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003310 * audio_bytes_per_sample(mMixerBufferFormat);
3311 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3312 }
Andy Hung98ef9782014-03-04 14:46:50 -08003313 free(mEffectBuffer);
3314 mEffectBuffer = NULL;
3315 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003316 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003317 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003318 * audio_bytes_per_sample(mEffectBufferFormat);
3319 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3320 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003321
Eric Laurentb62d0362021-10-26 17:40:18 +02003322 if (mType == SPATIALIZER) {
3323 free(mPostSpatializerBuffer);
3324 mPostSpatializerBuffer = nullptr;
3325 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3326 * audio_bytes_per_sample(mEffectBufferFormat);
3327 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3328 }
3329
Mikhail Naganov55773032020-10-01 15:08:13 -07003330 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3331 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003332 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3333 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003334 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003335
Eric Laurent81784c32012-11-19 14:55:58 -08003336 // force reconfiguration of effect chains and engines to take new buffer size and audio
3337 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003338 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003339 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3340 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003341 // create a copy of mEffectChains as calling moveEffectChain_ll()
3342 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003343 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003344 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003345 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003346 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003347 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003348
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003349 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003350 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003351 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003352 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003353 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3354 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3355 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3356 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3357 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3358 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3359 (int32_t)mHapticChannelMask)
3360 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3361 (int32_t)mHapticChannelCount)
3362 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003363 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003364 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3365 (int32_t)mFrameCount) // sic - added HAL
3366 ;
3367 uint32_t latencyMs;
3368 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3369 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3370 }
3371 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003372}
3373
Andy Hungee58e4a2023-07-07 13:47:37 -07003374ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003375{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003376 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003377 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003378 }
3379 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003380 static const bool stereo_spatialization_property =
3381 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3382 const bool stereo_spatialization_enabled =
3383 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3384 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003385 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3386 for (const sp<IAfTrack>& track : mActiveTracks) {
3387 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3388 allSessionsMetadata[track->sessionId()];
3389 auto backInserter = std::back_inserter(sessionMetadata);
3390 // No track is invalid as this is called after prepareTrack_l in the same
3391 // critical section
3392 track->copyMetadataTo(backInserter);
3393 }
3394 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3395 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3396 metadata.tracks.insert(metadata.tracks.end(),
3397 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3398 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3399 chain->sendMetadata_l(sessionTrackMetadata, {});
3400 }
3401 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3402 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3403 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3404 }
3405 }
3406 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3407 chain->sendMetadata_l(metadata.tracks, {});
3408 }
3409 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3410 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3411 }
3412 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3413 chain->sendMetadata_l(metadata.tracks, {});
3414 }
3415 } else {
3416 auto backInserter = std::back_inserter(metadata.tracks);
3417 for (const sp<IAfTrack>& track : mActiveTracks) {
3418 // No track is invalid as this is called after prepareTrack_l in the same
3419 // critical section
3420 track->copyMetadataTo(backInserter);
3421 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003422 }
Kevin Rocard12381092018-04-11 09:19:59 -07003423 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003424 MetadataUpdate change;
3425 change.playbackMetadataUpdate = metadata.tracks;
3426 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003427}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003428
Andy Hungee58e4a2023-07-07 13:47:37 -07003429void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003430 const StreamOutHalInterface::SourceMetadata& metadata)
3431{
3432 mOutput->stream->updateSourceMetadata(metadata);
3433};
3434
Andy Hungee58e4a2023-07-07 13:47:37 -07003435status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003436 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003437{
3438 if (halFrames == NULL || dspFrames == NULL) {
3439 return BAD_VALUE;
3440 }
Andy Hung972bec12023-08-31 16:13:39 -07003441 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003442 if (initCheck() != NO_ERROR) {
3443 return INVALID_OPERATION;
3444 }
Andy Hung818e7a32016-02-16 18:08:07 -08003445 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003446 *halFrames = framesWritten;
3447
3448 if (isSuspended()) {
3449 // return an estimation of rendered frames when the output is suspended
3450 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003451 *dspFrames = (uint32_t)
3452 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003453 return NO_ERROR;
3454 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003455 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003456 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003457 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003458 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003459 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003460 }
3461}
3462
Andy Hungee58e4a2023-07-07 13:47:37 -07003463product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003464{
3465 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3466 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3467 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003468 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003469 }
3470 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003471 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003472 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003473 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003474 }
3475 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003476 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003477}
3478
3479
Andy Hungee58e4a2023-07-07 13:47:37 -07003480AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003481{
Andy Hung972bec12023-08-31 16:13:39 -07003482 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003483 return mOutput;
3484}
3485
Andy Hungee58e4a2023-07-07 13:47:37 -07003486AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003487{
Andy Hung972bec12023-08-31 16:13:39 -07003488 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003489 AudioStreamOut *output = mOutput;
3490 mOutput = NULL;
3491 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3492 // must push a NULL and wait for ack
3493 mOutputSink.clear();
3494 mPipeSink.clear();
3495 mNormalSink.clear();
3496 return output;
3497}
3498
Andy Hungc5007f82023-08-29 14:26:09 -07003499// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003500sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003501{
3502 if (mOutput == NULL) {
3503 return NULL;
3504 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003505 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003506}
3507
Andy Hungee58e4a2023-07-07 13:47:37 -07003508uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003509{
3510 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3511}
3512
Andy Hungee58e4a2023-07-07 13:47:37 -07003513status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003514{
3515 if (!isValidSyncEvent(event)) {
3516 return BAD_VALUE;
3517 }
3518
Andy Hung972bec12023-08-31 16:13:39 -07003519 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003520
3521 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003522 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003523 if (event->triggerSession() == track->sessionId()) {
3524 (void) track->setSyncEvent(event);
3525 return NO_ERROR;
3526 }
3527 }
3528
3529 return NAME_NOT_FOUND;
3530}
3531
Andy Hungee58e4a2023-07-07 13:47:37 -07003532bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003533{
3534 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3535}
3536
Andy Hungee58e4a2023-07-07 13:47:37 -07003537void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003538 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003539{
Andy Hungfe726a62018-09-27 15:17:25 -07003540 // Miscellaneous track cleanup when removed from the active list,
3541 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003542#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003543 for (const auto& track : tracksToRemove) {
3544 if (track->isExternalTrack()) {
3545 // to track the speaker usage
3546 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003547 }
3548 }
Andy Hungfe726a62018-09-27 15:17:25 -07003549#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003550}
3551
Andy Hungee58e4a2023-07-07 13:47:37 -07003552void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003553{
3554 if (!mMasterMute) {
3555 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003556 if (mOutDeviceTypeAddrs.empty()) {
3557 ALOGD("ro.audio.silent is ignored since no output device is set");
3558 return;
3559 }
Andy Hungab65b182023-09-06 19:41:47 -07003560 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003561 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3562 return;
3563 }
Eric Laurent81784c32012-11-19 14:55:58 -08003564 if (property_get("ro.audio.silent", value, "0") > 0) {
3565 char *endptr;
3566 unsigned long ul = strtoul(value, &endptr, 0);
3567 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003568 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003569 // The setprop command will not allow a property to be changed after
3570 // the first time it is set, so we don't have to worry about un-muting.
3571 setMasterMute_l(true);
3572 }
3573 }
3574 }
3575}
3576
3577// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003578ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003579{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003580 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003581 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003582 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003583 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003584
3585 // If an NBAIO sink is present, use it to write the normal mixer's submix
3586 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003587
Andy Hung010a1a12014-03-13 13:57:33 -07003588 const size_t count = mBytesRemaining / mFrameSize;
3589
Simon Wilson2d590962012-11-29 15:18:50 -08003590 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003591 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003592 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003593 if (screenState != mScreenState) {
3594 mScreenState = screenState;
3595 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3596 if (pipe != NULL) {
3597 pipe->setAvgFrames((mScreenState & 1) ?
3598 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3599 }
3600 }
Andy Hung010a1a12014-03-13 13:57:33 -07003601 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003602 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003603
Eric Laurent81784c32012-11-19 14:55:58 -08003604 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003605 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003606
Andy Hung8946a282018-04-19 20:04:56 -07003607#ifdef TEE_SINK
3608 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3609#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003610 } else {
3611 bytesWritten = framesWritten;
3612 }
3613 // otherwise use the HAL / AudioStreamOut directly
3614 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003615 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003616
Eric Laurentbfb1b832013-01-07 09:53:42 -08003617 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003618 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3619 mWriteAckSequence += 2;
3620 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003621 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003622 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003624 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003625 // FIXME We should have an implementation of timestamps for direct output threads.
3626 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003627 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003628 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003629
Eric Laurentbfb1b832013-01-07 09:53:42 -08003630 if (mUseAsyncWrite &&
3631 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3632 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003633 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003634 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003635 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003636 }
Eric Laurent81784c32012-11-19 14:55:58 -08003637 }
3638
Eric Laurent81784c32012-11-19 14:55:58 -08003639 mNumWrites++;
3640 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003641 if (mStandby) {
3642 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003643 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003644 mStandby = false;
3645 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003646 return bytesWritten;
3647}
3648
Andy Hungc5007f82023-08-29 14:26:09 -07003649// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003650void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003651 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003652{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003653 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003654 if (outputSink != nullptr) {
3655 outputSink->startMelComputation(processor);
3656 }
Vlad Popab042ee62022-10-20 18:05:00 +02003657}
3658
Andy Hungc5007f82023-08-29 14:26:09 -07003659// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003660void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003661{
3662 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003663 if (outputSink != nullptr) {
3664 outputSink->stopMelComputation();
3665 }
Vlad Popab042ee62022-10-20 18:05:00 +02003666}
3667
Andy Hungee58e4a2023-07-07 13:47:37 -07003668void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003669{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003670 bool supportsDrain = false;
3671 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003672 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3673 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003674 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3675 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003676 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003677 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003678 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003679 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003680 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 }
3682}
3683
Andy Hungee58e4a2023-07-07 13:47:37 -07003684void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003685{
Eric Laurent275e8e92014-11-30 15:14:47 -08003686 {
Andy Hung972bec12023-08-31 16:13:39 -07003687 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003688 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003689 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003690 track->invalidate();
3691 }
Andy Hungdae27702016-10-31 14:01:16 -07003692 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3693 // After we exit there are no more track changes sent to BatteryNotifier
3694 // because that requires an active threadLoop.
3695 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3696 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003697 }
Eric Laurent81784c32012-11-19 14:55:58 -08003698}
3699
3700/*
3701The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003702 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003703 - mActiveSleepTimeUs from activeSleepTimeUs()
3704 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003705 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3706 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003707 - maxPeriod from frame count and sample rate (MIXER only)
3708
3709The parameters that affect these derived values are:
3710 - frame count
3711 - frame size
3712 - sample rate
3713 - device type: A2DP or not
3714 - device latency
3715 - format: PCM or not
3716 - active sleep time
3717 - idle sleep time
3718*/
3719
Andy Hungee58e4a2023-07-07 13:47:37 -07003720void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003721{
Andy Hung25c2dac2014-02-27 14:56:00 -08003722 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003723 mActiveSleepTimeUs = activeSleepTimeUs();
3724 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003725
Andy Hung8fe87eb2023-07-20 21:31:38 -07003726 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003727
Eric Laurent42537be2016-01-08 17:16:42 -08003728 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3729 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003730 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003731 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3732 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3733 }
3734 }
Eric Laurent81784c32012-11-19 14:55:58 -08003735}
3736
Andy Hungee58e4a2023-07-07 13:47:37 -07003737bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003738{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003739 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003740 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003741 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003742 size_t size = mTracks.size();
3743 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003744 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003745 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003746 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003747 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003748 }
3749 }
Eric Laurent13084622016-05-17 10:51:49 -07003750 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003751}
3752
Andy Hungee58e4a2023-07-07 13:47:37 -07003753void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003754{
Andy Hung972bec12023-08-31 16:13:39 -07003755 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003756 invalidateTracks_l(streamType);
3757}
3758
Andy Hungee58e4a2023-07-07 13:47:37 -07003759void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003760 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003761 invalidateTracks_l(portIds);
3762}
3763
Andy Hungee58e4a2023-07-07 13:47:37 -07003764bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003765 bool trackMatch = false;
3766 const size_t size = mTracks.size();
3767 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003768 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003769 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3770 t->invalidate();
3771 portIds.erase(t->portId());
3772 trackMatch = true;
3773 }
3774 if (portIds.empty()) {
3775 break;
3776 }
3777 }
3778 return trackMatch;
3779}
3780
jiabinf042b9b2021-05-07 23:46:28 +00003781// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003782IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003783 audio_port_handle_t trackPortId) {
3784 for (size_t i = 0; i < mTracks.size(); i++) {
3785 if (mTracks[i]->portId() == trackPortId) {
3786 return mTracks[i].get();
3787 }
3788 }
3789 return nullptr;
3790}
3791
Andy Hungee58e4a2023-07-07 13:47:37 -07003792status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003793{
Glenn Kastend848eb42016-03-08 13:42:11 -08003794 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003795 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003796 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003797
Andy Hungd3639922022-04-28 18:00:49 -07003798 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003799 if (!audio_is_global_session(session)) {
3800 // player sessions on a spatializer output will use a dedicated input buffer and
3801 // will either output multi channel to mEffectBuffer if the track is spatilaized
3802 // or stereo to mPostSpatializerBuffer if not spatialized.
3803 uint32_t channelMask;
3804 bool isSessionSpatialized =
3805 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3806 if (isSessionSpatialized) {
3807 channelMask = mMixerChannelMask;
3808 } else {
3809 channelMask = mChannelMask;
3810 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003811 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003812 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003813 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003814 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003815 &halInBuffer);
3816 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003817
Andy Hung583043b2023-07-17 17:05:00 -07003818 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003819 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3820 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3821 &halOutBuffer);
3822 if (result != OK) return result;
3823
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003824 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003825
Mikhail Naganov022b9952017-01-04 16:36:51 -08003826 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3827 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003828 } else {
3829 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3830 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3831 // mPostSpatializerBuffer as output buffer
3832 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003833 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003834 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3835 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003836 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003837 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3838 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003839
Eric Laurentb62d0362021-10-26 17:40:18 +02003840 if (session == AUDIO_SESSION_DEVICE) {
3841 halInBuffer = halOutBuffer;
3842 }
3843 }
3844 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003845 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003846 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3847 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3848 &halInBuffer);
3849 if (result != OK) return result;
3850 halOutBuffer = halInBuffer;
3851 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3852 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003853 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003854 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003855 // Only one effect chain can be present in direct output thread and it uses
3856 // the sink buffer as input
3857 if (mType != DIRECT) {
3858 size_t numSamples = mNormalFrameCount
3859 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3860 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003861 const status_t allocateStatus =
3862 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003863 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003864 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003865 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003866
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003867 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003868 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3869 buffer, session);
3870 }
3871 }
3872 }
3873
3874 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003875 // Attach all tracks with same session ID to this chain.
3876 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003877 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003878 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003879 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3880 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003881 track->setMainBuffer(buffer);
3882 chain->incTrackCnt();
3883 }
3884 }
3885
3886 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003887 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003888 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003889 ALOGV("addEffectChain_l() activating track %p on session %d",
3890 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003891 chain->incActiveTrackCnt();
3892 }
3893 }
3894 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003895
Eric Laurentaaa44472014-09-12 17:41:50 -07003896 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003897 chain->setInBuffer(halInBuffer);
3898 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003899 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3900 // chains list in order to be processed last as it contains output device effects.
3901 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3902 // processing effects specific to an output stream before effects applied to all streams
3903 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003904 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3905 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003906 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003907 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003908 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003909 // Effect chain for other sessions are inserted at beginning of effect
3910 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003911 // sessions is not important.
3912 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003913 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3914 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003915 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003916 size_t size = mEffectChains.size();
3917 size_t i = 0;
3918 for (i = 0; i < size; i++) {
3919 if (mEffectChains[i]->sessionId() < session) {
3920 break;
3921 }
3922 }
3923 mEffectChains.insertAt(chain, i);
3924 checkSuspendOnAddEffectChain_l(chain);
3925
3926 return NO_ERROR;
3927}
3928
Andy Hungee58e4a2023-07-07 13:47:37 -07003929size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003930{
Glenn Kastend848eb42016-03-08 13:42:11 -08003931 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003932
3933 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3934
3935 for (size_t i = 0; i < mEffectChains.size(); i++) {
3936 if (chain == mEffectChains[i]) {
3937 mEffectChains.removeAt(i);
3938 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003939 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003940 if (session == track->sessionId()) {
3941 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3942 chain.get(), session);
3943 chain->decActiveTrackCnt();
3944 }
3945 }
3946
3947 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003948 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003949 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003950 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003951 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003952 chain->decTrackCnt();
3953 }
3954 }
3955 break;
3956 }
3957 }
3958 return mEffectChains.size();
3959}
3960
Andy Hungee58e4a2023-07-07 13:47:37 -07003961status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003962 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003963{
Andy Hung972bec12023-08-31 16:13:39 -07003964 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003965 return attachAuxEffect_l(track, EffectId);
3966}
3967
Andy Hungee58e4a2023-07-07 13:47:37 -07003968status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003969 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003970{
3971 status_t status = NO_ERROR;
3972
3973 if (EffectId == 0) {
3974 track->setAuxBuffer(0, NULL);
3975 } else {
3976 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003977 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003978 if (effect != 0) {
3979 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3980 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3981 } else {
3982 status = INVALID_OPERATION;
3983 }
3984 } else {
3985 status = BAD_VALUE;
3986 }
3987 }
3988 return status;
3989}
3990
Andy Hungee58e4a2023-07-07 13:47:37 -07003991void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003992{
3993 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003994 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003995 if (track->auxEffectId() == effectId) {
3996 attachAuxEffect_l(track, 0);
3997 }
3998 }
3999}
4000
Andy Hungee58e4a2023-07-07 13:47:37 -07004001bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07004002NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08004003{
Andy Hung78d8d952023-05-30 18:10:23 -07004004 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08004005
Andy Hung077d62e2023-10-03 10:49:34 -07004006 if (mType == SPATIALIZER) {
4007 const pid_t tid = getTid();
4008 if (tid == -1) { // odd: we are here, we must be a running thread.
4009 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4010 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004011 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4012 if (priorityBoost > 0) {
4013 stream()->setHalThreadPriority(priorityBoost);
4014 }
Andy Hung077d62e2023-10-03 10:49:34 -07004015 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004016 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4017 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4018 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4019 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4020 // only on ARC.
4021 const pid_t tid = getTid();
4022 if (tid == -1) {
4023 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4024 } else {
4025 const status_t status = requestPriority(getpid(),
4026 tid,
4027 kPriorityPlaybackThreadArc,
4028 false /* isForApp */,
4029 true /* asynchronous */);
4030 if (status != OK) {
4031 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4032 status);
4033 } else {
4034 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4035 }
4036 }
Andy Hung077d62e2023-10-03 10:49:34 -07004037 }
4038
Andy Hung8d31fd22023-06-26 19:20:57 -07004039 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004040
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004041 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004042 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004043
4044 // MIXER
4045 nsecs_t lastWarning = 0;
4046
4047 // DUPLICATING
4048 // FIXME could this be made local to while loop?
4049 writeFrames = 0;
4050
4051 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004052 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004053
Andy Hungd3639922022-04-28 18:00:49 -07004054 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004055 sleepTimeShift = 0;
4056 }
4057
4058 CpuStats cpuStats;
4059 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4060
4061 acquireWakeLock();
4062
Glenn Kasteneef598c2017-04-03 14:41:13 -07004063 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4064 // thread associated with this PlaybackThread.
4065 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4066 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004067 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4068 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004069 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004070 const char *logString = NULL;
4071
rago1bb90822017-05-02 18:31:48 -07004072 // Estimated time for next buffer to be written to hal. This is used only on
4073 // suspended mode (for now) to help schedule the wait time until next iteration.
4074 nsecs_t timeLoopNextNs = 0;
4075
Eric Laurent664539d2013-09-23 18:24:31 -07004076 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004077
Andy Hung2dbffc22018-08-08 18:50:41 -07004078 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004079
Eric Laurentb3f315a2021-07-13 15:09:05 +02004080 sendCheckOutputStageEffectsEvent();
4081
Andy Hung446f4df2019-02-21 12:26:41 -08004082 // loopCount is used for statistics and diagnostics.
4083 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004084 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004085 // Log merge requests are performed during AudioFlinger binder transactions, but
4086 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004087 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004088
Eric Laurent81784c32012-11-19 14:55:58 -08004089 cpuStats.sample(myName);
4090
Andy Hung116bc262023-06-20 18:56:17 -07004091 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004092 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004093 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004094 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004095
Andy Hung2dbffc22018-08-08 18:50:41 -07004096 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4097 //
Andy Hungc5007f82023-08-29 14:26:09 -07004098 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004099 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004100 // Here, we try for the AF lock, but do not block on it as the latency
4101 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004102 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004103 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004104 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004105 status_t status = INVALID_OPERATION;
4106 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004107 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004108 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004109 && swPatches.size() > 0) {
4110 status = swPatches[0].getLatencyMs_l(&latencyMs);
4111 downstreamPatchHandle = swPatches[0].getPatchHandle();
4112 }
4113 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004114 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004115 lastDownstreamPatchHandle = downstreamPatchHandle;
4116 }
4117 if (status == OK) {
4118 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004119 // latency of 5 seconds).
4120 const double minLatency = 0., maxLatency = 5000.;
4121 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004122 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004123 } else {
4124 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004125 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004126 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004127 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004128 }
Andy Hung583043b2023-07-17 17:05:00 -07004129 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004130 }
4131 } else {
4132 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4133 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004134 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004135 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4136 }
4137 }
4138
Eric Laurentb3f315a2021-07-13 15:09:05 +02004139 if (mCheckOutputStageEffects.exchange(false)) {
4140 checkOutputStageEffects();
4141 }
4142
Vlad Popa7e81cea2023-01-19 16:34:16 +01004143 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004144 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004145
Andy Hungc5007f82023-08-29 14:26:09 -07004146 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004147
Eric Laurent021cf962014-05-13 10:18:14 -07004148 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004149 if (mCheckOutputStageEffects.load()) {
4150 continue;
4151 }
Eric Laurent10351942014-05-08 18:49:52 -07004152
Andy Hungc5007f82023-08-29 14:26:09 -07004153 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004154 if (logString != NULL) {
4155 mNBLogWriter->logTimestamp();
4156 mNBLogWriter->log(logString);
4157 logString = NULL;
4158 }
4159
Dean Wheatley12473e92021-03-18 23:00:55 +11004160 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004161
Eric Laurent81784c32012-11-19 14:55:58 -08004162 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004163 if (mSignalPending) {
4164 // A signal was raised while we were unlocked
4165 mSignalPending = false;
4166 } else if (waitingAsyncCallback_l()) {
4167 if (exitPending()) {
4168 break;
4169 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004170 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004171 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004172 releaseWakeLock_l();
4173 released = true;
4174 }
Andy Hung10cbff12017-02-21 17:30:14 -08004175
4176 const int64_t waitNs = computeWaitTimeNs_l();
4177 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004178 std::cv_status cvstatus =
4179 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4180 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004181 mSignalPending = true; // if timeout recheck everything
4182 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004183 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004184 if (released) {
4185 acquireWakeLock_l();
4186 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004187 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4188 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004189
4190 continue;
4191 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004192 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 isSuspended()) {
4194 // put audio hardware into standby after short delay
4195 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004196
4197 threadLoop_standby();
4198
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004199 // This is where we go into standby
4200 if (!mStandby) {
4201 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004202 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004203 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004204 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004205 }
Andy Hungd0979812019-02-21 15:51:44 -08004206 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004207 }
4208
Eric Tan39ec8d62018-07-24 09:49:29 -07004209 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004210 // we're about to wait, flush the binder command buffer
4211 IPCThreadState::self()->flushCommands();
4212
4213 clearOutputTracks();
4214
4215 if (exitPending()) {
4216 break;
4217 }
4218
4219 releaseWakeLock_l();
4220 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004221 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004222 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004223 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004224 acquireWakeLock_l();
4225
4226 mMixerStatus = MIXER_IDLE;
4227 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4228 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004229 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004230 checkSilentMode_l();
4231
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004232 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4233 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004234 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004235 sleepTimeShift = 0;
4236 }
4237
4238 continue;
4239 }
4240 }
Eric Laurent81784c32012-11-19 14:55:58 -08004241 // mMixerStatusIgnoringFastTracks is also updated internally
4242 mMixerStatus = prepareTracks_l(&tracksToRemove);
4243
Andy Hungab65b182023-09-06 19:41:47 -07004244 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004245
Vlad Popa7e81cea2023-01-19 16:34:16 +01004246 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004247
Andy Hungf302e812024-01-26 11:55:15 -08004248 // Acquire a local copy of active tracks with lock (release w/o lock).
4249 //
4250 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4251 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4252 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4253 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4254
4255 setHalLatencyMode_l();
4256
4257 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4258 // so this is done before we lock our effect chains.
4259 for (const auto& track : mActiveTracks) {
4260 track->updateTeePatches_l();
4261 }
4262
4263 // signal actual start of output stream when the render position reported by
4264 // the kernel starts moving.
4265 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4266 && (mKernelPositionOnStandby
4267 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4268 mHalStarted = true;
4269 mWaitHalStartCV.notify_all();
4270 }
4271
Eric Laurent81784c32012-11-19 14:55:58 -08004272 // prevent any changes in effect chain list and in each effect chain
4273 // during mixing and effect process as the audio buffers could be deleted
4274 // or modified if an effect is created or deleted
4275 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004276
4277 // Determine which session to pick up haptic data.
4278 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004279 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004280 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004281 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004282 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004283 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004284 if (effectChain != nullptr
4285 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004286 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004287 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004288 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004289 break;
4290 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004291 if (activeHapticSessionId == AUDIO_SESSION_NONE
4292 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004293 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004294 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004295 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004296 }
4297 }
4298 }
Andy Hungc5007f82023-08-29 14:26:09 -07004299 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004300
Eric Laurentbfb1b832013-01-07 09:53:42 -08004301 if (mBytesRemaining == 0) {
4302 mCurrentWriteLength = 0;
4303 if (mMixerStatus == MIXER_TRACKS_READY) {
4304 // threadLoop_mix() sets mCurrentWriteLength
4305 threadLoop_mix();
4306 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4307 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004308 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004309 // must be written to HAL
4310 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004311 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004312 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004313
4314 // Tally underrun frames as we are inserting 0s here.
4315 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004316 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004317 && !track->isStopped()
4318 && !track->isPaused()
4319 && !track->isTerminated()) {
4320 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4321 __func__, track->id(), track->getTrackStateAsString(),
4322 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004323 track->audioTrackServerProxy()->tallyUnderrunFrames(
4324 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004325 }
4326 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004327 }
4328 }
Andy Hung98ef9782014-03-04 14:46:50 -08004329 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004330 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004331 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004332 // or mSinkBuffer (if there are no effects and there is no data already copied to
4333 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004334 //
4335 // This is done pre-effects computation; if effects change to
4336 // support higher precision, this needs to move.
4337 //
4338 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004339 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004340 uint32_t mixerChannelCount = mEffectBufferValid ?
4341 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004342 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004343 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4344 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4345
David Li88ee0902022-06-22 10:01:21 +08004346 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4347 // do these processes after effects are applied.
4348 if (!mEffectBufferValid) {
4349 // mono blend occurs for mixer threads only (not direct or offloaded)
4350 // and is handled here if we're going directly to the sink.
4351 if (requireMonoBlend()) {
4352 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4353 mNormalFrameCount, true /*limit*/);
4354 }
Andy Hung2ddee192015-12-18 17:34:44 -08004355
David Li88ee0902022-06-22 10:01:21 +08004356 if (!hasFastMixer()) {
4357 // Balance must take effect after mono conversion.
4358 // We do it here if there is no FastMixer.
4359 // mBalance detects zero balance within the class for speed
4360 // (not needed here).
4361 mBalance.setBalance(mMasterBalance.load());
4362 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4363 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004364 }
4365
Andy Hung98ef9782014-03-04 14:46:50 -08004366 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004367 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004368
4369 // If we're going directly to the sink and there are haptic channels,
4370 // we should adjust channels as the sample data is partially interleaved
4371 // in this case.
4372 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4373 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4374 mChannelCount + mHapticChannelCount,
4375 audio_bytes_per_sample(format),
4376 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4377 }
Andy Hung98ef9782014-03-04 14:46:50 -08004378 }
4379
Eric Laurentbfb1b832013-01-07 09:53:42 -08004380 mBytesRemaining = mCurrentWriteLength;
4381 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004382 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4383 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4384 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4385 mBytesWritten += mBytesRemaining;
4386 mFramesWritten += framesRemaining;
4387 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004388 mBytesRemaining = 0;
4389 }
Eric Laurent81784c32012-11-19 14:55:58 -08004390
Eric Laurentbfb1b832013-01-07 09:53:42 -08004391 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004392 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004393 for (size_t i = 0; i < effectChains.size(); i ++) {
4394 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004395 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004396 if (activeHapticSessionId != AUDIO_SESSION_NONE
4397 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004398 // Haptic data is active in this case, copy it directly from
4399 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004400 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4401 audio_channel_count_from_out_mask(mMixerChannelMask) :
4402 mChannelCount;
4403 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4404 hapticSessionChannelCount = mChannelCount;
4405 }
4406
jiabin47affe52019-04-04 18:02:07 -07004407 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004408 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004409 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004410 memcpy_by_audio_format(
4411 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004412 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004413 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004414 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004415 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004416 }
Eric Laurent81784c32012-11-19 14:55:58 -08004417 }
4418 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004419 // Process effect chains for offloaded thread even if no audio
4420 // was read from audio track: process only updates effect state
4421 // and thus does have to be synchronized with audio writes but may have
4422 // to be called while waiting for async write callback
4423 if (mType == OFFLOAD) {
4424 for (size_t i = 0; i < effectChains.size(); i ++) {
4425 effectChains[i]->process_l();
4426 }
4427 }
Eric Laurent81784c32012-11-19 14:55:58 -08004428
Andy Hung98ef9782014-03-04 14:46:50 -08004429 // Only if the Effects buffer is enabled and there is data in the
4430 // Effects buffer (buffer valid), we need to
4431 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004432 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004433 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004434 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004435 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004436 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004437 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004438 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004439 }
4440
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004441 if (!hasFastMixer()) {
4442 // Balance must take effect after mono conversion.
4443 // We do it here if there is no FastMixer.
4444 // mBalance detects zero balance within the class for speed (not needed here).
4445 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004446 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004447 }
4448
Eric Laurentb62d0362021-10-26 17:40:18 +02004449 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4450 // mPostSpatializerBuffer if the haptics track is spatialized.
4451 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4452 // For other thread types, the haptics channels are already in mEffectBuffer.
4453 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4454 const size_t srcBufferSize = mNormalFrameCount *
4455 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4456 mEffectBufferFormat);
4457 const size_t dstBufferSize = mNormalFrameCount
4458 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4459
4460 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4461 mEffectBufferFormat,
4462 (uint8_t*)mEffectBuffer + srcBufferSize,
4463 mEffectBufferFormat,
4464 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004465 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004466 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4467 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4468 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4469 // Clamp PCM float values more than this distance from 0 to insulate
4470 // a HAL which doesn't handle NaN correctly.
4471 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4472 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4473 static_cast<const float*>(effectBuffer),
4474 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4475 } else {
4476 memcpy_by_audio_format(mSinkBuffer, mFormat,
4477 effectBuffer, mEffectBufferFormat, framesToCopy);
4478 }
jiabin245cdd92018-12-07 17:55:15 -08004479 // The sample data is partially interleaved when haptic channels exist,
4480 // we need to adjust channels here.
4481 if (mHapticChannelCount > 0) {
4482 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4483 mChannelCount + mHapticChannelCount,
4484 audio_bytes_per_sample(mFormat),
4485 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4486 }
Andy Hung98ef9782014-03-04 14:46:50 -08004487 }
4488
Eric Laurent81784c32012-11-19 14:55:58 -08004489 // enable changes in effect chain
4490 unlockEffectChains(effectChains);
4491
Vlad Popafce10862023-02-03 10:37:07 +01004492 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004493 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004494 metadataUpdate.playbackMetadataUpdate);
4495 }
4496
Eric Laurentbfb1b832013-01-07 09:53:42 -08004497 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004498 // mSleepTimeUs == 0 means we must write to audio hardware
4499 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004500 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004501 // writePeriodNs is updated >= 0 when ret > 0.
4502 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004503 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004504 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004505 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004506 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004507 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004508 if (ret < 0) {
4509 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004510 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004511 mBytesWritten += ret;
4512 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004513 const int64_t frames = ret / mFrameSize;
4514 mFramesWritten += frames;
4515
4516 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4517 // process information relating to write time.
4518 if (audio_has_proportional_frames(mFormat)) {
4519 // we are in a continuous mixing cycle
4520 if (mMixerStatus == MIXER_TRACKS_READY &&
4521 loopCount == lastLoopCountWritten + 1) {
4522
4523 const double jitterMs =
4524 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4525 {frames, writePeriodNs},
4526 {0, 0} /* lastTimestamp */, mSampleRate);
4527 const double processMs =
4528 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4529
Andy Hung972bec12023-08-31 16:13:39 -07004530 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004531 mIoJitterMs.add(jitterMs);
4532 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004533
4534 if (mPipeSink.get() != nullptr) {
4535 // Using the Monopipe availableToWrite, we estimate the current
4536 // buffer size.
4537 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4538 const ssize_t
4539 availableToWrite = mPipeSink->availableToWrite();
4540 const size_t pipeFrames = monoPipe->maxFrames();
4541 const size_t
4542 remainingFrames = pipeFrames - max(availableToWrite, 0);
4543 mMonopipePipeDepthStats.add(remainingFrames);
4544 }
Andy Hung446f4df2019-02-21 12:26:41 -08004545 }
4546
4547 // write blocked detection
4548 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004549 if ((mType == MIXER || mType == SPATIALIZER)
4550 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004551 mNumDelayedWrites++;
4552 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4553 ATRACE_NAME("underrun");
4554 ALOGW("write blocked for %lld msecs, "
4555 "%d delayed writes, thread %d",
4556 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4557 mNumDelayedWrites, mId);
4558 lastWarning = lastIoEndNs;
4559 }
4560 }
4561 }
4562 // update timing info.
4563 mLastIoBeginNs = lastIoBeginNs;
4564 mLastIoEndNs = lastIoEndNs;
4565 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004566 }
4567 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4568 (mMixerStatus == MIXER_DRAIN_ALL)) {
4569 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004570 }
Andy Hungd3639922022-04-28 18:00:49 -07004571 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004572
4573 if (mThreadThrottle
4574 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004575 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004576 // Limit MixerThread data processing to no more than twice the
4577 // expected processing rate.
4578 //
4579 // This helps prevent underruns with NuPlayer and other applications
4580 // which may set up buffers that are close to the minimum size, or use
4581 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4582 //
4583 // The throttle smooths out sudden large data drains from the device,
4584 // e.g. when it comes out of standby, which often causes problems with
4585 // (1) mixer threads without a fast mixer (which has its own warm-up)
4586 // (2) minimum buffer sized tracks (even if the track is full,
4587 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004588 //
4589 // Total time spent in last processing cycle equals time spent in
4590 // 1. threadLoop_write, as well as time spent in
4591 // 2. threadLoop_mix (significant for heavy mixing, especially
4592 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004593
Andy Hung446f4df2019-02-21 12:26:41 -08004594 // it's OK if deltaMs is an overestimate.
4595
4596 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004597
Ivan Lozanoea04d392017-11-07 14:37:07 -08004598 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004599 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004600 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004601
Andy Hung08fb1742015-05-31 23:22:10 -07004602 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004603 // notify of throttle start on verbose log
4604 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4605 "mixer(%p) throttle begin:"
4606 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004607 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004608 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004609 // Throttle must be attributed to the previous mixer loop's write time
4610 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004611 // This also ensures proper timing statistics.
4612 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004613 } else {
4614 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4615 if (diff > 0) {
4616 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004617 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004618 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004619 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004620 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004621 outDeviceTypes_l(),
4622 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004623 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004624 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4625 }
Andy Hung08fb1742015-05-31 23:22:10 -07004626 }
4627 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004628 }
Eric Laurent81784c32012-11-19 14:55:58 -08004629
Eric Laurentbfb1b832013-01-07 09:53:42 -08004630 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004631 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004632 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004633 // suspended requires accurate metering of sleep time.
4634 if (isSuspended()) {
4635 // advance by expected sleepTime
4636 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4637 const nsecs_t nowNs = systemTime();
4638
4639 // compute expected next time vs current time.
4640 // (negative deltas are treated as delays).
4641 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4642 if (deltaNs < -kMaxNextBufferDelayNs) {
4643 // Delays longer than the max allowed trigger a reset.
4644 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4645 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4646 timeLoopNextNs = nowNs + deltaNs;
4647 } else if (deltaNs < 0) {
4648 // Delays within the max delay allowed: zero the delta/sleepTime
4649 // to help the system catch up in the next iteration(s)
4650 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4651 deltaNs = 0;
4652 }
4653 // update sleep time (which is >= 0)
4654 mSleepTimeUs = deltaNs / 1000;
4655 }
Eric Laurente93cc032016-05-05 10:15:10 -07004656 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004657 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004658 }
Glenn Kastene7754022014-10-31 12:11:26 -07004659 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004660 }
Eric Laurent81784c32012-11-19 14:55:58 -08004661 }
4662
4663 // Finally let go of removed track(s), without the lock held
4664 // since we can't guarantee the destructors won't acquire that
4665 // same lock. This will also mutate and push a new fast mixer state.
4666 threadLoop_removeTracks(tracksToRemove);
4667 tracksToRemove.clear();
4668
4669 // FIXME I don't understand the need for this here;
4670 // it was in the original code but maybe the
4671 // assignment in saveOutputTracks() makes this unnecessary?
4672 clearOutputTracks();
4673
4674 // Effect chains will be actually deleted here if they were removed from
4675 // mEffectChains list during mixing or effects processing
4676 effectChains.clear();
4677
4678 // FIXME Note that the above .clear() is no longer necessary since effectChains
4679 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004680
4681 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004682 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004683 mThreadloopExecutor.process(); // process any remaining deferred actions.
4684 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004685
Eric Laurentbfb1b832013-01-07 09:53:42 -08004686 threadLoop_exit();
4687
Eric Laurentcf817a22014-08-04 20:36:31 -07004688 if (!mStandby) {
4689 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004690 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004691 }
4692
4693 releaseWakeLock();
4694
4695 ALOGV("Thread %p type %d exiting", this, mType);
4696 return false;
4697}
4698
Andy Hungee58e4a2023-07-07 13:47:37 -07004699void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004700{
Dean Wheatley12473e92021-03-18 23:00:55 +11004701 if (mStandby) {
4702 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4703 return;
4704 } else if (mHwPaused) {
4705 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4706 return;
4707 }
4708
4709 // Gather the framesReleased counters for all active tracks,
4710 // and associate with the sink frames written out. We need
4711 // this to convert the sink timestamp to the track timestamp.
4712 bool kernelLocationUpdate = false;
4713 ExtendedTimestamp timestamp; // use private copy to fetch
4714
4715 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4716 // HAL may be draining some small duration buffered data for fade out.
4717 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4718 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4719 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4720 mSampleRate);
4721
Andy Hungab65b182023-09-06 19:41:47 -07004722 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004723 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4724 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4725 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4726 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4727 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4728 = correctedTimestamp.mFrames;
4729 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4730 = correctedTimestamp.mTimeNs;
4731 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4732 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4733 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4734
4735 // Note: Downstream latency only added if timestamp correction enabled.
4736 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4737 const int64_t newPosition =
4738 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4739 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4740 // prevent retrograde
4741 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4742 newPosition,
4743 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4744 - mSuspendedFrames));
4745 }
4746 }
4747
4748 // We always fetch the timestamp here because often the downstream
4749 // sink will block while writing.
4750
4751 // We keep track of the last valid kernel position in case we are in underrun
4752 // and the normal mixer period is the same as the fast mixer period, or there
4753 // is some error from the HAL.
4754 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4755 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4756 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4757 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4758 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4759
4760 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4761 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4762 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4763 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4764 }
4765
4766 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4767 kernelLocationUpdate = true;
4768 } else {
4769 ALOGVV("getTimestamp error - no valid kernel position");
4770 }
4771
4772 // copy over kernel info
4773 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4774 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4775 + mSuspendedFrames; // add frames discarded when suspended
4776 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4777 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4778 } else {
4779 mTimestampVerifier.error();
4780 }
4781
4782 // mFramesWritten for non-offloaded tracks are contiguous
4783 // even after standby() is called. This is useful for the track frame
4784 // to sink frame mapping.
4785 bool serverLocationUpdate = false;
4786 if (mFramesWritten != mLastFramesWritten) {
4787 serverLocationUpdate = true;
4788 mLastFramesWritten = mFramesWritten;
4789 }
4790 // Only update timestamps if there is a meaningful change.
4791 // Either the kernel timestamp must be valid or we have written something.
4792 if (kernelLocationUpdate || serverLocationUpdate) {
4793 if (serverLocationUpdate) {
4794 // use the time before we called the HAL write - it is a bit more accurate
4795 // to when the server last read data than the current time here.
4796 //
4797 // If we haven't written anything, mLastIoBeginNs will be -1
4798 // and we use systemTime().
4799 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4800 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004801 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004802 }
4803
Andy Hung8d31fd22023-06-26 19:20:57 -07004804 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004805 if (!t->isFastTrack()) {
4806 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004807 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004808 mFramesWritten,
4809 mSampleRate,
4810 mTimestamp);
4811 }
4812 }
4813 }
4814
4815 if (audio_has_proportional_frames(mFormat)) {
4816 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4817 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4818 mLatencyMs.add(latencyMs);
4819 }
4820 }
4821#if 0
4822 // logFormat example
4823 if (z % 100 == 0) {
4824 timespec ts;
4825 clock_gettime(CLOCK_MONOTONIC, &ts);
4826 LOGT("This is an integer %d, this is a float %f, this is my "
4827 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4828 LOGT("A deceptive null-terminated string %\0");
4829 }
4830 ++z;
4831#endif
4832}
4833
Andy Hungc5007f82023-08-29 14:26:09 -07004834// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004835void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004836NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004837{
Andy Hung6c498e92023-12-05 17:28:17 -08004838 if (tracksToRemove.empty()) return;
4839
4840 // Block all incoming TrackHandle requests until we are finished with the release.
4841 setThreadBusy_l(true);
4842
Andy Hungfe726a62018-09-27 15:17:25 -07004843 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004844 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004845 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004846 if (chain != 0) {
4847 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4848 __func__, track->id(), chain.get(), track->sessionId());
4849 chain->decActiveTrackCnt();
4850 }
Andy Hung6c498e92023-12-05 17:28:17 -08004851
Andy Hungfe726a62018-09-27 15:17:25 -07004852 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004853 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004854 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004855 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004856 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004857 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004858 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004859 }
Andy Hung6c498e92023-12-05 17:28:17 -08004860 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004861 }
jiabineb3bda02020-06-30 14:07:03 -07004862 if (mHapticChannelCount > 0 &&
4863 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004864 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004865 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004866 // Unlock due to VibratorService will lock for this call and will
4867 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004868 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004869 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004870
4871 // When the track is stop, set the haptic intensity as MUTE
4872 // for the HapticGenerator effect.
4873 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004874 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004875 }
jiabin245cdd92018-12-07 17:55:15 -08004876 }
Andy Hung6c498e92023-12-05 17:28:17 -08004877
4878 // Under lock, the track is removed from the active tracks list.
4879 //
4880 // Once the track is no longer active, the TrackHandle may directly
4881 // modify it as the threadLoop() is no longer responsible for its maintenance.
4882 // Do not modify the track from threadLoop after the mutex is unlocked
4883 // if it is not active.
4884 mActiveTracks.remove(track);
4885
4886 if (track->isTerminated()) {
4887 // remove from our tracks vector
4888 removeTrack_l(track);
4889 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004890 }
Andy Hung6c498e92023-12-05 17:28:17 -08004891
4892 // Allow incoming TrackHandle requests. We still hold the mutex,
4893 // so pending TrackHandle requests will occur after we unlock it.
4894 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004895}
Eric Laurent81784c32012-11-19 14:55:58 -08004896
Andy Hungee58e4a2023-07-07 13:47:37 -07004897status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004898{
4899 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004900 ExtendedTimestamp ets;
4901 status_t status = mNormalSink->getTimestamp(ets);
4902 if (status == NO_ERROR) {
4903 status = ets.getBestTimestamp(&timestamp);
4904 }
4905 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004906 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004907 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004908 collectTimestamps_l();
4909 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4910 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004911 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004912 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4913 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4914 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4915 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4916 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004917 }
4918 return INVALID_OPERATION;
4919}
Eric Laurent1c333e22014-05-20 10:48:17 -07004920
Eric Laurenteab90452019-06-24 15:17:46 -07004921// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4922// still applied by the mixer.
4923// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4924// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4925// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004926status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004927{
4928 status_t result = NO_ERROR;
4929 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4930 if (*volume != mLeftVolFloat) {
4931 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004932 // HAL can return INVALID_OPERATION if operation is not supported.
4933 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004934 "Error when setting output stream volume: %d", result);
4935 if (result == NO_ERROR) {
4936 mLeftVolFloat = *volume;
4937 }
4938 }
4939 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4940 // remove stream volume contribution from software volume.
4941 if (mLeftVolFloat == *volume) {
4942 *volume = 1.0f;
4943 }
4944 }
4945 return result;
4946}
4947
Andy Hungee58e4a2023-07-07 13:47:37 -07004948status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004949 audio_patch_handle_t *handle)
4950{
Andy Hungf60abce2016-08-26 11:37:54 -07004951 status_t status;
4952 if (property_get_bool("af.patch_park", false /* default_value */)) {
4953 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4954 // or if HAL does not properly lock against access.
4955 AutoPark<FastMixer> park(mFastMixer);
4956 status = PlaybackThread::createAudioPatch_l(patch, handle);
4957 } else {
4958 status = PlaybackThread::createAudioPatch_l(patch, handle);
4959 }
Eric Laurentb0463942022-12-20 16:31:10 +01004960
4961 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004962 return status;
4963}
4964
Andy Hungee58e4a2023-07-07 13:47:37 -07004965status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004966 audio_patch_handle_t *handle)
4967{
4968 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004969
4970 // store new device and send to effects
4971 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004972 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004973 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004974 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4975 && !mOutput->audioHwDev->supportsAudioPatches(),
4976 "Enumerated device type(%#x) must not be used "
4977 "as it does not support audio patches",
4978 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004979 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004980 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4981 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004982 }
4983
François Gaffie0c280aa2018-07-25 10:02:15 +02004984 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004985#ifdef ADD_BATTERY_DATA
4986 // when changing the audio output device, call addBatteryData to notify
4987 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004988 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004989 uint32_t params = 0;
4990 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004991 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004992 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004993 }
4994
Eric Laurent054d9d32015-04-24 08:48:48 -07004995 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004996 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004997 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4998 }
4999
5000 if (params != 0) {
5001 addBatteryData(params);
5002 }
5003 }
5004#endif
5005
5006 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08005007 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005008 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005009
jiabinc52b1ff2019-10-31 17:20:42 -07005010 // mPatch.num_sinks is not set when the thread is created so that
5011 // the first patch creation triggers an ioConfigChanged callback
5012 bool configChanged = (mPatch.num_sinks == 0) ||
5013 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005014 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005015 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005016 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005017
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005018 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005019 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5020 status = hwDevice->createAudioPatch(patch->num_sources,
5021 patch->sources,
5022 patch->num_sinks,
5023 patch->sinks,
5024 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005025 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005026 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005027 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005028 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005029 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005030
5031 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005032 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005033 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005034 // also dispatch to active AudioTracks for MediaMetrics
5035 for (const auto &track : mActiveTracks) {
5036 track->logEndInterval();
5037 track->logBeginInterval(patchSinksAsString);
5038 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005039
Eric Laurente8726fe2015-06-26 09:39:24 -07005040 if (configChanged) {
5041 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5042 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005043 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005044 mActiveTracks.setHasChanged();
5045
Eric Laurent1c333e22014-05-20 10:48:17 -07005046 return status;
5047}
5048
Andy Hungee58e4a2023-07-07 13:47:37 -07005049status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005050{
Andy Hungf60abce2016-08-26 11:37:54 -07005051 status_t status;
5052 if (property_get_bool("af.patch_park", false /* default_value */)) {
5053 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5054 // or if HAL does not properly lock against access.
5055 AutoPark<FastMixer> park(mFastMixer);
5056 status = PlaybackThread::releaseAudioPatch_l(handle);
5057 } else {
5058 status = PlaybackThread::releaseAudioPatch_l(handle);
5059 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005060 return status;
5061}
5062
Andy Hungee58e4a2023-07-07 13:47:37 -07005063status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005064{
5065 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005066
jiabinc52b1ff2019-10-31 17:20:42 -07005067 mPatch = audio_patch{};
5068 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005069
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005070 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005071 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5072 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005073 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005074 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005075 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005076 // Force meteadata update after a route change
5077 mActiveTracks.setHasChanged();
5078
Eric Laurent1c333e22014-05-20 10:48:17 -07005079 return status;
5080}
5081
Andy Hungee58e4a2023-07-07 13:47:37 -07005082void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005083{
Andy Hung972bec12023-08-31 16:13:39 -07005084 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005085 mTracks.add(track);
5086}
5087
Andy Hungee58e4a2023-07-07 13:47:37 -07005088void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005089{
Andy Hung972bec12023-08-31 16:13:39 -07005090 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005091 destroyTrack_l(track);
5092}
5093
Andy Hungee58e4a2023-07-07 13:47:37 -07005094void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005095{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005096 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005097 config->role = AUDIO_PORT_ROLE_SOURCE;
5098 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5099 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005100 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5101 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5102 config->flags.output = mOutput->flags;
5103 }
Eric Laurent83b88082014-06-20 18:31:16 -07005104}
5105
Eric Laurent81784c32012-11-19 14:55:58 -08005106// ----------------------------------------------------------------------------
5107
Andy Hungee58e4a2023-07-07 13:47:37 -07005108/* static */
5109sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005110 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005111 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005112 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005113}
5114
Andy Hung583043b2023-07-17 17:05:00 -07005115MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005116 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005117 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005118 // mAudioMixer below
5119 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005120 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005121 mFastMixerFutex(0),
5122 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005123 // mOutputSink below
5124 // mPipeSink below
5125 // mNormalSink below
5126{
jiabinc52b1ff2019-10-31 17:20:42 -07005127 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005128 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005129 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005130 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5131 mNormalFrameCount);
5132 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5133
Andy Hungfbfc3952015-01-15 13:33:51 -08005134 if (type == DUPLICATING) {
5135 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5136 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5137 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005138 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5139 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005140 return;
5141 }
Eric Laurent81784c32012-11-19 14:55:58 -08005142 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005143 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005144 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005145 const NBAIO_Format offers[1] = {Format_from_SR_C(
5146 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005147#if !LOG_NDEBUG
5148 ssize_t index =
5149#else
5150 (void)
5151#endif
5152 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005153 ALOG_ASSERT(index == 0);
5154
5155 // initialize fast mixer depending on configuration
5156 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005157 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005158 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005159 } else {
5160 switch (kUseFastMixer) {
5161 case FastMixer_Never:
5162 initFastMixer = false;
5163 break;
5164 case FastMixer_Always:
5165 initFastMixer = true;
5166 break;
5167 case FastMixer_Static:
5168 case FastMixer_Dynamic:
5169 initFastMixer = mFrameCount < mNormalFrameCount;
5170 break;
5171 }
5172 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5173 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5174 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005175 }
5176 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005177 audio_format_t fastMixerFormat;
5178 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5179 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5180 } else {
5181 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5182 }
5183 if (mFormat != fastMixerFormat) {
5184 // change our Sink format to accept our intermediate precision
5185 mFormat = fastMixerFormat;
5186 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005187 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005188 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5189 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5190 }
Eric Laurent81784c32012-11-19 14:55:58 -08005191
5192 // create a MonoPipe to connect our submix to FastMixer
5193 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005194
Andy Hung1258c1a2014-05-23 21:22:17 -07005195 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005196 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005197 format.mFormat = fastMixerFormat;
5198 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5199
Eric Laurent81784c32012-11-19 14:55:58 -08005200 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5201 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5202 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5203 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005204 const NBAIO_Format offersFast[1] = {format};
5205 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005206#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005207 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005208#else
5209 (void)
5210#endif
Andy Hung920f6572022-10-06 12:09:49 -07005211 monoPipe->negotiate(offersFast, std::size(offersFast),
5212 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005213 ALOG_ASSERT(index == 0);
5214 monoPipe->setAvgFrames((mScreenState & 1) ?
5215 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5216 mPipeSink = monoPipe;
5217
Eric Laurent81784c32012-11-19 14:55:58 -08005218 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005219 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005220 FastMixerStateQueue *sq = mFastMixer->sq();
5221#ifdef STATE_QUEUE_DUMP
5222 sq->setObserverDump(&mStateQueueObserverDump);
5223 sq->setMutatorDump(&mStateQueueMutatorDump);
5224#endif
5225 FastMixerState *state = sq->begin();
5226 FastTrack *fastTrack = &state->mFastTracks[0];
5227 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5228 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5229 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005230 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5231 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5232 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005233 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005234 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005235 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005236 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005237 fastTrack->mGeneration++;
5238 state->mFastTracksGen++;
5239 state->mTrackMask = 1;
5240 // fast mixer will use the HAL output sink
5241 state->mOutputSink = mOutputSink.get();
5242 state->mOutputSinkGen++;
5243 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005244 // specify sink channel mask when haptic channel mask present as it can not
5245 // be calculated directly from channel count
5246 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005247 ? AUDIO_CHANNEL_NONE
5248 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005249 state->mCommand = FastMixerState::COLD_IDLE;
5250 // already done in constructor initialization list
5251 //mFastMixerFutex = 0;
5252 state->mColdFutexAddr = &mFastMixerFutex;
5253 state->mColdGen++;
5254 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005255 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005256 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005257 sq->end();
5258 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5259
Eric Tan0513b5d2018-09-17 10:32:48 -07005260 NBLog::thread_info_t info;
5261 info.id = mId;
5262 info.type = NBLog::FASTMIXER;
5263 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5264
Eric Laurent81784c32012-11-19 14:55:58 -08005265 // start the fast mixer
5266 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5267 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005268 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005269 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005270
5271#ifdef AUDIO_WATCHDOG
5272 // create and start the watchdog
5273 mAudioWatchdog = new AudioWatchdog();
5274 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5275 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5276 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005277 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005278#endif
Andy Hung8946a282018-04-19 20:04:56 -07005279 } else {
5280#ifdef TEE_SINK
5281 // Only use the MixerThread tee if there is no FastMixer.
5282 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5283 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5284#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005285 }
5286
5287 switch (kUseFastMixer) {
5288 case FastMixer_Never:
5289 case FastMixer_Dynamic:
5290 mNormalSink = mOutputSink;
5291 break;
5292 case FastMixer_Always:
5293 mNormalSink = mPipeSink;
5294 break;
5295 case FastMixer_Static:
5296 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5297 break;
5298 }
Andy Hung922617c2024-06-25 17:07:58 -07005299 // setMasterBalance needs to be called after the FastMixer
5300 // (if any) is set up, in order to deliver the balance settings to it.
5301 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005302}
5303
Andy Hungee58e4a2023-07-07 13:47:37 -07005304MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005305{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005306 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005307 FastMixerStateQueue *sq = mFastMixer->sq();
5308 FastMixerState *state = sq->begin();
5309 if (state->mCommand == FastMixerState::COLD_IDLE) {
5310 int32_t old = android_atomic_inc(&mFastMixerFutex);
5311 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005312 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005313 }
5314 }
5315 state->mCommand = FastMixerState::EXIT;
5316 sq->end();
5317 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5318 mFastMixer->join();
5319 // Though the fast mixer thread has exited, it's state queue is still valid.
5320 // We'll use that extract the final state which contains one remaining fast track
5321 // corresponding to our sub-mix.
5322 state = sq->begin();
5323 ALOG_ASSERT(state->mTrackMask == 1);
5324 FastTrack *fastTrack = &state->mFastTracks[0];
5325 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5326 delete fastTrack->mBufferProvider;
5327 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005328 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005329#ifdef AUDIO_WATCHDOG
5330 if (mAudioWatchdog != 0) {
5331 mAudioWatchdog->requestExit();
5332 mAudioWatchdog->requestExitAndWait();
5333 mAudioWatchdog.clear();
5334 }
5335#endif
5336 }
Andy Hung583043b2023-07-17 17:05:00 -07005337 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005338 delete mAudioMixer;
5339}
5340
Andy Hungee58e4a2023-07-07 13:47:37 -07005341void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005342 PlaybackThread::onFirstRef();
5343
Andy Hung972bec12023-08-31 16:13:39 -07005344 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005345 if (mOutput != nullptr && mOutput->stream != nullptr) {
5346 status_t status = mOutput->stream->setLatencyModeCallback(this);
5347 if (status != INVALID_OPERATION) {
5348 updateHalSupportedLatencyModes_l();
5349 }
5350 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5351 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5352 mBluetoothLatencyModesEnabled.store(
5353 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5354 }
5355}
Eric Laurent81784c32012-11-19 14:55:58 -08005356
Andy Hungee58e4a2023-07-07 13:47:37 -07005357uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005358{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005359 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005360 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5361 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5362 }
5363 return latency;
5364}
5365
Andy Hungee58e4a2023-07-07 13:47:37 -07005366ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005367{
5368 // FIXME we should only do one push per cycle; confirm this is true
5369 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005370 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005371 FastMixerStateQueue *sq = mFastMixer->sq();
5372 FastMixerState *state = sq->begin();
5373 if (state->mCommand != FastMixerState::MIX_WRITE &&
5374 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5375 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005376
5377 // FIXME workaround for first HAL write being CPU bound on some devices
5378 ATRACE_BEGIN("write");
5379 mOutput->write((char *)mSinkBuffer, 0);
5380 ATRACE_END();
5381
Eric Laurent81784c32012-11-19 14:55:58 -08005382 int32_t old = android_atomic_inc(&mFastMixerFutex);
5383 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005384 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005385 }
5386#ifdef AUDIO_WATCHDOG
5387 if (mAudioWatchdog != 0) {
5388 mAudioWatchdog->resume();
5389 }
5390#endif
5391 }
5392 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005393#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005394 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005395 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005396#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005397 sq->end();
5398 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5399 if (kUseFastMixer == FastMixer_Dynamic) {
5400 mNormalSink = mPipeSink;
5401 }
5402 } else {
5403 sq->end(false /*didModify*/);
5404 }
5405 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005406 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005407}
5408
Andy Hungee58e4a2023-07-07 13:47:37 -07005409void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005410{
5411 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005412 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005413 FastMixerStateQueue *sq = mFastMixer->sq();
5414 FastMixerState *state = sq->begin();
5415 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005416 // Report any frames trapped in the Monopipe
5417 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5418 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5419 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5420 "monoPipeWritten:%lld monoPipeLeft:%lld",
5421 (long long)mFramesWritten, (long long)mSuspendedFrames,
5422 (long long)mPipeSink->framesWritten(), pipeFrames);
5423 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5424
Eric Laurent81784c32012-11-19 14:55:58 -08005425 state->mCommand = FastMixerState::COLD_IDLE;
5426 state->mColdFutexAddr = &mFastMixerFutex;
5427 state->mColdGen++;
5428 mFastMixerFutex = 0;
5429 sq->end();
5430 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5431 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5432 if (kUseFastMixer == FastMixer_Dynamic) {
5433 mNormalSink = mOutputSink;
5434 }
5435#ifdef AUDIO_WATCHDOG
5436 if (mAudioWatchdog != 0) {
5437 mAudioWatchdog->pause();
5438 }
5439#endif
5440 } else {
5441 sq->end(false /*didModify*/);
5442 }
5443 }
5444 PlaybackThread::threadLoop_standby();
5445}
5446
Andy Hungee58e4a2023-07-07 13:47:37 -07005447bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005448{
5449 return false;
5450}
5451
Andy Hungee58e4a2023-07-07 13:47:37 -07005452bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005453{
5454 return !mStandby;
5455}
5456
Andy Hungee58e4a2023-07-07 13:47:37 -07005457bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005458{
Andy Hung972bec12023-08-31 16:13:39 -07005459 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005460 return waitingAsyncCallback_l();
5461}
5462
Eric Laurent81784c32012-11-19 14:55:58 -08005463// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005464void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005465{
Andy Hung8d672e02023-09-15 18:19:28 -07005466 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5467 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005468 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005469 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005470 // discard any pending drain or write ack by incrementing sequence
5471 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5472 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005473 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005474 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5475 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005476 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005477 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005478 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005479}
5480
Andy Hungee58e4a2023-07-07 13:47:37 -07005481void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005482{
5483 ALOGV("signal playback thread");
5484 broadcast_l();
5485}
5486
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005487void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005488{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005489 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005490 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5491 invalidateTracks((audio_stream_type_t)i);
5492 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005493 if (isHardError) {
5494 mAfThreadCallback->onHardError(allTrackPortIds);
5495 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005496}
5497
Andy Hungee58e4a2023-07-07 13:47:37 -07005498void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005499{
Eric Laurent81784c32012-11-19 14:55:58 -08005500 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005501 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005502 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005503 // increase sleep time progressively when application underrun condition clears.
5504 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5505 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5506 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005507 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005508 sleepTimeShift--;
5509 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005510 mSleepTimeUs = 0;
5511 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005512 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005513
Eric Laurent81784c32012-11-19 14:55:58 -08005514}
5515
Andy Hungee58e4a2023-07-07 13:47:37 -07005516void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005517{
5518 // If no tracks are ready, sleep once for the duration of an output
5519 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005520 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005521 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005522 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5523 // Using the Monopipe availableToWrite, we estimate the
5524 // sleep time to retry for more data (before we underrun).
5525 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5526 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5527 const size_t pipeFrames = monoPipe->maxFrames();
5528 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5529 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5530 const size_t framesDelay = std::min(
5531 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5532 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5533 pipeFrames, framesLeft, framesDelay);
5534 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5535 } else {
5536 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5537 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5538 mSleepTimeUs = kMinThreadSleepTimeUs;
5539 }
5540 // reduce sleep time in case of consecutive application underruns to avoid
5541 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5542 // duration we would end up writing less data than needed by the audio HAL if
5543 // the condition persists.
5544 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5545 sleepTimeShift++;
5546 }
Eric Laurent81784c32012-11-19 14:55:58 -08005547 }
5548 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005549 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005550 }
5551 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005552 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5553 // before effects processing or output.
5554 if (mMixerBufferValid) {
5555 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005556 if (mType == SPATIALIZER) {
5557 memset(mSinkBuffer, 0, mSinkBufferSize);
5558 }
Andy Hung98ef9782014-03-04 14:46:50 -08005559 } else {
5560 memset(mSinkBuffer, 0, mSinkBufferSize);
5561 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005562 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005563 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5564 "anticipated start");
5565 }
5566 // TODO add standby time extension fct of effect tail
5567}
5568
Andy Hungc5007f82023-08-29 14:26:09 -07005569// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005570PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005571 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005572{
Andy Hungc0691382018-09-12 18:01:57 -07005573 // clean up deleted track ids in AudioMixer before allocating new tracks
5574 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5575 // for each trackId, destroy it in the AudioMixer
5576 if (mAudioMixer->exists(trackId)) {
5577 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005578 }
5579 });
Andy Hungc0691382018-09-12 18:01:57 -07005580 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005581
5582 mixer_state mixerStatus = MIXER_IDLE;
5583 // find out which tracks need to be processed
5584 size_t count = mActiveTracks.size();
5585 size_t mixedTracks = 0;
5586 size_t tracksWithEffect = 0;
5587 // counts only _active_ fast tracks
5588 size_t fastTracks = 0;
5589 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5590
5591 float masterVolume = mMasterVolume;
5592 bool masterMute = mMasterMute;
5593
5594 if (masterMute) {
5595 masterVolume = 0;
5596 }
5597 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005598 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005599 if (chain != 0) {
5600 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005601 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005602 masterVolume = (float)((v + (1 << 23)) >> 24);
5603 chain.clear();
5604 }
5605
5606 // prepare a new state to push
5607 FastMixerStateQueue *sq = NULL;
5608 FastMixerState *state = NULL;
5609 bool didModify = false;
5610 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005611 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005612 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005613 sq = mFastMixer->sq();
5614 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005615 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005616 }
5617
Andy Hung69aed5f2014-02-25 17:24:40 -08005618 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005619 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005620
Andy Hungbd3b2b02018-05-21 10:53:11 -07005621 // DeferredOperations handles statistics after setting mixerStatus.
5622 class DeferredOperations {
5623 public:
Andy Hungea840382020-05-05 21:50:17 -07005624 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5625 : mMixerStatus(mixerStatus)
5626 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005627
5628 // when leaving scope, tally frames properly.
5629 ~DeferredOperations() {
5630 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5631 // because that is when the underrun occurs.
5632 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005633 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005634 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005635 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005636 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005637 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005638 }
5639 }
Andy Hungea840382020-05-05 21:50:17 -07005640 // send the max underrun frames for this mixer period
5641 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005642 }
5643
5644 // tallyUnderrunFrames() is called to update the track counters
5645 // with the number of underrun frames for a particular mixer period.
5646 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005647 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005648 mUnderrunFrames.emplace_back(track, underrunFrames);
5649 }
5650
5651 private:
5652 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005653 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005654 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005655 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005656 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005657
jiabin245cdd92018-12-07 17:55:15 -08005658 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005659 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005660 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005661
5662 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005663 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005664
5665 // process fast tracks
5666 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005667 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5668 "%s(%d): FastTrack(%d) present without FastMixer",
5669 __func__, id(), track->id());
5670
jiabin245cdd92018-12-07 17:55:15 -08005671 if (track->getHapticPlaybackEnabled()) {
5672 noFastHapticTrack = false;
5673 }
Eric Laurent81784c32012-11-19 14:55:58 -08005674
5675 // It's theoretically possible (though unlikely) for a fast track to be created
5676 // and then removed within the same normal mix cycle. This is not a problem, as
5677 // the track never becomes active so it's fast mixer slot is never touched.
5678 // The converse, of removing an (active) track and then creating a new track
5679 // at the identical fast mixer slot within the same normal mix cycle,
5680 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005681 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005682 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005683 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5684 FastTrack *fastTrack = &state->mFastTracks[j];
5685
5686 // Determine whether the track is currently in underrun condition,
5687 // and whether it had a recent underrun.
5688 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5689 FastTrackUnderruns underruns = ftDump->mUnderruns;
5690 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005691 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005692 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005693 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005694 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005695 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005696 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005697 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005698 // don't count underruns that occur while stopping or pausing
5699 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005700 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005701 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5702 recentUnderruns > 0) {
5703 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005704 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005705 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005706 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005707 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005708
5709 // This is similar to the state machine for normal tracks,
5710 // with a few modifications for fast tracks.
5711 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005712 switch (track->state()) {
5713 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005714 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005715 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005716 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005717 }
5718 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005719 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005720 // ramp down is not yet implemented
5721 track->setPaused();
5722 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005723 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005724 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005725 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005726 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005727 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005728 if (recentFull > 0 || recentPartial > 0) {
5729 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005730 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005731 }
5732 if (recentUnderruns == 0) {
5733 // no recent underruns: stay active
5734 break;
5735 }
5736 // there has recently been an underrun of some kind
5737 if (track->sharedBuffer() == 0) {
5738 // were any of the recent underruns "empty" (no frames available)?
5739 if (recentEmpty == 0) {
5740 // no, then ignore the partial underruns as they are allowed indefinitely
5741 break;
5742 }
5743 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005744 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005745 break;
5746 }
5747 // indicate to client process that the track was disabled because of underrun;
5748 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005749 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005750 // remove from active list, but state remains ACTIVE [confusing but true]
5751 isActive = false;
5752 break;
5753 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005754 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005755 case IAfTrackBase::STOPPING_2:
5756 case IAfTrackBase::PAUSED:
5757 case IAfTrackBase::STOPPED:
5758 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005759 // Check for presentation complete if track is inactive
5760 // We have consumed all the buffers of this track.
5761 // This would be incomplete if we auto-paused on underrun
5762 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005763 uint32_t latency = 0;
5764 status_t result = mOutput->stream->getLatency(&latency);
5765 ALOGE_IF(result != OK,
5766 "Error when retrieving output stream latency: %d", result);
5767 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005768 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005769 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5770 // track stays in active list until presentation is complete
5771 break;
5772 }
5773 }
5774 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005775 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005776 }
5777 if (track->isStopped()) {
5778 // Can't reset directly, as fast mixer is still polling this track
5779 // track->reset();
5780 // So instead mark this track as needing to be reset after push with ack
5781 resetMask |= 1 << i;
5782 }
5783 isActive = false;
5784 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005785 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005786 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005787 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005788 }
5789
5790 if (isActive) {
5791 // was it previously inactive?
5792 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005793 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5794 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005795 fastTrack->mBufferProvider = eabp;
5796 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005797 fastTrack->mChannelMask = track->channelMask();
5798 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005799 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005800 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005801 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005802 fastTrack->mGeneration++;
5803 state->mTrackMask |= 1 << j;
5804 didModify = true;
5805 // no acknowledgement required for newly active tracks
5806 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005807 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005808 float volume;
Andy Hung6b137d12024-08-27 22:35:17 +00005809 if (!audioserver_flags::portid_volume_management()) {
5810 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5811 volume = 0.f;
5812 } else {
5813 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5814 }
Eric Laurenteab90452019-06-24 15:17:46 -07005815 } else {
Andy Hung6b137d12024-08-27 22:35:17 +00005816 if (track->isPlaybackRestricted()) {
5817 volume = 0.f;
5818 } else {
5819 volume = masterVolume * track->getPortVolume();
5820 }
Eric Laurenteab90452019-06-24 15:17:46 -07005821 }
Eric Laurenteab90452019-06-24 15:17:46 -07005822 handleVoipVolume_l(&volume);
5823
Eric Laurent81784c32012-11-19 14:55:58 -08005824 // cache the combined master volume and stream type volume for fast mixer; this
5825 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005826 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005827 proxy->framesReleased()).first;
5828 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005829 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005830 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005831 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5832 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Andy Hung6b137d12024-08-27 22:35:17 +00005833 if (!audioserver_flags::portid_volume_management()) {
5834 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5835 /*muteState=*/{masterVolume == 0.f,
5836 mStreamTypes[track->streamType()].volume == 0.f,
5837 mStreamTypes[track->streamType()].mute,
5838 track->isPlaybackRestricted(),
5839 vlf == 0.f && vrf == 0.f,
5840 vh == 0.f});
5841 } else {
5842 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5843 /*muteState=*/{masterVolume == 0.f,
5844 track->getPortVolume() == 0.f,
5845 /* muteFromStreamMuted= */ false,
5846 track->isPlaybackRestricted(),
5847 vlf == 0.f && vrf == 0.f,
5848 vh == 0.f});
5849 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005850 vlf *= volume;
5851 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005852
jiabin220eea12024-05-17 17:55:20 +00005853 if (track->getInternalMute()) {
5854 vlf = 0.f;
5855 vrf = 0.f;
5856 }
5857
jiabin76d94692022-12-15 21:51:21 +00005858 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005859 ++fastTracks;
5860 } else {
5861 // was it previously active?
5862 if (state->mTrackMask & (1 << j)) {
5863 fastTrack->mBufferProvider = NULL;
5864 fastTrack->mGeneration++;
5865 state->mTrackMask &= ~(1 << j);
5866 didModify = true;
5867 // If any fast tracks were removed, we must wait for acknowledgement
5868 // because we're about to decrement the last sp<> on those tracks.
5869 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5870 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005871 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5872 // AudioTrack may start (which may not be with a start() but with a write()
5873 // after underrun) and immediately paused or released. In that case the
5874 // FastTrack state hasn't had time to update.
5875 // TODO Remove the ALOGW when this theory is confirmed.
5876 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005877 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005878 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005879 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005880 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005881 }
5882 tracksToRemove->add(track);
5883 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005884 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005885 }
jiabin245cdd92018-12-07 17:55:15 -08005886 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5887 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5888 didModify = true;
5889 }
Eric Laurent81784c32012-11-19 14:55:58 -08005890 continue;
5891 }
5892
5893 { // local variable scope to avoid goto warning
5894
5895 audio_track_cblk_t* cblk = track->cblk();
5896
5897 // The first time a track is added we wait
5898 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005899 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005900
5901 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005902 // use the trackId as the AudioMixer name.
5903 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005904 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005905 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005906 track->channelMask(),
5907 track->format(),
5908 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005909 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005910 ALOGW("%s(): AudioMixer cannot create track(%d)"
5911 " mask %#x, format %#x, sessionId %d",
5912 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005913 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005914 tracksToRemove->add(track);
5915 track->invalidate(); // consider it dead.
5916 continue;
5917 }
5918 }
5919
Eric Laurent81784c32012-11-19 14:55:58 -08005920 // make sure that we have enough frames to mix one full buffer.
5921 // enforce this condition only once to enable draining the buffer in case the client
5922 // app does not call stop() and relies on underrun to stop:
5923 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5924 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005925 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005926 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5927 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005928
5929 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005930 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005931 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5932 // add frames already consumed but not yet released by the resampler
5933 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005934 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005935
Eric Laurent81784c32012-11-19 14:55:58 -08005936 uint32_t minFrames = 1;
5937 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5938 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005939 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005940 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005941
5942 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005943 if (ATRACE_ENABLED()) {
5944 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005945 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005946 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005947 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005948 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005949 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005950 !track->isPaused() && !track->isTerminated())
5951 {
Andy Hungc0691382018-09-12 18:01:57 -07005952 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005953
5954 mixedTracks++;
5955
Shunkai Yaof4847652024-01-12 00:25:20 +00005956 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005957 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005958 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005959 if (track->mainBuffer() != mSinkBuffer &&
5960 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005961 if (mEffectBufferEnabled) {
5962 mEffectBufferValid = true; // Later can set directly.
5963 }
Eric Laurent81784c32012-11-19 14:55:58 -08005964 chain = getEffectChain_l(track->sessionId());
5965 // Delegate volume control to effect in track effect chain if needed
5966 if (chain != 0) {
5967 tracksWithEffect++;
5968 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005969 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005970 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005971 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005972 }
5973 }
5974
5975
5976 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005977 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005978 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005979 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5980 if (track->state() == IAfTrackBase::RESUMING) {
5981 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005982 // If a new track is paused immediately after start, do not ramp on resume.
5983 if (cblk->mServer != 0) {
5984 param = AudioMixer::RAMP_VOLUME;
5985 }
Eric Laurent81784c32012-11-19 14:55:58 -08005986 }
Andy Hungc0691382018-09-12 18:01:57 -07005987 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005988 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005989 // FIXME should not make a decision based on mServer
5990 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005991 // If the track is stopped before the first frame was mixed,
5992 // do not apply ramp
5993 param = AudioMixer::RAMP_VOLUME;
5994 }
5995
5996 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005997 uint32_t vl, vr; // in U8.24 integer format
5998 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005999 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07006000 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07006001 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07006002 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07006003 track->audioTrackServerProxy()->framesReleased()).first;
Andy Hung6b137d12024-08-27 22:35:17 +00006004 float v;
6005 if (!audioserver_flags::portid_volume_management()) {
6006 v = masterVolume * mStreamTypes[track->streamType()].volume;
6007 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6008 v = 0;
6009 }
6010 } else {
6011 v = masterVolume * track->getPortVolume();
6012 if (track->isPlaybackRestricted()) {
6013 v = 0;
6014 }
Eric Laurenteab90452019-06-24 15:17:46 -07006015 }
Eric Laurenteab90452019-06-24 15:17:46 -07006016 handleVoipVolume_l(&v);
6017
6018 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006019 vl = vr = 0;
6020 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006021 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006022 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006023 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006024 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6025 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006026 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006027 if (vlf > GAIN_FLOAT_UNITY) {
6028 ALOGV("Track left volume out of range: %.3g", vlf);
6029 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006030 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006031 if (vrf > GAIN_FLOAT_UNITY) {
6032 ALOGV("Track right volume out of range: %.3g", vrf);
6033 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006034 }
Andy Hung6b137d12024-08-27 22:35:17 +00006035 if (!audioserver_flags::portid_volume_management()) {
6036 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6037 /*muteState=*/{masterVolume == 0.f,
6038 mStreamTypes[track->streamType()].volume == 0.f,
6039 mStreamTypes[track->streamType()].mute,
6040 track->isPlaybackRestricted(),
6041 vlf == 0.f && vrf == 0.f,
6042 vh == 0.f});
6043 } else {
6044 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6045 /*muteState=*/{masterVolume == 0.f,
6046 track->getPortVolume() == 0.f,
6047 /* muteFromStreamMuted= */ false,
6048 track->isPlaybackRestricted(),
6049 vlf == 0.f && vrf == 0.f,
6050 vh == 0.f});
6051 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006052 // now apply the master volume and stream type volume and shaper volume
6053 vlf *= v * vh;
6054 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006055 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006056 // then derive vl and vr as U8.24 versions for the effect chain
6057 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6058 vl = (uint32_t) (scaleto8_24 * vlf);
6059 vr = (uint32_t) (scaleto8_24 * vrf);
6060 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006061 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006062 // send level comes from shared memory and so may be corrupt
6063 if (sendLevel > MAX_GAIN_INT) {
6064 ALOGV("Track send level out of range: %04X", sendLevel);
6065 sendLevel = MAX_GAIN_INT;
6066 }
Andy Hung6be49402014-05-30 10:42:03 -07006067 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6068 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006069 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006070
jiabin220eea12024-05-17 17:55:20 +00006071 if (track->getInternalMute()) {
6072 vrf = 0.f;
6073 vlf = 0.f;
6074 }
6075
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006076 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006077
Eric Laurent81784c32012-11-19 14:55:58 -08006078 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006079 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006080 // Do not ramp volume if volume is controlled by effect
6081 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006082 // Update remaining floating point volume levels
6083 vlf = (float)vl / (1 << 24);
6084 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006085 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006086 } else {
6087 // force no volume ramp when volume controller was just disabled or removed
6088 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006089 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006090 param = AudioMixer::VOLUME;
6091 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006092 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006093 }
6094
Eric Laurent81784c32012-11-19 14:55:58 -08006095 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006096 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006097 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006098
Andy Hungc0691382018-09-12 18:01:57 -07006099 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6100 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6101 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006102 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006103 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006104 AudioMixer::TRACK,
6105 AudioMixer::FORMAT, (void *)track->format());
6106 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006107 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006108 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006109 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006110
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006111 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006112 mAudioMixer->setParameter(
6113 trackId,
6114 AudioMixer::TRACK,
6115 AudioMixer::MIXER_CHANNEL_MASK,
6116 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6117 } else {
6118 mAudioMixer->setParameter(
6119 trackId,
6120 AudioMixer::TRACK,
6121 AudioMixer::MIXER_CHANNEL_MASK,
6122 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6123 }
6124
Glenn Kastene3aa6592012-12-04 12:22:46 -08006125 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006126 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006127 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006128 if (reqSampleRate == 0) {
6129 reqSampleRate = mSampleRate;
6130 } else if (reqSampleRate > maxSampleRate) {
6131 reqSampleRate = maxSampleRate;
6132 }
Eric Laurent81784c32012-11-19 14:55:58 -08006133 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006134 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006135 AudioMixer::RESAMPLE,
6136 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006137 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006138
Andy Hung8edb8dc2015-03-26 19:13:55 -07006139 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006140 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006141 AudioMixer::TIMESTRETCH,
6142 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006143 // cast away constness for this generic API.
6144 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006145
Andy Hung69aed5f2014-02-25 17:24:40 -08006146 /*
6147 * Select the appropriate output buffer for the track.
6148 *
Andy Hung98ef9782014-03-04 14:46:50 -08006149 * Tracks with effects go into their own effects chain buffer
6150 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006151 *
6152 * Other tracks can use mMixerBuffer for higher precision
6153 * channel accumulation. If this buffer is enabled
6154 * (mMixerBufferEnabled true), then selected tracks will accumulate
6155 * into it.
6156 *
6157 */
6158 if (mMixerBufferEnabled
6159 && (track->mainBuffer() == mSinkBuffer
6160 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006161 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006162 mAudioMixer->setParameter(
6163 trackId,
6164 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006165 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006166 mAudioMixer->setParameter(
6167 trackId,
6168 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006169 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006170 } else {
6171 mAudioMixer->setParameter(
6172 trackId,
6173 AudioMixer::TRACK,
6174 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6175 mAudioMixer->setParameter(
6176 trackId,
6177 AudioMixer::TRACK,
6178 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6179 // TODO: override track->mainBuffer()?
6180 mMixerBufferValid = true;
6181 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006182 } else {
6183 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006184 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006185 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006186 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006187 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006188 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006189 AudioMixer::TRACK,
6190 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6191 }
Eric Laurent81784c32012-11-19 14:55:58 -08006192 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006193 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006194 AudioMixer::TRACK,
6195 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006196 mAudioMixer->setParameter(
6197 trackId,
6198 AudioMixer::TRACK,
6199 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006200 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006201 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006202 trackId,
6203 AudioMixer::TRACK,
6204 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006205 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006206 mAudioMixer->setParameter(
6207 trackId,
6208 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006209 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006210
6211 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006212 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006213
6214 // If one track is ready, set the mixer ready if:
6215 // - the mixer was not ready during previous round OR
6216 // - no other track is not ready
6217 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6218 mixerStatus != MIXER_TRACKS_ENABLED) {
6219 mixerStatus = MIXER_TRACKS_READY;
6220 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006221
6222 // Enable the next few lines to instrument a test for underrun log handling.
6223 // TODO: Remove when we have a better way of testing the underrun log.
6224#if 0
6225 static int i;
6226 if ((++i & 0xf) == 0) {
6227 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6228 }
6229#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006230 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006231 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006232 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006233 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6234 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006235 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006236 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006237 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006238
Eric Laurent81784c32012-11-19 14:55:58 -08006239 // clear effect chain input buffer if an active track underruns to avoid sending
6240 // previous audio buffer again to effects
6241 chain = getEffectChain_l(track->sessionId());
6242 if (chain != 0) {
6243 chain->clearInputBuffer();
6244 }
6245
Andy Hungc0691382018-09-12 18:01:57 -07006246 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006247 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6248 track->isStopped() || track->isPaused()) {
6249 // We have consumed all the buffers of this track.
6250 // Remove it from the list of active tracks.
6251 // TODO: use actual buffer filling status instead of latency when available from
6252 // audio HAL
6253 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006254 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006255 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6256 if (track->isStopped()) {
6257 track->reset();
6258 }
6259 tracksToRemove->add(track);
6260 }
6261 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006262 // No buffers for this track. Give it a few chances to
6263 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006264 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006265 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6266 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006267 tracksToRemove->add(track);
6268 // indicate to client process that the track was disabled because of underrun;
6269 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006270 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006271 // If one track is not ready, mark the mixer also not ready if:
6272 // - the mixer was ready during previous round OR
6273 // - no other track is ready
6274 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6275 mixerStatus != MIXER_TRACKS_READY) {
6276 mixerStatus = MIXER_TRACKS_ENABLED;
6277 }
6278 }
Andy Hungc0691382018-09-12 18:01:57 -07006279 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006280 }
6281
6282 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006283
6284 }
6285
jiabin245cdd92018-12-07 17:55:15 -08006286 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6287 // When there is no fast track playing haptic and FastMixer exists,
6288 // enabling the first FastTrack, which provides mixed data from normal
6289 // tracks, to play haptic data.
6290 FastTrack *fastTrack = &state->mFastTracks[0];
6291 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6292 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6293 didModify = true;
6294 }
6295 }
6296
Eric Laurent81784c32012-11-19 14:55:58 -08006297 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006298 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006299 if (didModify) {
6300 state->mFastTracksGen++;
6301 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6302 if (kUseFastMixer == FastMixer_Dynamic &&
6303 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6304 state->mCommand = FastMixerState::COLD_IDLE;
6305 state->mColdFutexAddr = &mFastMixerFutex;
6306 state->mColdGen++;
6307 mFastMixerFutex = 0;
6308 if (kUseFastMixer == FastMixer_Dynamic) {
6309 mNormalSink = mOutputSink;
6310 }
6311 // If we go into cold idle, need to wait for acknowledgement
6312 // so that fast mixer stops doing I/O.
6313 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6314 pauseAudioWatchdog = true;
6315 }
Eric Laurent81784c32012-11-19 14:55:58 -08006316 }
6317 if (sq != NULL) {
6318 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006319 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6320 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6321 // when bringing the output sink into standby.)
6322 //
6323 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6324 //
6325 // This occurs with BT suspend when we idle the FastMixer with
6326 // active tracks, which may be added or removed.
6327 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006328 }
6329#ifdef AUDIO_WATCHDOG
6330 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6331 mAudioWatchdog->pause();
6332 }
6333#endif
6334
6335 // Now perform the deferred reset on fast tracks that have stopped
6336 while (resetMask != 0) {
6337 size_t i = __builtin_ctz(resetMask);
6338 ALOG_ASSERT(i < count);
6339 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006340 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006341 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6342 track->reset();
6343 }
6344
Andy Hung80d03d22018-04-10 10:32:11 -07006345 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6346 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6347 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6348 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6349 // See also the implementation of destroyTrack_l().
6350 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006351 const int trackId = track->id();
6352 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6353 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006354 }
6355 }
6356
Eric Laurent81784c32012-11-19 14:55:58 -08006357 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006358 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006359
Eric Laurentb3f315a2021-07-13 15:09:05 +02006360 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6361 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006362 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006363 }
6364
6365 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006366 // as long as there are effects we should clear the effects buffer, to avoid
6367 // passing a non-clean buffer to the effect chain
6368 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006369 if (mType == SPATIALIZER) {
6370 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6371 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006372 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006373 // sink or mix buffer must be cleared if all tracks are connected to an
6374 // effect chain as in this case the mixer will not write to the sink or mix buffer
6375 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006376 // always clear sink buffer for spatializer output as the output of the spatializer
6377 // effect will be accumulated into it
6378 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6379 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006380 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006381 if (mMixerBufferValid) {
6382 memset(mMixerBuffer, 0, mMixerBufferSize);
6383 // TODO: In testing, mSinkBuffer below need not be cleared because
6384 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6385 // after mixing.
6386 //
6387 // To enforce this guarantee:
6388 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6389 // (mixedTracks == 0 && fastTracks > 0))
6390 // must imply MIXER_TRACKS_READY.
6391 // Later, we may clear buffers regardless, and skip much of this logic.
6392 }
Andy Hung98ef9782014-03-04 14:46:50 -08006393 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006394 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006395 }
6396
6397 // if any fast tracks, then status is ready
6398 mMixerStatusIgnoringFastTracks = mixerStatus;
6399 if (fastTracks > 0) {
6400 mixerStatus = MIXER_TRACKS_READY;
6401 }
6402 return mixerStatus;
6403}
6404
Andy Hungc5007f82023-08-29 14:26:09 -07006405// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006406uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006407{
6408 uint32_t trackCount = 0;
6409 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006410 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006411 trackCount++;
6412 }
6413 }
6414 return trackCount;
6415}
6416
Andy Hungee58e4a2023-07-07 13:47:37 -07006417bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006418{
Brian Lindahl65e90012022-07-27 18:01:07 +02006419 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6420 // could falsely detect that the frame position has stalled due to underrun because we haven't
6421 // given the Audio HAL enough time to update.
6422 const nsecs_t nowNs = systemTime();
6423 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6424 return mLatchedValue;
6425 }
6426 mPreviousNs = nowNs;
6427 mLatchedValue = false;
6428 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006429 uint64_t position = 0;
6430 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006431 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006432 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006433 if (position != mPreviousPosition) {
6434 mPreviousPosition = position;
6435 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006436 }
6437 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006438 return mLatchedValue;
6439}
6440
Andy Hungee58e4a2023-07-07 13:47:37 -07006441void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006442{
6443 mLatchedValue = true;
6444 mPreviousPosition = 0;
6445 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006446}
6447
Andy Hungc5007f82023-08-29 14:26:09 -07006448// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006449bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006450 audio_channel_mask_t channelMask, audio_format_t format,
6451 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006452{
Andy Hung1bc088a2018-02-09 15:57:31 -08006453 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6454 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006455 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006456 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006457 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006458 ALOGW("%s: invalid format: %#x", __func__, format);
6459 return false;
6460 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006461 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006462 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6463 return false;
6464 }
6465 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006466}
6467
Andy Hungc5007f82023-08-29 14:26:09 -07006468// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006469bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006470 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006471{
Eric Laurent81784c32012-11-19 14:55:58 -08006472 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006473 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006474
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006475 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006476
Eric Laurent10351942014-05-08 18:49:52 -07006477 AudioParameter param = AudioParameter(keyValuePair);
6478 int value;
6479 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6480 reconfig = true;
6481 }
6482 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006483 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006484 status = BAD_VALUE;
6485 } else {
6486 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006487 reconfig = true;
6488 }
Eric Laurent10351942014-05-08 18:49:52 -07006489 }
6490 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006491 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006492 status = BAD_VALUE;
6493 } else {
6494 // no need to save value, since it's constant
6495 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006496 }
Eric Laurent10351942014-05-08 18:49:52 -07006497 }
6498 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6499 // do not accept frame count changes if tracks are open as the track buffer
6500 // size depends on frame count and correct behavior would not be guaranteed
6501 // if frame count is changed after track creation
6502 if (!mTracks.isEmpty()) {
6503 status = INVALID_OPERATION;
6504 } else {
6505 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006506 }
Eric Laurent10351942014-05-08 18:49:52 -07006507 }
6508 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006509 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006510 }
Eric Laurent81784c32012-11-19 14:55:58 -08006511
Eric Laurent10351942014-05-08 18:49:52 -07006512 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006513 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006514 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006515 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6516 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006517 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006518 mThreadMetrics.logEndInterval();
6519 mThreadSnapshot.onEnd();
6520 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006521 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006522 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006523 }
Eric Laurent10351942014-05-08 18:49:52 -07006524 if (status == NO_ERROR && reconfig) {
6525 readOutputParameters_l();
6526 delete mAudioMixer;
6527 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006528 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006529 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006530 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006531 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006532 track->channelMask(),
6533 track->format(),
6534 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006535 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006536 "%s(): AudioMixer cannot create track(%d)"
6537 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006538 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006539 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006540 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006541 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006542 }
Eric Laurent81784c32012-11-19 14:55:58 -08006543 }
6544
Dean Wheatley68918102021-03-19 22:09:19 +11006545 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006546}
6547
6548
Andy Hungee58e4a2023-07-07 13:47:37 -07006549void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006550{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006551 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006552 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006553 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006554 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006555 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6556 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6557 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006558 if (hasFastMixer()) {
6559 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6560
6561 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6562 // while we are dumping it. It may be inconsistent, but it won't mutate!
6563 // This is a large object so we place it on the heap.
6564 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006565 const std::unique_ptr<FastMixerDumpState> copy =
6566 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006567 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006568
6569#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006570 // Similar for state queue
6571 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6572 observerCopy.dump(fd);
6573 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6574 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006575#endif
6576
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006577#ifdef AUDIO_WATCHDOG
6578 if (mAudioWatchdog != 0) {
6579 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6580 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6581 wdCopy.dump(fd);
6582 }
6583#endif
6584
6585 } else {
6586 dprintf(fd, " No FastMixer\n");
6587 }
Eric Laurent90cea102023-05-15 15:08:27 +02006588
6589 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6590 mBluetoothLatencyModesEnabled ? "" : "not ");
6591 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6592 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6593 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006594}
6595
Andy Hungee58e4a2023-07-07 13:47:37 -07006596uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006597{
6598 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6599}
6600
Andy Hungee58e4a2023-07-07 13:47:37 -07006601uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006602{
6603 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6604}
6605
Andy Hungee58e4a2023-07-07 13:47:37 -07006606void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006607{
6608 PlaybackThread::cacheParameters_l();
6609
6610 // FIXME: Relaxed timing because of a certain device that can't meet latency
6611 // Should be reduced to 2x after the vendor fixes the driver issue
6612 // increase threshold again due to low power audio mode. The way this warning
6613 // threshold is calculated and its usefulness should be reconsidered anyway.
6614 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6615}
6616
Andy Hungee58e4a2023-07-07 13:47:37 -07006617void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006618 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006619}
6620
Andy Hungee58e4a2023-07-07 13:47:37 -07006621void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006622 // Only handle latency mode if:
6623 // - mBluetoothLatencyModesEnabled is true
6624 // - the HAL supports latency modes
6625 // - the selected device is Bluetooth LE or A2DP
6626 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6627 return;
6628 }
6629 if (mOutDeviceTypeAddrs.size() != 1
6630 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6631 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6632 return;
6633 }
6634
6635 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6636 if (mSupportedLatencyModes.size() == 1) {
6637 // If the HAL only support one latency mode currently, confirm the choice
6638 latencyMode = mSupportedLatencyModes[0];
6639 } else if (mSupportedLatencyModes.size() > 1) {
6640 // Request low latency if:
6641 // - At least one active track is either:
6642 // - a fast track with gaming usage or
6643 // - a track with acessibility usage
6644 for (const auto& track : mActiveTracks) {
6645 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6646 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6647 latencyMode = AUDIO_LATENCY_MODE_LOW;
6648 break;
6649 }
6650 }
6651 }
6652
6653 if (latencyMode != mSetLatencyMode) {
6654 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6655 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6656 __func__, mId, toString(latencyMode).c_str(), status);
6657 if (status == NO_ERROR) {
6658 mSetLatencyMode = latencyMode;
6659 }
6660 }
6661}
6662
Andy Hungee58e4a2023-07-07 13:47:37 -07006663void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006664
6665 if (mOutput == nullptr || mOutput->stream == nullptr) {
6666 return;
6667 }
6668 std::vector<audio_latency_mode_t> latencyModes;
6669 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6670 if (status != NO_ERROR) {
6671 latencyModes.clear();
6672 }
6673 if (latencyModes != mSupportedLatencyModes) {
6674 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6675 __func__, mId, status, toString(latencyModes).c_str());
6676 mSupportedLatencyModes.swap(latencyModes);
6677 sendHalLatencyModesChangedEvent_l();
6678 }
6679}
6680
Andy Hungee58e4a2023-07-07 13:47:37 -07006681status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006682 std::vector<audio_latency_mode_t>* modes) {
6683 if (modes == nullptr) {
6684 return BAD_VALUE;
6685 }
Andy Hung972bec12023-08-31 16:13:39 -07006686 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006687 *modes = mSupportedLatencyModes;
6688 return NO_ERROR;
6689}
6690
Andy Hungee58e4a2023-07-07 13:47:37 -07006691void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006692 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006693 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006694 if (modes != mSupportedLatencyModes) {
6695 ALOGD("%s: thread(%d) supported latency modes: %s",
6696 __func__, mId, toString(modes).c_str());
6697 mSupportedLatencyModes.swap(modes);
6698 sendHalLatencyModesChangedEvent_l();
6699 }
6700}
6701
Andy Hungee58e4a2023-07-07 13:47:37 -07006702status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006703 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6704 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6705 return INVALID_OPERATION;
6706 }
6707 mBluetoothLatencyModesEnabled.store(enabled);
6708 return NO_ERROR;
6709}
6710
Eric Laurent81784c32012-11-19 14:55:58 -08006711// ----------------------------------------------------------------------------
6712
Andy Hungee58e4a2023-07-07 13:47:37 -07006713/* static */
6714sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006715 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006716 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6717 const audio_offload_info_t& offloadInfo) {
6718 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006719 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006720}
6721
Andy Hung583043b2023-07-17 17:05:00 -07006722DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006723 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6724 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006725 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006726 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006727{
Andy Hung583043b2023-07-17 17:05:00 -07006728 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006729}
6730
Andy Hungee58e4a2023-07-07 13:47:37 -07006731DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006732{
6733}
6734
Andy Hungee58e4a2023-07-07 13:47:37 -07006735void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006736{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006737 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006738 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6739 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6740}
6741
Andy Hungee58e4a2023-07-07 13:47:37 -07006742void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006743{
Andy Hung972bec12023-08-31 16:13:39 -07006744 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006745 if (mMasterBalance != balance) {
6746 mMasterBalance.store(balance);
6747 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6748 broadcast_l();
6749 }
6750}
6751
Andy Hungee58e4a2023-07-07 13:47:37 -07006752void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006753{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006754 float left, right;
6755
Andy Hung333ab962019-05-28 20:23:35 -07006756 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006757 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006758
Andy Hung398ffa22022-12-13 19:19:53 -08006759 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6760 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6761
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006762 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6763 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006764
6765 const int64_t volumeShaperFrames =
6766 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6767 const auto [shaperVolume, shaperActive] =
6768 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006769 mVolumeShaperActive = shaperActive;
6770
Vlad Popae2f5aef2022-07-25 16:00:20 +02006771 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6772 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6773 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6774
6775 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6776
Andy Hung6b137d12024-08-27 22:35:17 +00006777 if (!audioserver_flags::portid_volume_management()) {
6778 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6779 track->isPlaybackRestricted()) {
6780 left = right = 0;
6781 } else {
6782 float typeVolume = mStreamTypes[track->streamType()].volume;
6783 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurent277a37e2024-07-29 18:37:52 +00006784
Andy Hung6b137d12024-08-27 22:35:17 +00006785 if (left > GAIN_FLOAT_UNITY) {
6786 left = GAIN_FLOAT_UNITY;
6787 }
6788 if (right > GAIN_FLOAT_UNITY) {
6789 right = GAIN_FLOAT_UNITY;
6790 }
6791 left *= v;
6792 right *= v;
6793 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006794 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Andy Hung6b137d12024-08-27 22:35:17 +00006795 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6796 right *= mMasterBalanceRight;
6797 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006798 }
Andy Hung6b137d12024-08-27 22:35:17 +00006799 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6800 /*muteState=*/{mMasterMute,
6801 mStreamTypes[track->streamType()].volume == 0.f,
6802 mStreamTypes[track->streamType()].mute,
6803 track->isPlaybackRestricted(),
6804 clientVolumeMute,
6805 shaperVolume == 0.f});
6806 } else {
6807 if (mMasterMute || track->isPlaybackRestricted()) {
6808 left = right = 0;
6809 } else {
6810 float typeVolume = track->getPortVolume();
6811 const float v = mMasterVolume * typeVolume * shaperVolume;
Liana Kazanova (xWF)d3e99d22024-08-23 22:15:51 +00006812
Andy Hung6b137d12024-08-27 22:35:17 +00006813 if (left > GAIN_FLOAT_UNITY) {
6814 left = GAIN_FLOAT_UNITY;
6815 }
6816 if (right > GAIN_FLOAT_UNITY) {
6817 right = GAIN_FLOAT_UNITY;
6818 }
6819 left *= v;
6820 right *= v;
6821 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6822 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6823 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6824 right *= mMasterBalanceRight;
6825 }
6826 }
6827 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6828 /*muteState=*/{mMasterMute,
6829 track->getPortVolume() == 0.f,
6830 /* muteFromStreamMuted= */ false,
6831 track->isPlaybackRestricted(),
6832 clientVolumeMute,
6833 shaperVolume == 0.f});
6834 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006835
Eric Laurentbfb1b832013-01-07 09:53:42 -08006836 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006837 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006838 if (left != mLeftVolFloat || right != mRightVolFloat) {
6839 mLeftVolFloat = left;
6840 mRightVolFloat = right;
6841
Eric Laurentbfb1b832013-01-07 09:53:42 -08006842 // Delegate volume control to effect in track effect chain if needed
6843 // only one effect chain can be present on DirectOutputThread, so if
6844 // there is one, the track is connected to it
6845 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006846 // if effect chain exists, volume is handled by it.
6847 // Convert volumes from float to 8.24
6848 uint32_t vl = (uint32_t)(left * (1 << 24));
6849 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006850 // Direct/Offload effect chains set output volume in setVolume().
6851 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006852 } else {
6853 // otherwise we directly set the volume.
6854 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006855 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006856 }
6857 }
6858}
6859
Andy Hungee58e4a2023-07-07 13:47:37 -07006860void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006861{
Andy Hung8d31fd22023-06-26 19:20:57 -07006862 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6863 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006864
Eric Laurent0f0631e2015-07-06 18:01:25 -07006865 if (previousTrack != 0 && latestTrack != 0) {
6866 if (mType == DIRECT) {
6867 if (previousTrack.get() != latestTrack.get()) {
6868 mFlushPending = true;
6869 }
6870 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006871 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6872 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006873 mFlushPending = true;
6874 }
6875 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006876 } else if (previousTrack == 0) {
6877 // there could be an old track added back during track transition for direct
6878 // output, so always issues flush to flush data of the previous track if it
6879 // was already destroyed with HAL paused, then flush can resume the playback
6880 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006881 }
6882 PlaybackThread::onAddNewTrack_l();
6883}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006884
Andy Hungee58e4a2023-07-07 13:47:37 -07006885PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006886 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006887)
6888{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006889 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006890 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006891 bool doHwPause = false;
6892 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006893
6894 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006895 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006896 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006897 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006898 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006899 continue;
6900 }
6901
Andy Hung8d31fd22023-06-26 19:20:57 -07006902 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006903#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006904 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006905#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006906 // Only consider last track started for volume and mixer state control.
6907 // In theory an older track could underrun and restart after the new one starts
6908 // but as we only care about the transition phase between two tracks on a
6909 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006910 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006911 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006912
Kuowei Li23666472021-01-20 10:23:25 +08006913 if (track->isPausePending()) {
6914 track->pauseAck();
6915 // It is possible a track might have been flushed or stopped.
6916 // Other operations such as flush pending might occur on the next prepare.
6917 if (track->isPausing()) {
6918 track->setPaused();
6919 }
6920 // Always perform pause, as an immediate flush will change
6921 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006922 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006923 doHwPause = true;
6924 mHwPaused = true;
6925 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006926 } else if (track->isFlushPending()) {
6927 track->flushAck();
6928 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006929 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006930 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006931 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006932 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006933 if (last) {
6934 mLeftVolFloat = mRightVolFloat = -1.0;
6935 if (mHwPaused) {
6936 doHwResume = true;
6937 mHwPaused = false;
6938 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006939 }
6940 }
6941
Eric Laurent81784c32012-11-19 14:55:58 -08006942 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006943 // for all its buffers to be filled before processing it.
6944 // Allow draining the buffer in case the client
6945 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006946 // hence the test on (track->retryCount() > 1).
6947 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006948 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6949 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006950 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006951
6952 // target retry count that we will use is based on the time we wait for retries.
6953 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6954 // the retry threshold is when we accept any size for PCM data. This is slightly
6955 // smaller than the retry count so we can push small bits of data without a glitch.
6956 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006957 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006958 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006959 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006960 minFrames = mNormalFrameCount;
6961 } else {
6962 minFrames = 1;
6963 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006964
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006965 const size_t framesReady = track->framesReady();
6966 const int trackId = track->id();
6967 if (ATRACE_ENABLED()) {
6968 std::string traceName("nRdy");
6969 traceName += std::to_string(trackId);
6970 ATRACE_INT(traceName.c_str(), framesReady);
6971 }
6972 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006973 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006974 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006975 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006976
Andy Hung8d31fd22023-06-26 19:20:57 -07006977 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6978 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006979 if (last) {
6980 // make sure processVolume_l() will apply new volume even if 0
6981 mLeftVolFloat = mRightVolFloat = -1.0;
6982 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006983 if (!mHwSupportsPause) {
6984 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006985 }
6986 }
6987
6988 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006989 processVolume_l(track, last);
6990 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006991 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006992 if (previousTrack != 0) {
6993 if (track != previousTrack.get()) {
6994 // Flush any data still being written from last track
6995 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006996 // Invalidate previous track to force a seek when resuming.
6997 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006998 }
6999 }
7000 mPreviousTrack = track;
7001
Eric Laurentd595b7c2013-04-03 17:27:56 -07007002 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07007003 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08007004 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07007005 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07007006 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007007 doHwResume = true;
7008 mHwPaused = false;
7009 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007010 }
Eric Laurent81784c32012-11-19 14:55:58 -08007011 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007012 // clear effect chain input buffer if the last active track started underruns
7013 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007014 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007015 mEffectChains[0]->clearInputBuffer();
7016 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007017 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007018 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007019 if (last && mHwPaused) {
7020 doHwResume = true;
7021 mHwPaused = false;
7022 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007023 }
7024 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7025 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007026 // We have consumed all the buffers of this track.
7027 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007028 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007029 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007030 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007031 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007032 if (presComplete) {
7033 mOutput->presentationComplete();
7034 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007035 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007036 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007037 }
Eric Laurent81784c32012-11-19 14:55:58 -08007038 if (track->isStopped()) {
7039 track->reset();
7040 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007041 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007042 }
7043 } else {
7044 // No buffers for this track. Give it a few chances to
7045 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007046 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007047 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007048 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007049 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007050 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007051 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007052 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007053 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7054 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007055 tracksToRemove->add(track);
7056 // indicate to client process that the track was disabled because of
7057 // underrun; it will then automatically call start() when data is available
7058 track->disable();
7059 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7060 // unlike mixerthread, HAL can be paused for direct output
7061 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7062 "minFrames = %u, mFormat = %#x",
7063 framesReady, minFrames, mFormat);
7064 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7065 doHwPause = true;
7066 mHwPaused = true;
7067 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007068 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007069 } else if (last) {
7070 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007071 }
7072 }
7073 }
7074 }
7075
Eric Laurentd1f69b02014-12-15 14:33:13 -08007076 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007077 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007078 for (size_t i = 0; i < mTracks.size(); i++) {
7079 if (mTracks[i]->isFlushPending()) {
7080 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007081 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007082 }
7083 }
7084 }
7085
7086 // make sure the pause/flush/resume sequence is executed in the right order.
7087 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7088 // before flush and then resume HW. This can happen in case of pause/flush/resume
7089 // if resume is received before pause is executed.
7090 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007091 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007092 status_t result = mOutput->stream->pause();
7093 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007094 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007095 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007096 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007097 flushHw_l();
7098 }
7099 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007100 status_t result = mOutput->stream->resume();
7101 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007102 }
Eric Laurent81784c32012-11-19 14:55:58 -08007103 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007104 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007105
7106 return mixerStatus;
7107}
7108
Andy Hungee58e4a2023-07-07 13:47:37 -07007109void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007110{
Eric Laurent81784c32012-11-19 14:55:58 -08007111 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007112 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007113 // output audio to hardware
7114 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007115 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007116 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007117 status_t status = mActiveTrack->getNextBuffer(&buffer);
7118 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007119 // no need to pad with 0 for compressed audio
7120 if (audio_has_proportional_frames(mFormat)) {
7121 memset(curBuf, 0, frameCount * mFrameSize);
7122 }
Eric Laurent81784c32012-11-19 14:55:58 -08007123 break;
7124 }
7125 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7126 frameCount -= buffer.frameCount;
7127 curBuf += buffer.frameCount * mFrameSize;
7128 mActiveTrack->releaseBuffer(&buffer);
7129 }
Andy Hung2098f272014-02-27 14:00:06 -08007130 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007131 mSleepTimeUs = 0;
7132 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007133 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007134}
7135
Andy Hungee58e4a2023-07-07 13:47:37 -07007136void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007137{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007138 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007139 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007140 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007141 return;
7142 }
Andy Hung85ba3332021-04-27 17:40:26 -07007143 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7144 mSleepTimeUs = mActiveSleepTimeUs;
7145 } else {
7146 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007147 }
Andy Hung85ba3332021-04-27 17:40:26 -07007148 // Note: In S or later, we do not write zeroes for
7149 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007150}
7151
Andy Hungee58e4a2023-07-07 13:47:37 -07007152void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007153{
7154 {
Andy Hung972bec12023-08-31 16:13:39 -07007155 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007156 for (size_t i = 0; i < mTracks.size(); i++) {
7157 if (mTracks[i]->isFlushPending()) {
7158 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007159 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007160 }
7161 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007162 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007163 flushHw_l();
7164 }
7165 }
7166 PlaybackThread::threadLoop_exit();
7167}
7168
7169// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007170bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007171{
7172 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007173 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007174 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007175
Eric Laurent022a5132024-04-12 17:02:51 +00007176 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007177 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007178 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007179 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007180 const auto& mainTrack = mTracks[mTracks.size() - 1];
7181
7182 trackPaused = mainTrack->isPaused();
7183 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7184 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007185 }
7186
Eric Laurent022a5132024-04-12 17:02:51 +00007187 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007188}
7189
Andy Hungc5007f82023-08-29 14:26:09 -07007190// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007191bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007192 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007193{
7194 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007195 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007196
Eric Laurent10351942014-05-08 18:49:52 -07007197 AudioParameter param = AudioParameter(keyValuePair);
7198 int value;
7199 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007200 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007201 }
Eric Laurent10351942014-05-08 18:49:52 -07007202 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7203 // do not accept frame count changes if tracks are open as the track buffer
7204 // size depends on frame count and correct behavior would not be garantied
7205 // if frame count is changed after track creation
7206 if (!mTracks.isEmpty()) {
7207 status = INVALID_OPERATION;
7208 } else {
7209 reconfig = true;
7210 }
7211 }
7212 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007213 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007214 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007215 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007216 if (!mStandby) {
7217 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007218 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007219 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007220 }
Eric Laurent10351942014-05-08 18:49:52 -07007221 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007222 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007223 }
7224 if (status == NO_ERROR && reconfig) {
7225 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007226 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007227 }
7228 }
7229
Dean Wheatley68918102021-03-19 22:09:19 +11007230 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007231}
7232
Andy Hungee58e4a2023-07-07 13:47:37 -07007233uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007234{
7235 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007236 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007237 time = PlaybackThread::activeSleepTimeUs();
7238 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007239 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007240 }
7241 return time;
7242}
7243
Andy Hungee58e4a2023-07-07 13:47:37 -07007244uint32_t DirectOutputThread::idleSleepTimeUs() 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 = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
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::suspendSleepTimeUs() 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);
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 -07007266void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007267{
7268 PlaybackThread::cacheParameters_l();
7269
7270 // use shorter standby delay as on normal output to release
7271 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007272 // no delay on outputs with HW A/V sync
7273 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007274 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007275 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007276 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007277 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007278 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007279 }
Eric Laurent81784c32012-11-19 14:55:58 -08007280}
7281
Andy Hungee58e4a2023-07-07 13:47:37 -07007282void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007283{
ziyangch8f194f12021-12-01 13:48:04 -08007284 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007285 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007286 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007287 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007288 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007289 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007290 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007291}
7292
Andy Hungee58e4a2023-07-07 13:47:37 -07007293int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007294 // If a VolumeShaper is active, we must wake up periodically to update volume.
7295 const int64_t NS_PER_MS = 1000000;
7296 return mVolumeShaperActive ?
7297 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7298}
7299
Eric Laurent81784c32012-11-19 14:55:58 -08007300// ----------------------------------------------------------------------------
7301
Andy Hungee58e4a2023-07-07 13:47:37 -07007302AsyncCallbackThread::AsyncCallbackThread(
7303 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007304 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007305 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007306 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007307 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007308 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007309{
7310}
7311
Andy Hungee58e4a2023-07-07 13:47:37 -07007312void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007313{
7314 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7315}
7316
Andy Hungee58e4a2023-07-07 13:47:37 -07007317bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007318{
7319 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007320 uint32_t writeAckSequence;
7321 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007322 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007323
7324 {
Andy Hungc5007f82023-08-29 14:26:09 -07007325 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007326 while (!((mWriteAckSequence & 1) ||
7327 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007328 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007329 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007330 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007331 }
7332
Eric Laurentbfb1b832013-01-07 09:53:42 -08007333 if (exitPending()) {
7334 break;
7335 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007336 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7337 mWriteAckSequence, mDrainSequence);
7338 writeAckSequence = mWriteAckSequence;
7339 mWriteAckSequence &= ~1;
7340 drainSequence = mDrainSequence;
7341 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007342 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007343 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007344 }
7345 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007346 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007347 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007348 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007349 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007350 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007351 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007352 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007353 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007354 if (asyncError != ASYNC_ERROR_NONE) {
7355 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007356 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007357 }
7358 }
7359 }
7360 return false;
7361}
7362
Andy Hungee58e4a2023-07-07 13:47:37 -07007363void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007364{
7365 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007366 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007367 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007368 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007369}
7370
Andy Hungee58e4a2023-07-07 13:47:37 -07007371void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007372{
Andy Hung972bec12023-08-31 16:13:39 -07007373 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007374 // bit 0 is cleared
7375 mWriteAckSequence = sequence << 1;
7376}
7377
Andy Hungee58e4a2023-07-07 13:47:37 -07007378void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007379{
Andy Hung972bec12023-08-31 16:13:39 -07007380 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007381 // ignore unexpected callbacks
7382 if (mWriteAckSequence & 2) {
7383 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007384 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007385 }
7386}
7387
Andy Hungee58e4a2023-07-07 13:47:37 -07007388void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007389{
Andy Hung972bec12023-08-31 16:13:39 -07007390 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007391 // bit 0 is cleared
7392 mDrainSequence = sequence << 1;
7393}
7394
Andy Hungee58e4a2023-07-07 13:47:37 -07007395void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007396{
Andy Hung972bec12023-08-31 16:13:39 -07007397 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007398 // ignore unexpected callbacks
7399 if (mDrainSequence & 2) {
7400 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007401 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007402 }
7403}
7404
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007405void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007406{
Andy Hung972bec12023-08-31 16:13:39 -07007407 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007408 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007409 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007410}
7411
Eric Laurentbfb1b832013-01-07 09:53:42 -08007412
7413// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007414
7415/* static */
7416sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007417 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007418 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7419 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007420 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007421}
7422
Andy Hung583043b2023-07-17 17:05:00 -07007423OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007424 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7425 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007426 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007427 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007428{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007429 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007430 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007431 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007432}
7433
Andy Hungee58e4a2023-07-07 13:47:37 -07007434void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007435{
7436 if (mFlushPending || mHwPaused) {
7437 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007438 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007439 flushHw_l();
7440 } else {
7441 mMixerStatus = MIXER_DRAIN_ALL;
7442 threadLoop_drain();
7443 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007444 if (mUseAsyncWrite) {
7445 ALOG_ASSERT(mCallbackThread != 0);
7446 mCallbackThread->exit();
7447 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007448 PlaybackThread::threadLoop_exit();
7449}
7450
Andy Hungee58e4a2023-07-07 13:47:37 -07007451PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007452 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007453)
7454{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007455 size_t count = mActiveTracks.size();
7456
7457 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007458 bool doHwPause = false;
7459 bool doHwResume = false;
7460
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007461 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007462
Eric Laurentbfb1b832013-01-07 09:53:42 -08007463 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007464 for (const sp<IAfTrack>& t : mActiveTracks) {
7465 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007466#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007467 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007468#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007469 // Only consider last track started for volume and mixer state control.
7470 // In theory an older track could underrun and restart after the new one starts
7471 // but as we only care about the transition phase between two tracks on a
7472 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007473 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007474 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007475
Haynes Mathew George7844f672014-01-15 12:32:55 -08007476 if (track->isInvalid()) {
7477 ALOGW("An invalidated track shouldn't be in active list");
7478 tracksToRemove->add(track);
7479 continue;
7480 }
7481
Andy Hung8d31fd22023-06-26 19:20:57 -07007482 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007483 ALOGW("An idle track shouldn't be in active list");
7484 continue;
7485 }
7486
Kuowei Li23666472021-01-20 10:23:25 +08007487 if (track->isPausePending()) {
7488 track->pauseAck();
7489 // It is possible a track might have been flushed or stopped.
7490 // Other operations such as flush pending might occur on the next prepare.
7491 if (track->isPausing()) {
7492 track->setPaused();
7493 }
7494 // Always perform pause if last, as an immediate flush will change
7495 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007496 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007497 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007498 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007499 mHwPaused = true;
7500 }
7501 // If we were part way through writing the mixbuffer to
7502 // the HAL we must save this until we resume
7503 // BUG - this will be wrong if a different track is made active,
7504 // in that case we want to discard the pending data in the
7505 // mixbuffer and tell the client to present it again when the
7506 // track is resumed
7507 mPausedWriteLength = mCurrentWriteLength;
7508 mPausedBytesRemaining = mBytesRemaining;
7509 mBytesRemaining = 0; // stop writing
7510 }
7511 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007512 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007513 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007514 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007515 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007516 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007517 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007518 track->flushAck();
7519 if (last) {
7520 mFlushPending = true;
7521 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007522 } else if (track->isResumePending()){
7523 track->resumeAck();
7524 if (last) {
7525 if (mPausedBytesRemaining) {
7526 // Need to continue write that was interrupted
7527 mCurrentWriteLength = mPausedWriteLength;
7528 mBytesRemaining = mPausedBytesRemaining;
7529 mPausedBytesRemaining = 0;
7530 }
7531 if (mHwPaused) {
7532 doHwResume = true;
7533 mHwPaused = false;
7534 // threadLoop_mix() will handle the case that we need to
7535 // resume an interrupted write
7536 }
7537 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007538 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007539
Eric Laurent3df841a2016-07-15 15:15:40 -07007540 mLeftVolFloat = mRightVolFloat = -1.0;
7541
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007542 // Do not handle new data in this iteration even if track->framesReady()
7543 mixerStatus = MIXER_TRACKS_ENABLED;
7544 }
7545 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007546 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007547 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007548 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7549 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007550 if (last) {
7551 // make sure processVolume_l() will apply new volume even if 0
7552 mLeftVolFloat = mRightVolFloat = -1.0;
7553 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007554 }
7555
7556 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007557 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007558 if (previousTrack != 0) {
7559 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007560 // Flush any data still being written from last track
7561 mBytesRemaining = 0;
7562 if (mPausedBytesRemaining) {
7563 // Last track was paused so we also need to flush saved
7564 // mixbuffer state and invalidate track so that it will
7565 // re-submit that unwritten data when it is next resumed
7566 mPausedBytesRemaining = 0;
7567 // Invalidate is a bit drastic - would be more efficient
7568 // to have a flag to tell client that some of the
7569 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007570 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007571 }
7572 // flush data already sent to the DSP if changing audio session as audio
7573 // comes from a different source. Also invalidate previous track to force a
7574 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007575 if (previousTrack->sessionId() != track->sessionId()) {
7576 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007577 }
7578 }
7579 }
7580 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007581 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007582 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007583 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007584 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007585 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007586 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007587 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007588 mixerStatus = MIXER_TRACKS_READY;
7589 }
7590 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007591 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007592 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007593 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007594 // Hardware buffer can hold a large amount of audio so we must
7595 // wait for all current track's data to drain before we say
7596 // that the track is stopped.
7597 if (mBytesRemaining == 0) {
7598 // Only start draining when all data in mixbuffer
7599 // has been written
7600 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007601 track->setState(IAfTrackBase::STOPPING_2);
7602 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007603 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7604 if (last && !mStandby) {
7605 // do not modify drain sequence if we are already draining. This happens
7606 // when resuming from pause after drain.
7607 if ((mDrainSequence & 1) == 0) {
7608 mSleepTimeUs = 0;
7609 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7610 mixerStatus = MIXER_DRAIN_TRACK;
7611 mDrainSequence += 2;
7612 }
7613 if (mHwPaused) {
7614 // It is possible to move from PAUSED to STOPPING_1 without
7615 // a resume so we must ensure hardware is running
7616 doHwResume = true;
7617 mHwPaused = false;
7618 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007619 }
7620 }
Eric Laurente93cc032016-05-05 10:15:10 -07007621 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007622 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007623 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007624 }
7625 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007626 // Drain has completed or we are in standby, signal presentation complete
7627 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007628 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007629 mOutput->presentationComplete();
7630 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007631 track->reset();
7632 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007633 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007634 if (!mUseAsyncWrite) {
7635 // If we don't get explicit drain notification we must
7636 // register discontinuity regardless of whether this is
7637 // the previous (!last) or the upcoming (last) track
7638 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007639 mTimestampVerifier.discontinuity(
7640 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007641 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007642 }
7643 } else {
7644 // No buffers for this track. Give it a few chances to
7645 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007646 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007647 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007648 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007649 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007650 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007651 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007652 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7653 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007654 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007655 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007656 // it will then automatically call start() when data is available
7657 track->disable();
7658 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007659 } else if (last){
7660 mixerStatus = MIXER_TRACKS_ENABLED;
7661 }
7662 }
7663 }
7664 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007665 if (track->isReady()) { // check ready to prevent premature start.
7666 processVolume_l(track, last);
7667 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007668 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007669
Eric Laurentea0fade2013-10-04 16:23:48 -07007670 // make sure the pause/flush/resume sequence is executed in the right order.
7671 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7672 // before flush and then resume HW. This can happen in case of pause/flush/resume
7673 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007674 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007675 status_t result = mOutput->stream->pause();
7676 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007677 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007678 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007679 if (mFlushPending) {
7680 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007681 }
Eric Laurentfd477972013-10-25 18:10:40 -07007682 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007683 status_t result = mOutput->stream->resume();
7684 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007685 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007686
Eric Laurentbfb1b832013-01-07 09:53:42 -08007687 // remove all the tracks that need to be...
7688 removeTracks_l(*tracksToRemove);
7689
7690 return mixerStatus;
7691}
7692
Eric Laurentbfb1b832013-01-07 09:53:42 -08007693// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007694bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007695{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007696 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7697 mWriteAckSequence, mDrainSequence);
7698 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007699 return true;
7700 }
7701 return false;
7702}
7703
Andy Hungee58e4a2023-07-07 13:47:37 -07007704bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007705{
Andy Hung972bec12023-08-31 16:13:39 -07007706 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007707 return waitingAsyncCallback_l();
7708}
7709
Andy Hungee58e4a2023-07-07 13:47:37 -07007710void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007711{
Eric Laurente659ef42014-09-29 13:06:46 -07007712 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007713 // Flush anything still waiting in the mixbuffer
7714 mCurrentWriteLength = 0;
7715 mBytesRemaining = 0;
7716 mPausedWriteLength = 0;
7717 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007718 // reset bytes written count to reflect that DSP buffers are empty after flush.
7719 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007720
Eric Laurentbfb1b832013-01-07 09:53:42 -08007721 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007722 // discard any pending drain or write ack by incrementing sequence
7723 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7724 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007725 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007726 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7727 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007728 }
7729}
7730
Andy Hungee58e4a2023-07-07 13:47:37 -07007731void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007732{
Andy Hung972bec12023-08-31 16:13:39 -07007733 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007734 if (PlaybackThread::invalidateTracks_l(streamType)) {
7735 mFlushPending = true;
7736 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007737}
7738
Andy Hungee58e4a2023-07-07 13:47:37 -07007739void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007740 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007741 if (PlaybackThread::invalidateTracks_l(portIds)) {
7742 mFlushPending = true;
7743 }
7744}
7745
Eric Laurentbfb1b832013-01-07 09:53:42 -08007746// ----------------------------------------------------------------------------
7747
Andy Hungee58e4a2023-07-07 13:47:37 -07007748/* static */
7749sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007750 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007751 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007752 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007753}
7754
Andy Hung583043b2023-07-17 17:05:00 -07007755DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007756 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007757 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007758 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007759 mWaitTimeMs(UINT_MAX)
7760{
7761 addOutputTrack(mainThread);
7762}
7763
Andy Hungee58e4a2023-07-07 13:47:37 -07007764DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007765{
7766 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7767 mOutputTracks[i]->destroy();
7768 }
7769}
7770
Andy Hungee58e4a2023-07-07 13:47:37 -07007771void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007772{
7773 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007774 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007775 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007776 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007777 if (mMixerBufferValid) {
7778 memset(mMixerBuffer, 0, mMixerBufferSize);
7779 } else {
7780 memset(mSinkBuffer, 0, mSinkBufferSize);
7781 }
Eric Laurent81784c32012-11-19 14:55:58 -08007782 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007783 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007784 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007785 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007786 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007787}
7788
Andy Hungee58e4a2023-07-07 13:47:37 -07007789void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007790{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007791 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007792 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007793 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007794 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007795 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007796 }
7797 } else if (mBytesWritten != 0) {
7798 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7799 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007800 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007801 } else {
7802 // flush remaining overflow buffers in output tracks
7803 writeFrames = 0;
7804 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007805 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007806 }
7807}
7808
Andy Hungee58e4a2023-07-07 13:47:37 -07007809ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007810{
7811 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007812 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7813
7814 // Consider the first OutputTrack for timestamp and frame counting.
7815
7816 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7817 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7818 // we always claim success.
7819 if (i == 0) {
7820 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7821 ALOGD_IF(correction != 0 && writeFrames != 0,
7822 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7823 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7824 mFramesWritten -= correction;
7825 }
7826
7827 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007828 }
Andy Hungcf10d742020-04-28 15:38:24 -07007829 if (mStandby) {
7830 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007831 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007832 mStandby = false;
7833 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007834 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007835}
7836
Andy Hungee58e4a2023-07-07 13:47:37 -07007837void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007838{
7839 // DuplicatingThread implements standby by stopping all tracks
7840 for (size_t i = 0; i < outputTracks.size(); i++) {
7841 outputTracks[i]->stop();
7842 }
7843}
7844
Andy Hung8a5abfd2023-12-07 19:35:12 -08007845void DuplicatingThread::threadLoop_exit()
7846{
7847 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7848 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7849 // Do so here in the threadLoop_exit().
7850
7851 SortedVector <sp<IAfOutputTrack>> localTracks;
7852 {
7853 audio_utils::lock_guard l(mutex());
7854 localTracks = std::move(mOutputTracks);
7855 mOutputTracks.clear();
7856 }
7857 localTracks.clear();
7858 outputTracks.clear();
7859 PlaybackThread::threadLoop_exit();
7860}
7861
Andy Hungee58e4a2023-07-07 13:47:37 -07007862void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007863{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007864 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007865
7866 std::stringstream ss;
7867 const size_t numTracks = mOutputTracks.size();
7868 ss << " " << numTracks << " OutputTracks";
7869 if (numTracks > 0) {
7870 ss << ":";
7871 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007872 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007873 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007874 if (thread.get() != nullptr) {
7875 ss << thread.get() << ", " << thread->id();
7876 } else {
7877 ss << "null";
7878 }
7879 ss << ")";
7880 }
7881 }
7882 ss << "\n";
7883 std::string result = ss.str();
7884 write(fd, result.c_str(), result.size());
7885}
7886
Andy Hungee58e4a2023-07-07 13:47:37 -07007887void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007888{
7889 outputTracks = mOutputTracks;
7890}
7891
Andy Hungee58e4a2023-07-07 13:47:37 -07007892void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007893{
7894 outputTracks.clear();
7895}
7896
Andy Hungee58e4a2023-07-07 13:47:37 -07007897void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007898{
Andy Hung972bec12023-08-31 16:13:39 -07007899 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007900 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7901 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7902 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7903 const size_t frameCount =
7904 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7905 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7906 // from different OutputTracks and their associated MixerThreads (e.g. one may
7907 // nearly empty and the other may be dropping data).
7908
Svet Ganov33761132021-05-13 22:51:08 +00007909 // TODO b/182392769: use attribution source util, move to server edge
7910 AttributionSourceState attributionSource = AttributionSourceState();
7911 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007912 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007913 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007914 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007915 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007916 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007917 this,
7918 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007919 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007920 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007921 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007922 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007923 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7924 if (status != NO_ERROR) {
7925 ALOGE("addOutputTrack() initCheck failed %d", status);
7926 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007927 }
Andy Hung6b137d12024-08-27 22:35:17 +00007928 if (!audioserver_flags::portid_volume_management()) {
7929 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7930 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007931 mOutputTracks.add(outputTrack);
7932 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7933 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007934}
7935
Andy Hungee58e4a2023-07-07 13:47:37 -07007936void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007937{
Andy Hung972bec12023-08-31 16:13:39 -07007938 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007939 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7940 if (mOutputTracks[i]->thread() == thread) {
7941 mOutputTracks[i]->destroy();
7942 mOutputTracks.removeAt(i);
7943 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007944 // NO_THREAD_SAFETY_ANALYSIS
7945 // Lambda workaround: as thread != this
7946 // we can safely call the remote thread getOutput.
7947 const bool equalOutput =
7948 [&](){ return thread->getOutput() == mOutput; }();
7949 if (equalOutput) {
7950 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007951 }
Eric Laurent81784c32012-11-19 14:55:58 -08007952 return;
7953 }
7954 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007955 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007956}
7957
Andy Hungc5007f82023-08-29 14:26:09 -07007958// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007959void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007960{
7961 mWaitTimeMs = UINT_MAX;
7962 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007963 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007964 if (strong != 0) {
7965 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7966 if (waitTimeMs < mWaitTimeMs) {
7967 mWaitTimeMs = waitTimeMs;
7968 }
7969 }
7970 }
7971}
7972
Andy Hungee58e4a2023-07-07 13:47:37 -07007973bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007974{
7975 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007976 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007977 if (thread == 0) {
7978 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7979 outputTracks[i].get());
7980 return false;
7981 }
Andy Hung87c693c2023-07-06 20:56:16 -07007982 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007983 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007984 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007985 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7986 thread.get());
7987 return false;
7988 }
7989 }
7990 return true;
7991}
7992
Andy Hungee58e4a2023-07-07 13:47:37 -07007993void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007994 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007995{
Kevin Rocard12381092018-04-11 09:19:59 -07007996 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7997 outputTrack->setMetadatas(metadata.tracks);
7998 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007999}
8000
Andy Hungee58e4a2023-07-07 13:47:37 -07008001uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08008002{
Andy Hung7a6a0f02023-11-29 13:42:08 -08008003 // return half the wait time in microseconds.
8004 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08008005}
8006
Andy Hungee58e4a2023-07-07 13:47:37 -07008007void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008008{
8009 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8010 updateWaitTime_l();
8011
8012 MixerThread::cacheParameters_l();
8013}
8014
Eric Laurentb3f315a2021-07-13 15:09:05 +02008015// ----------------------------------------------------------------------------
8016
Andy Hungee58e4a2023-07-07 13:47:37 -07008017/* static */
8018sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008019 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008020 AudioStreamOut* output,
8021 audio_io_handle_t id,
8022 bool systemReady,
8023 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008024 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008025}
8026
Andy Hung583043b2023-07-17 17:05:00 -07008027SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008028 AudioStreamOut* output,
8029 audio_io_handle_t id,
8030 bool systemReady,
8031 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008032 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008033{
8034}
8035
Andy Hungee58e4a2023-07-07 13:47:37 -07008036void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008037 // if mSupportedLatencyModes is empty, the HAL stream does not support
8038 // latency mode control and we can exit.
8039 if (mSupportedLatencyModes.empty()) {
8040 return;
8041 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008042 // Do not update the HAL latency mode if no track is active
8043 if (mActiveTracks.isEmpty()) {
8044 return;
8045 }
8046
Eric Laurent68a40a82022-05-03 18:15:04 +02008047 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8048 if (mSupportedLatencyModes.size() == 1) {
8049 // If the HAL only support one latency mode currently, confirm the choice
8050 latencyMode = mSupportedLatencyModes[0];
8051 } else if (mSupportedLatencyModes.size() > 1) {
8052 // Request low latency if:
8053 // - The low latency mode is requested by the spatializer controller
8054 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8055 // AND
8056 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008057 for (const auto& track : mActiveTracks) {
8058 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008059 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008060 break;
8061 }
8062 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008063 }
8064
8065 if (latencyMode != mSetLatencyMode) {
8066 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008067 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8068 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008069 if (status == NO_ERROR) {
8070 mSetLatencyMode = latencyMode;
8071 }
8072 }
8073}
8074
Andy Hungee58e4a2023-07-07 13:47:37 -07008075status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008076 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008077 return BAD_VALUE;
8078 }
Andy Hung972bec12023-08-31 16:13:39 -07008079 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008080 mRequestedLatencyMode = mode;
8081 return NO_ERROR;
8082}
8083
Andy Hungee58e4a2023-07-07 13:47:37 -07008084void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008085NO_THREAD_SAFETY_ANALYSIS
8086// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008087{
8088 bool hasVirtualizer = false;
8089 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008090 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008091 {
Andy Hung972bec12023-08-31 16:13:39 -07008092 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008093 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008094 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008095 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008096 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8097 }
8098
8099 finalDownMixer = mFinalDownMixer;
8100 mFinalDownMixer.clear();
8101 }
8102
8103 if (hasVirtualizer) {
8104 if (finalDownMixer != nullptr) {
8105 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008106 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008107 }
8108 finalDownMixer.clear();
8109 } else if (!hasDownMixer) {
8110 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008111 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008112 EFFECT_UIID_DOWNMIX, &descriptors);
8113 if (status != NO_ERROR) {
8114 return;
8115 }
8116 ALOG_ASSERT(!descriptors.empty(),
8117 "%s getDescriptors() returned no error but empty list", __func__);
8118
8119 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8120 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008121 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008122
8123 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8124 ALOGW("%s error creating downmixer %d", __func__, status);
8125 finalDownMixer.clear();
8126 } else {
8127 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008128 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008129 }
8130 }
8131
8132 {
Andy Hung972bec12023-08-31 16:13:39 -07008133 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008134 mFinalDownMixer = finalDownMixer;
8135 }
8136}
8137
Andy Hunge2514462023-12-06 14:59:24 -08008138void SpatializerThread::threadLoop_exit()
8139{
8140 // The Spatializer EffectHandle must be released on the PlaybackThread
8141 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8142 mFinalDownMixer.clear();
8143
8144 PlaybackThread::threadLoop_exit();
8145}
8146
Eric Laurent81784c32012-11-19 14:55:58 -08008147// ----------------------------------------------------------------------------
8148// Record
8149// ----------------------------------------------------------------------------
8150
Andy Hung583043b2023-07-17 17:05:00 -07008151sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008152 AudioStreamIn* input,
8153 audio_io_handle_t id,
8154 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008155 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008156}
8157
Andy Hung583043b2023-07-17 17:05:00 -07008158RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008159 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008160 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008161 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008162 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008163 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008164 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008165 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008166 mActiveTracks(&this->mLocalLog),
8167 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008168 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008169 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008170 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8171 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008172 // mFastCapture below
8173 , mFastCaptureFutex(0)
8174 // mInputSource
8175 // mPipeSink
8176 // mPipeSource
8177 , mPipeFramesP2(0)
8178 // mPipeMemory
8179 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008180 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008181 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008182{
Glenn Kastend7dca052015-03-05 16:05:54 -08008183 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008184 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008185
George Burgess IVa8f90c12020-05-14 11:27:19 -07008186 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008187 mIsMsdDevice = strcmp(
8188 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8189 }
8190
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008191 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008192
Andy Hungc8fddf32018-08-08 18:32:37 -07008193 // TODO: We may also match on address as well as device type for
8194 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008195 // TODO: This property should be ensure that only contains one single device type.
8196 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8197 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008198 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8199 : AUDIO_DEVICE_NONE));
8200
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008201 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008202 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008203 size_t numCounterOffers = 0;
8204 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008205#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008206 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008207#else
8208 (void)
8209#endif
8210 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008211 ALOG_ASSERT(index == 0);
8212
8213 // initialize fast capture depending on configuration
8214 bool initFastCapture;
8215 switch (kUseFastCapture) {
8216 case FastCapture_Never:
8217 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008218 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008219 break;
8220 case FastCapture_Always:
8221 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008222 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008223 break;
8224 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008225 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008226 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008227 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008228 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8229 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8230 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008231 break;
8232 // case FastCapture_Dynamic:
8233 }
8234
8235 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008236 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008237 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008238 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8239 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008240 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008241 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008242 const sp<MemoryDealer> roHeap(readOnlyHeap());
8243 sp<IMemory> pipeMemory;
8244 if ((roHeap == 0) ||
8245 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008246 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008247 ALOGE("not enough memory for pipe buffer size=%zu; "
8248 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8249 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8250 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008251 goto failed;
8252 }
8253 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8254 memset(pipeBuffer, 0, pipeSize);
8255 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008256 const NBAIO_Format offersFast[1] = {format};
8257 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008258 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008259 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008260 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008261 mPipeSink = pipe;
8262 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008263 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008264 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008265 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008266 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008267 mPipeSource = pipeReader;
8268 mPipeFramesP2 = pipeFramesP2;
8269 mPipeMemory = pipeMemory;
8270
8271 // create fast capture
8272 mFastCapture = new FastCapture();
8273 FastCaptureStateQueue *sq = mFastCapture->sq();
8274#ifdef STATE_QUEUE_DUMP
8275 // FIXME
8276#endif
8277 FastCaptureState *state = sq->begin();
8278 state->mCblk = NULL;
8279 state->mInputSource = mInputSource.get();
8280 state->mInputSourceGen++;
8281 state->mPipeSink = pipe;
8282 state->mPipeSinkGen++;
8283 state->mFrameCount = mFrameCount;
8284 state->mCommand = FastCaptureState::COLD_IDLE;
8285 // already done in constructor initialization list
8286 //mFastCaptureFutex = 0;
8287 state->mColdFutexAddr = &mFastCaptureFutex;
8288 state->mColdGen++;
8289 state->mDumpState = &mFastCaptureDumpState;
8290#ifdef TEE_SINK
8291 // FIXME
8292#endif
Andy Hung583043b2023-07-17 17:05:00 -07008293 mFastCaptureNBLogWriter =
8294 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008295 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8296 sq->end();
8297 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8298
8299 // start the fast capture
8300 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8301 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008302 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008303 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008304#ifdef AUDIO_WATCHDOG
8305 // FIXME
8306#endif
8307
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008308 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008309 }
Andy Hung8946a282018-04-19 20:04:56 -07008310#ifdef TEE_SINK
8311 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8312 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8313#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008314failed: ;
8315
8316 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008317}
8318
Andy Hungee58e4a2023-07-07 13:47:37 -07008319RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008320{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008321 if (mFastCapture != 0) {
8322 FastCaptureStateQueue *sq = mFastCapture->sq();
8323 FastCaptureState *state = sq->begin();
8324 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8325 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8326 if (old == -1) {
8327 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8328 }
8329 }
8330 state->mCommand = FastCaptureState::EXIT;
8331 sq->end();
8332 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8333 mFastCapture->join();
8334 mFastCapture.clear();
8335 }
Andy Hung583043b2023-07-17 17:05:00 -07008336 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8337 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008338 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008339}
8340
Andy Hungee58e4a2023-07-07 13:47:37 -07008341void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008342{
Glenn Kastend7dca052015-03-05 16:05:54 -08008343 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008344}
8345
Andy Hungee58e4a2023-07-07 13:47:37 -07008346void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008347{
8348 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008349 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008350 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008351 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008352 track->invalidate();
8353 }
8354 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008355 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008356}
8357
Andy Hungee58e4a2023-07-07 13:47:37 -07008358bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008359{
Eric Laurent81784c32012-11-19 14:55:58 -08008360 nsecs_t lastWarning = 0;
8361
8362 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008363
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008364reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008365 {
Andy Hung972bec12023-08-31 16:13:39 -07008366 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008367 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008368 }
8369
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008370 // used to request a deferred sleep, to be executed later while mutex is unlocked
8371 uint32_t sleepUs = 0;
8372
Andy Hung95c94a22023-10-20 16:41:18 -07008373 // timestamp correction enable is determined under lock, used in processing step.
8374 bool timestampCorrectionEnabled = false;
8375
Andy Hung446f4df2019-02-21 12:26:41 -08008376 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8377
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008378 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008379 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008380 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8381 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008382 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008383 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008384
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008385 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008386 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008387
Glenn Kasten735f45f2014-08-18 15:51:59 -07008388 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008389 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008390
Glenn Kasten735f45f2014-08-18 15:51:59 -07008391 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008392 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008393
Eric Laurent33403f02020-05-29 18:35:06 -07008394 bool silenceFastCapture = false;
8395
Andy Hungc5007f82023-08-29 14:26:09 -07008396 { // scope for mutex()
8397 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008398
Eric Laurent021cf962014-05-13 10:18:14 -07008399 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008400
Eric Laurent000a4192014-01-29 15:17:32 -08008401 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008402 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008403 if (exitPending()) {
8404 break;
8405 }
8406
Eric Laurent5c25d562016-07-13 17:17:45 -07008407 // sleep with mutex unlocked
8408 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008409 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008410 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008411 ATRACE_END();
8412 sleepUs = 0;
8413 continue;
8414 }
8415
Glenn Kasten2b806402013-11-20 16:37:38 -08008416 // if no active track(s), then standby and release wakelock
8417 size_t size = mActiveTracks.size();
8418 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008419 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008420 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008421 releaseWakeLock_l();
8422 ALOGV("RecordThread: loop stopping");
8423 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008424 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008425 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008426 goto reacquire_wakelock;
8427 }
8428
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008429 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008430 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008432 if (activeTrack) { // ensure track release is outside lock.
8433 oldActiveTracks.emplace_back(std::move(activeTrack));
8434 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008435 activeTrack = mActiveTracks[i];
8436 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008437 if (activeTrack->isFastTrack()) {
8438 ALOG_ASSERT(fastTrackToRemove == 0);
8439 fastTrackToRemove = activeTrack;
8440 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008441 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008442 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008443 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008444 continue;
8445 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008446
Andy Hung8d31fd22023-06-26 19:20:57 -07008447 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008448 switch (activeTrackState) {
8449
Andy Hung8d31fd22023-06-26 19:20:57 -07008450 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008451 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008452 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008453 if (activeTrack->isFastTrack()) {
8454 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8455 // Keep a ref on fast track to wait for FastCapture thread to get updated
8456 // state before potential track removal
8457 fastTrackToRemove = activeTrack;
8458 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008459 doBroadcast = true;
8460 size--;
8461 continue;
8462
Andy Hung8d31fd22023-06-26 19:20:57 -07008463 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008464 sleepUs = 10000;
8465 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008466 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008467 continue;
8468
Andy Hung8d31fd22023-06-26 19:20:57 -07008469 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008470 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008471 if (mStandby) {
8472 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008473 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008474 mStandby = false;
8475 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008476 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008477 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008478 break;
8479
Andy Hung8d31fd22023-06-26 19:20:57 -07008480 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008481 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008482 break;
8483
Andy Hung8d31fd22023-06-26 19:20:57 -07008484 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8485 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8486 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008487 default:
Andy Hungce685402018-10-05 17:23:27 -07008488 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8489 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008490 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008491
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008492 if (activeTrack->isFastTrack()) {
8493 ALOG_ASSERT(!mFastTrackAvail);
8494 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008495 // if the active fast track is silenced either:
8496 // 1) silence the whole capture from fast capture buffer if this is
8497 // the only active track
8498 // 2) invalidate this track: this will cause the client to reconnect and possibly
8499 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008500 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008501 if (activeTrack->isSilenced()) {
8502 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008503 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008504 } else {
8505 silenceFastCapture = true;
8506 }
8507 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008508 // Invalidate fast tracks if access to audio history is required as this is not
8509 // possible with fast tracks. Once the fast track has been invalidated, no new
8510 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8511 if (mMaxSharedAudioHistoryMs != 0) {
8512 invalidate = true;
8513 }
8514 if (invalidate) {
8515 activeTrack->invalidate();
8516 ALOG_ASSERT(fastTrackToRemove == 0);
8517 fastTrackToRemove = activeTrack;
8518 removeTrack_l(activeTrack);
8519 mActiveTracks.remove(activeTrack);
8520 size--;
8521 continue;
8522 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008523 fastTrack = activeTrack;
8524 }
Eric Laurent33403f02020-05-29 18:35:06 -07008525
8526 activeTracks.add(activeTrack);
8527 i++;
8528
Glenn Kasten9e982352013-08-14 14:39:50 -07008529 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008530
Andy Hungab65b182023-09-06 19:41:47 -07008531 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008532
Kevin Rocard069c2712018-03-29 19:09:14 -07008533 updateMetadata_l();
8534
Eric Laurent5c25d562016-07-13 17:17:45 -07008535 if (allStopped) {
8536 standbyIfNotAlreadyInStandby();
8537 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008538 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008539 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008540 }
8541
8542 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008543 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008544 if (sleepUs == 0) {
8545 sleepUs = kRecordThreadSleepUs;
8546 }
8547 continue;
8548 }
8549 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008550
Andy Hung95c94a22023-10-20 16:41:18 -07008551 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008552 lockEffectChains_l(effectChains);
8553 }
8554
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008555 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008556
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008557 size_t size = effectChains.size();
8558 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008559 // thread mutex is not locked, but effect chain is locked
8560 effectChains[i]->process_l();
8561 }
8562
Glenn Kasten735f45f2014-08-18 15:51:59 -07008563 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008564 if (mFastCapture != 0) {
8565 FastCaptureStateQueue *sq = mFastCapture->sq();
8566 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008567 bool didModify = false;
8568 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008569 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8570 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8571 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8572 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8573 if (old == -1) {
8574 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8575 }
8576 }
8577 state->mCommand = FastCaptureState::READ_WRITE;
8578#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008579 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008580 FastThreadDumpState::kSamplingNforLowRamDevice :
8581 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008582#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008583 didModify = true;
8584 }
8585 audio_track_cblk_t *cblkOld = state->mCblk;
8586 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8587 if (cblkNew != cblkOld) {
8588 state->mCblk = cblkNew;
8589 // block until acked if removing a fast track
8590 if (cblkOld != NULL) {
8591 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8592 }
8593 didModify = true;
8594 }
jiabin01c8f562018-07-19 17:47:28 -07008595 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8596 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8597 if (state->mFastPatchRecordBufferProvider != abp) {
8598 state->mFastPatchRecordBufferProvider = abp;
8599 state->mFastPatchRecordFormat = fastTrack == 0 ?
8600 AUDIO_FORMAT_INVALID : fastTrack->format();
8601 didModify = true;
8602 }
Eric Laurent33403f02020-05-29 18:35:06 -07008603 if (state->mSilenceCapture != silenceFastCapture) {
8604 state->mSilenceCapture = silenceFastCapture;
8605 didModify = true;
8606 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008607 sq->end(didModify);
8608 if (didModify) {
8609 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008610#if 0
8611 if (kUseFastCapture == FastCapture_Dynamic) {
8612 mNormalSource = mPipeSource;
8613 }
8614#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008615 }
8616 }
8617
Glenn Kasten735f45f2014-08-18 15:51:59 -07008618 // now run the fast track destructor with thread mutex unlocked
8619 fastTrackToRemove.clear();
8620
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008621 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8622 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8623 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8624 // If destination is non-contiguous, first read past the nominal end of buffer, then
8625 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008626
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008627 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008628 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008629 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008630
8631 // If an NBAIO source is present, use it to read the normal capture's data
8632 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008633 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008634
8635 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8636 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8637 // we immediately retry the read() to get data and prevent another overflow.
8638 for (int retries = 0; retries <= 2; ++retries) {
8639 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8640 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8641 framesToRead);
8642 if (framesRead != OVERRUN) break;
8643 }
8644
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008645 const ssize_t availableToRead = mPipeSource->availableToRead();
8646 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008647 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008648 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008649 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8650 "more frames to read than fifo size, %zd > %zu",
8651 availableToRead, mPipeFramesP2);
8652 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8653 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8654 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8655 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008656 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8657 }
8658 if (framesRead < 0) {
8659 status_t status = (status_t) framesRead;
8660 switch (status) {
8661 case OVERRUN:
8662 ALOGW("overrun on read from pipe");
8663 framesRead = 0;
8664 break;
8665 case NEGOTIATE:
8666 ALOGE("re-negotiation is needed");
8667 framesRead = -1; // Will cause an attempt to recover.
8668 break;
8669 default:
8670 ALOGE("unknown error %d on read from pipe", status);
8671 break;
8672 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008673 }
8674 // otherwise use the HAL / AudioStreamIn directly
8675 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008676 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008677 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008678 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008679 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008680 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008681 if (result < 0) {
8682 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008683 } else {
8684 framesRead = bytesRead / mFrameSize;
8685 }
8686 }
8687
Andy Hung446f4df2019-02-21 12:26:41 -08008688 const int64_t lastIoEndNs = systemTime(); // end IO timing
8689
Andy Hung3f0c9022016-01-15 17:49:46 -08008690 // Update server timestamp with server stats
8691 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008692 if (framesRead >= 0) {
8693 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8694 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8695 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008696
8697 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008698 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008699 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008700 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008701 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8702 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8703 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008704 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008705 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8706
8707 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008708 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008709 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008710 id(), (long long)time, (long long)position);
8711 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8712 position = correctedTimestamp.mFrames;
8713 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008714 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008715 id(), (long long)time, (long long)position);
8716 }
8717
Andy Hung3f0c9022016-01-15 17:49:46 -08008718 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8719 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8720 // Note: In general record buffers should tend to be empty in
8721 // a properly running pipeline.
8722 //
8723 // Also, it is not advantageous to call get_presentation_position during the read
8724 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008725 } else {
8726 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008727 }
8728 }
Andy Hunge6c37112019-02-26 17:38:10 -08008729
8730 // From the timestamp, input read latency is negative output write latency.
8731 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008732 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008733 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8734 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8735 mLatencyMs.add(latencyMs);
8736 }
8737
Andy Hung3f0c9022016-01-15 17:49:46 -08008738 // Use this to track timestamp information
8739 // ALOGD("%s", mTimestamp.toString().c_str());
8740
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008741 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008742 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008743 // Force input into standby so that it tries to recover at next read attempt
8744 inputStandBy();
8745 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008746 }
8747 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008748 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008749 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008750 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008751 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008752
Andy Hung8946a282018-04-19 20:04:56 -07008753#ifdef TEE_SINK
8754 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8755#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008756 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008757 {
8758 size_t part1 = mRsmpInFramesP2 - rear;
8759 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008760 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008761 (framesRead - part1) * mFrameSize);
8762 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008763 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008764 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008765
8766 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008767
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008768 // loop over each active track
8769 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008770 if (activeTrack) { // ensure track release is outside lock.
8771 oldActiveTracks.emplace_back(std::move(activeTrack));
8772 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008773 activeTrack = activeTracks[i];
8774
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008775 // skip fast tracks, as those are handled directly by FastCapture
8776 if (activeTrack->isFastTrack()) {
8777 continue;
8778 }
8779
Andy Hung73c02e42015-03-29 01:13:58 -07008780 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008781 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8782
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008783 enum {
8784 OVERRUN_UNKNOWN,
8785 OVERRUN_TRUE,
8786 OVERRUN_FALSE
8787 } overrun = OVERRUN_UNKNOWN;
8788
8789 // loop over getNextBuffer to handle circular sink
8790 for (;;) {
8791
Andy Hung8d31fd22023-06-26 19:20:57 -07008792 activeTrack->sinkBuffer().frameCount = ~0;
8793 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8794 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008795 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8796
Andy Hung73c02e42015-03-29 01:13:58 -07008797 // check available frames and handle overrun conditions
8798 // if the record track isn't draining fast enough.
8799 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008800 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008801 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008802 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008803 overrun = OVERRUN_TRUE;
8804 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008805 if (framesOut == 0 || framesIn == 0) {
8806 break;
8807 }
8808
Andy Hung6770c6f2015-04-07 13:43:36 -07008809 // Don't allow framesOut to be larger than what is possible with resampling
8810 // from framesIn.
8811 // This isn't strictly necessary but helps limit buffer resizing in
8812 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008813 if (audio_is_linear_pcm(activeTrack->format())) {
8814 framesOut = min(framesOut,
8815 destinationFramesPossible(
8816 framesIn, mSampleRate, activeTrack->sampleRate()));
8817 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008818
8819 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008820 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008821 // straight from RecordThread buffer to RecordTrack buffer.
8822 AudioBufferProvider::Buffer buffer;
8823 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008824 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008825 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008826 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008827 ALOGV_IF(buffer.frameCount != framesOut,
8828 "%s() read less than expected (%zu vs %zu)",
8829 __func__, buffer.frameCount, framesOut);
8830 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008831 memcpy(activeTrack->sinkBuffer().raw,
8832 buffer.raw, buffer.frameCount * mFrameSize);
8833 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008834 } else {
8835 framesOut = 0;
8836 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008837 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008838 }
8839 } else {
8840 // process frames from the RecordThread buffer provider to the RecordTrack
8841 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008842 framesOut = activeTrack->recordBufferConverter()->convert(
8843 activeTrack->sinkBuffer().raw,
8844 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008845 framesOut);
8846 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008847
8848 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8849 overrun = OVERRUN_FALSE;
8850 }
8851
Andy Hung93bb5732023-05-04 21:16:34 -07008852 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8853 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008854 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008855 if (framesToDrop == 0) {
8856 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008857 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008858 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008859 // Sanitize before releasing if the track has no access to the source data
8860 // An idle UID receives silence from non virtual devices until active
8861 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008862 memset(activeTrack->sinkBuffer().raw,
8863 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008864 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008865 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008866 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008867 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008868 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008869 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008870 }
8871 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008872
8873 switch (overrun) {
8874 case OVERRUN_TRUE:
8875 // client isn't retrieving buffers fast enough
8876 if (!activeTrack->setOverflow()) {
8877 nsecs_t now = systemTime();
8878 // FIXME should lastWarning per track?
8879 if ((now - lastWarning) > kWarningThrottleNs) {
8880 ALOGW("RecordThread: buffer overflow");
8881 lastWarning = now;
8882 }
8883 }
8884 break;
8885 case OVERRUN_FALSE:
8886 activeTrack->clearOverflow();
8887 break;
8888 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008889 break;
8890 }
8891
Andy Hung3f0c9022016-01-15 17:49:46 -08008892 // update frame information and push timestamp out
8893 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008894 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008895 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8896 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008897 }
8898
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008899unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008900 // enable changes in effect chain
8901 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008902 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008903 if (audio_has_proportional_frames(mFormat)
8904 && loopCount == lastLoopCountRead + 1) {
8905 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8906 const double jitterMs =
8907 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8908 {framesRead, readPeriodNs},
8909 {0, 0} /* lastTimestamp */, mSampleRate);
8910 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8911
Andy Hung972bec12023-08-31 16:13:39 -07008912 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008913 mIoJitterMs.add(jitterMs);
8914 mProcessTimeMs.add(processMs);
8915 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008916 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008917 // update timing info.
8918 mLastIoBeginNs = lastIoBeginNs;
8919 mLastIoEndNs = lastIoEndNs;
8920 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008921 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008922 mThreadloopExecutor.process(); // process any remaining deferred actions.
8923 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008924
Glenn Kasten93e471f2013-08-19 08:40:07 -07008925 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008926
8927 {
Andy Hung972bec12023-08-31 16:13:39 -07008928 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008929 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008930 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008931 track->invalidate();
8932 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008933 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008934 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008935 }
8936
8937 releaseWakeLock();
8938
8939 ALOGV("RecordThread %p exiting", this);
8940 return false;
8941}
8942
Andy Hungee58e4a2023-07-07 13:47:37 -07008943void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008944{
8945 if (!mStandby) {
8946 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008947 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008948 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008949 mStandby = true;
8950 }
8951}
8952
Andy Hungee58e4a2023-07-07 13:47:37 -07008953void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008954{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008955 // Idle the fast capture if it's currently running
8956 if (mFastCapture != 0) {
8957 FastCaptureStateQueue *sq = mFastCapture->sq();
8958 FastCaptureState *state = sq->begin();
8959 if (!(state->mCommand & FastCaptureState::IDLE)) {
8960 state->mCommand = FastCaptureState::COLD_IDLE;
8961 state->mColdFutexAddr = &mFastCaptureFutex;
8962 state->mColdGen++;
8963 mFastCaptureFutex = 0;
8964 sq->end();
8965 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8966 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8967#if 0
8968 if (kUseFastCapture == FastCapture_Dynamic) {
8969 // FIXME
8970 }
8971#endif
8972#ifdef AUDIO_WATCHDOG
8973 // FIXME
8974#endif
8975 } else {
8976 sq->end(false /*didModify*/);
8977 }
8978 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008979 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008980 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008981
8982 // If going into standby, flush the pipe source.
8983 if (mPipeSource.get() != nullptr) {
8984 const ssize_t flushed = mPipeSource->flush();
8985 if (flushed > 0) {
8986 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8987 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8988 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8989 }
8990 }
Eric Laurent81784c32012-11-19 14:55:58 -08008991}
8992
Andy Hungc5007f82023-08-29 14:26:09 -07008993// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008994sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008995 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008996 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008997 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008998 audio_format_t format,
8999 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08009000 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08009001 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009002 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009003 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00009004 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07009005 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08009006 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08009007 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009008 audio_port_handle_t portId,
9009 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009010{
Glenn Kasten74935e42013-12-19 08:56:45 -08009011 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009012 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009013 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009014 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009015 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009016 audio_input_flags_t requestedFlags = *flags;
9017 uint32_t sampleRate;
9018
9019 lStatus = initCheck();
9020 if (lStatus != NO_ERROR) {
9021 ALOGE("createRecordTrack_l() audio driver not initialized");
9022 goto Exit;
9023 }
9024
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009025 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9026 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9027 lStatus = BAD_VALUE;
9028 goto Exit;
9029 }
9030
Eric Laurentec376dc2021-04-08 20:41:22 +02009031 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009032 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009033 lStatus = PERMISSION_DENIED;
9034 goto Exit;
9035 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009036 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009037 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009038 lStatus = BAD_VALUE;
9039 goto Exit;
9040 }
9041 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009042 if (*pSampleRate == 0) {
9043 *pSampleRate = mSampleRate;
9044 }
9045 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009046
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009047 // special case for FAST flag considered OK if fast capture is present and access to
9048 // audio history is not required
9049 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009050 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9051 }
9052
Eric Laurentf14db3c2017-12-08 14:20:36 -08009053 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009054 if ((*flags & inputFlags) != *flags) {
9055 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9056 " input flags (%08x)",
9057 *flags, inputFlags);
9058 *flags = (audio_input_flags_t)(*flags & inputFlags);
9059 }
Eric Laurent81784c32012-11-19 14:55:58 -08009060
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009061 // client expresses a preference for FAST and no access to audio history,
9062 // but we get the final say
9063 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009064 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009065 // we formerly checked for a callback handler (non-0 tid),
9066 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009067 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009068 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009069 // Frame count is not specified (0), or is less than or equal the pipe depth.
9070 // It is OK to provide a higher capacity than requested.
9071 // We will force it to mPipeFramesP2 below.
9072 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009073 // PCM data
9074 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009075 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009076 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009077 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009078 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009079 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009080 hasFastCapture() &&
9081 // there are sufficient fast track slots available
9082 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009083 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009084 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009085 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009086 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009087 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009088 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009089 audio_input_flags_t old = *flags;
9090 chain->checkInputFlagCompatibility(flags);
9091 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009092 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9093 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009094 }
9095 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009096 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009097 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9098 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009099 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009100 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9101 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009102 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009103 this, frameCount, mFrameCount, mPipeFramesP2,
9104 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009105 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009106 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009107 }
9108 }
9109
Eric Laurentf14db3c2017-12-08 14:20:36 -08009110 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9111 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9112 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9113 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9114 lStatus = BAD_TYPE;
9115 goto Exit;
9116 }
9117
Glenn Kasten74105912014-07-03 12:28:53 -07009118 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009119 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009120 // fast track: frame count is exactly the pipe depth
9121 frameCount = mPipeFramesP2;
9122 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009123 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009124 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009125 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9126 // or 20 ms if there is a fast capture
9127 // TODO This could be a roundupRatio inline, and const
9128 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9129 * sampleRate + mSampleRate - 1) / mSampleRate;
9130 // minimum number of notification periods is at least kMinNotifications,
9131 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9132 static const size_t kMinNotifications = 3;
9133 static const uint32_t kMinMs = 30;
9134 // TODO This could be a roundupRatio inline
9135 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9136 // TODO This could be a roundupRatio inline
9137 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9138 maxNotificationFrames;
9139 const size_t minFrameCount = maxNotificationFrames *
9140 max(kMinNotifications, minNotificationsByMs);
9141 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009142 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9143 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009144 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009145 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009146 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009147 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009148
Andy Hungc5007f82023-08-29 14:26:09 -07009149 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009150 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009151 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009152 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009153 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009154 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009155 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009156 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009157 }
Eric Laurent81784c32012-11-19 14:55:58 -08009158
Andy Hung8d31fd22023-06-26 19:20:57 -07009159 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009160 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009161 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009162 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009163 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009164
Glenn Kasten03003332013-08-06 15:40:54 -07009165 lStatus = track->initCheck();
9166 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009167 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009168 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009169 goto Exit;
9170 }
9171 mTracks.add(track);
9172
Eric Laurent05067782016-06-01 18:27:28 -07009173 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009174 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9175 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9176 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009177 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009178 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009179
9180 if (maxSharedAudioHistoryMs != 0) {
9181 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9182 }
Eric Laurent81784c32012-11-19 14:55:58 -08009183 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009184
Eric Laurent81784c32012-11-19 14:55:58 -08009185 lStatus = NO_ERROR;
9186
9187Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009188 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009189 return track;
9190}
9191
Andy Hungee58e4a2023-07-07 13:47:37 -07009192status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009193 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009194 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009195{
9196 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9197 sp<ThreadBase> strongMe = this;
9198 status_t status = NO_ERROR;
9199
9200 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009201 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009202 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009203 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009204 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009205 event, triggerSession,
9206 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009207 }
9208
9209 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009210 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009211 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009212 if (recordTrack->isInvalid()) {
9213 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009214 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9215 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009216 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009217 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009218 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009219 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9220 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009221 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009222 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009223 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009224 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009225 }
9226 return status;
9227 }
9228
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009229 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9230 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9231 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009232 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009233 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009234 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009235 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009236 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009237 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009238 if (recordTrack->isInvalid()) {
9239 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009240 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9241 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009242 // STARTING_2 forces destroy to call stopInput.
9243 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009244 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9245 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009246 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009247 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009248 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009249 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009250 // Someone else has changed state, let them take over,
9251 // leave mState in the new state.
9252 recordTrack->clearSyncStartEvent();
9253 return INVALID_OPERATION;
9254 }
9255 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009256 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009257 ALOGW("%s(%d): startInput failed, status %d",
9258 __func__, recordTrack->id(), status);
9259 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9260 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009261 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009262 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009263 return status;
9264 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009265 sendIoConfigEvent_l(
9266 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009267 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009268
9269 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9270
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009271 // Catch up with current buffer indices if thread is already running.
9272 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9273 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9274 // see previously buffered data before it called start(), but with greater risk of overrun.
9275
Andy Hung8d31fd22023-06-26 19:20:57 -07009276 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009277 if (!recordTrack->isDirect()) {
9278 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009279 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009280 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009281 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009282 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009283 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009284 return status;
9285 }
Eric Laurent81784c32012-11-19 14:55:58 -08009286}
9287
Andy Hungee58e4a2023-07-07 13:47:37 -07009288void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009289{
Andy Hungee58e4a2023-07-07 13:47:37 -07009290 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009291
9292 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009293 sp<IAfTrackBase> ptr =
9294 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9295 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009296 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009297 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009298 }
Eric Laurent81784c32012-11-19 14:55:58 -08009299 }
9300}
9301
Andy Hungee58e4a2023-07-07 13:47:37 -07009302bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009303 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009304 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009305 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009306 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009307 return false;
9308 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009309 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009310 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009311
Andy Hungabfab202019-03-07 19:45:54 -08009312 // NOTE: Waiting here is important to keep stop synchronous.
9313 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009314 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009315 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009316 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009317 }
Andy Hungce685402018-10-05 17:23:27 -07009318
Andy Hung8d31fd22023-06-26 19:20:57 -07009319 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009320 ALOGV("Record stopped OK");
9321 return true;
9322 }
Andy Hungce685402018-10-05 17:23:27 -07009323
9324 // don't handle anything - we've been invalidated or restarted and in a different state
9325 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009326 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009327 return false;
9328}
9329
Andy Hungee58e4a2023-07-07 13:47:37 -07009330bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009331{
9332 return false;
9333}
9334
Andy Hungee58e4a2023-07-07 13:47:37 -07009335status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009336{
9337#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9338 if (!isValidSyncEvent(event)) {
9339 return BAD_VALUE;
9340 }
9341
Glenn Kastend848eb42016-03-08 13:42:11 -08009342 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009343 status_t ret = NAME_NOT_FOUND;
9344
Andy Hung972bec12023-08-31 16:13:39 -07009345 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009346
9347 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009348 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009349 if (eventSession == track->sessionId()) {
9350 (void) track->setSyncEvent(event);
9351 ret = NO_ERROR;
9352 }
9353 }
9354 return ret;
9355#else
9356 return BAD_VALUE;
9357#endif
9358}
9359
Andy Hungee58e4a2023-07-07 13:47:37 -07009360status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009361 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009362{
9363 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009364 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009365 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009366 return NO_INIT;
9367 }
jiabin9ff780e2018-03-19 18:19:52 -07009368 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9369 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009370}
9371
Andy Hungee58e4a2023-07-07 13:47:37 -07009372status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009373 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009374{
Paul McLean12340082019-03-19 09:35:05 -06009375 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009376 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009377 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009378 return NO_INIT;
9379 }
Paul McLean12340082019-03-19 09:35:05 -06009380 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009381}
9382
Andy Hungee58e4a2023-07-07 13:47:37 -07009383status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009384{
Paul McLean12340082019-03-19 09:35:05 -06009385 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009386 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009387 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009388 return NO_INIT;
9389 }
Paul McLean12340082019-03-19 09:35:05 -06009390 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009391}
9392
Andy Hungee58e4a2023-07-07 13:47:37 -07009393status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009394 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9395 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009396 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009397 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9398}
9399
Andy Hungee58e4a2023-07-07 13:47:37 -07009400status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009401 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9402 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009403
Eric Laurentec376dc2021-04-08 20:41:22 +02009404 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9405 return BAD_VALUE;
9406 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009407
9408 if (sharedAudioStartMs < 0
9409 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009410 return BAD_VALUE;
9411 }
9412
Eric Laurent2407ce32021-04-26 14:56:03 +02009413 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9414 // As we cannot detect more than one wraparound, only accept values up current write position
9415 // after one wraparound
9416 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9417 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009418 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009419 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9420 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009421 // Bring the start frame position within the input buffer to match the documented
9422 // "best effort" behavior of the API.
9423 if (sharedOffset < 0) {
9424 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009425 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009426 sharedAudioStartFrames =
9427 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009428 }
9429
Eric Laurentec376dc2021-04-08 20:41:22 +02009430 mSharedAudioPackageName = sharedAudioPackageName;
9431 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009432 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009433 } else {
9434 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009435 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009436 }
9437 return NO_ERROR;
9438}
9439
Andy Hungee58e4a2023-07-07 13:47:37 -07009440void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009441 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9442 mSharedAudioStartFrames = -1;
9443 mSharedAudioPackageName = "";
9444}
9445
Andy Hungee58e4a2023-07-07 13:47:37 -07009446ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009447{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009448 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009449 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009450 }
9451 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009452 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009453 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009454 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009455 }
9456 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009457 MetadataUpdate change;
9458 change.recordMetadataUpdate = metadata.tracks;
9459 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009460}
9461
Andy Hungc5007f82023-08-29 14:26:09 -07009462// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009463void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009464{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009465 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009466 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009467
Eric Laurent81784c32012-11-19 14:55:58 -08009468 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009469 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009470 removeTrack_l(track);
9471 }
9472}
9473
Andy Hungee58e4a2023-07-07 13:47:37 -07009474void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009475{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009476 String8 result;
9477 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009478 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009479
Eric Laurent81784c32012-11-19 14:55:58 -08009480 mTracks.remove(track);
9481 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009482 if (track->isFastTrack()) {
9483 ALOG_ASSERT(!mFastTrackAvail);
9484 mFastTrackAvail = true;
9485 }
Eric Laurent81784c32012-11-19 14:55:58 -08009486}
9487
Andy Hungee58e4a2023-07-07 13:47:37 -07009488void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009489{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009490 AudioStreamIn *input = mInput;
9491 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9492 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009493 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009494 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009495 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009496 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009497 }
Andy Hungbfa64962017-06-12 14:43:19 -07009498
9499 if (input != nullptr) {
9500 dprintf(fd, " Hal stream dump:\n");
9501 (void)input->stream->dump(fd);
9502 }
9503
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009504 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009505 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009506
Glenn Kasten2f90c512015-12-02 11:40:09 -08009507 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9508 // while we are dumping it. It may be inconsistent, but it won't mutate!
9509 // This is a large object so we place it on the heap.
9510 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009511 const std::unique_ptr<FastCaptureDumpState> copy =
9512 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009513 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009514}
9515
Andy Hungee58e4a2023-07-07 13:47:37 -07009516void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009517{
Eric Laurent81784c32012-11-19 14:55:58 -08009518 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009519 size_t numtracks = mTracks.size();
9520 size_t numactive = mActiveTracks.size();
9521 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009522 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009523 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009524 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009525 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009526 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009527 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009528 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009529 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009530 if (track != 0) {
9531 bool active = mActiveTracks.indexOf(track) >= 0;
9532 if (active) {
9533 numactiveseen++;
9534 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009535 result.append(prefix);
9536 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009537 }
Eric Laurent81784c32012-11-19 14:55:58 -08009538 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009539 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009540 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009541 }
9542
Marco Nelissenb2208842014-02-07 14:00:50 -08009543 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009544 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009545 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009546 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009547 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009548 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009549 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009550 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009551 result.append(prefix);
9552 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009553 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009554 }
Eric Laurent81784c32012-11-19 14:55:58 -08009555
9556 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009557 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009558}
9559
Andy Hungee58e4a2023-07-07 13:47:37 -07009560void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009561{
Andy Hung972bec12023-08-31 16:13:39 -07009562 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009563 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009564 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009565 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009566 track->setSilenced(silenced);
9567 }
9568 }
9569}
Andy Hung73c02e42015-03-29 01:13:58 -07009570
Andy Hung8d31fd22023-06-26 19:20:57 -07009571void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009572{
Andy Hung87c693c2023-07-06 20:56:16 -07009573 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009574 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009575 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009576 const int32_t rear = recordThread->mRsmpInRear;
9577 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009578 if (mRecordTrack->startFrames() >= 0) {
9579 int32_t startFrames = mRecordTrack->startFrames();
9580 // Accept a recent wraparound of mRsmpInRear
9581 if (startFrames <= rear) {
9582 deltaFrames = rear - startFrames;
9583 } else {
9584 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009585 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009586 // start frame cannot be further in the past than start of resampling buffer
9587 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9588 deltaFrames = recordThread->mRsmpInFrames;
9589 }
9590 }
9591 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009592}
9593
Andy Hung8d31fd22023-06-26 19:20:57 -07009594void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009595 size_t *framesAvailable, bool *hasOverrun)
9596{
Andy Hung87c693c2023-07-06 20:56:16 -07009597 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009598 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009599 const int32_t rear = recordThread->mRsmpInRear;
9600 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009601 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009602
9603 size_t framesIn;
9604 bool overrun = false;
9605 if (filled < 0) {
9606 // should not happen, but treat like a massive overrun and re-sync
9607 framesIn = 0;
9608 mRsmpInFront = rear;
9609 overrun = true;
9610 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9611 framesIn = (size_t) filled;
9612 } else {
9613 // client is not keeping up with server, but give it latest data
9614 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009615 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9616 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009617 overrun = true;
9618 }
9619 if (framesAvailable != NULL) {
9620 *framesAvailable = framesIn;
9621 }
9622 if (hasOverrun != NULL) {
9623 *hasOverrun = overrun;
9624 }
9625}
9626
Eric Laurent81784c32012-11-19 14:55:58 -08009627// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009628status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009629 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009630{
Andy Hung87c693c2023-07-06 20:56:16 -07009631 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009632 if (threadBase == 0) {
9633 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009634 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009635 return NOT_ENOUGH_DATA;
9636 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009637 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009638 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009639 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009640 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009641 // FIXME should not be P2 (don't want to increase latency)
9642 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009643 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009644 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009645
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009646 front &= recordThread->mRsmpInFramesP2 - 1;
9647 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009648 if (part1 > (size_t) filled) {
9649 part1 = filled;
9650 }
9651 size_t ask = buffer->frameCount;
9652 ALOG_ASSERT(ask > 0);
9653 if (part1 > ask) {
9654 part1 = ask;
9655 }
9656 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009657 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009658 buffer->raw = NULL;
9659 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009660 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009661 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009662 }
9663
Andy Hung57446612015-04-19 23:56:46 -07009664 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009665 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009666 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009667 return NO_ERROR;
9668}
9669
9670// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009671void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009672 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009673{
Hongwei Wang95e37682019-04-12 11:13:36 -07009674 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009675 if (stepCount == 0) {
9676 return;
9677 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009678 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009679 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009680 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009681 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009682 buffer->frameCount = 0;
9683}
9684
Andy Hungee58e4a2023-07-07 13:47:37 -07009685void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009686{
Andy Hung972bec12023-08-31 16:13:39 -07009687 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009688 checkBtNrec_l();
9689}
9690
Andy Hungee58e4a2023-07-07 13:47:37 -07009691void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009692{
9693 // disable AEC and NS if the device is a BT SCO headset supporting those
9694 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009695 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009696 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009697 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9698 for (size_t i = 0; i < mEffectChains.size(); i++) {
9699 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9700 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9701 }
9702 }
9703}
9704
Andy Hung97a893e2015-03-29 01:03:07 -07009705
Andy Hungee58e4a2023-07-07 13:47:37 -07009706bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009707 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009708{
9709 bool reconfig = false;
9710
Eric Laurent10351942014-05-08 18:49:52 -07009711 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009712
Eric Laurent10351942014-05-08 18:49:52 -07009713 audio_format_t reqFormat = mFormat;
9714 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009715 // 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 +08009716 [[maybe_unused]] audio_channel_mask_t channelMask =
9717 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009718
9719 AudioParameter param = AudioParameter(keyValuePair);
9720 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009721
9722 // scope for AutoPark extends to end of method
9723 AutoPark<FastCapture> park(mFastCapture);
9724
Eric Laurent10351942014-05-08 18:49:52 -07009725 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9726 // channel count change can be requested. Do we mandate the first client defines the
9727 // HAL sampling rate and channel count or do we allow changes on the fly?
9728 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9729 samplingRate = value;
9730 reconfig = true;
9731 }
9732 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009733 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009734 status = BAD_VALUE;
9735 } else {
9736 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009737 reconfig = true;
9738 }
Eric Laurent10351942014-05-08 18:49:52 -07009739 }
9740 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9741 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009742 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009743 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009744 status = BAD_VALUE;
9745 } else {
9746 channelMask = mask;
9747 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009748 }
Eric Laurent10351942014-05-08 18:49:52 -07009749 }
9750 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9751 // do not accept frame count changes if tracks are open as the track buffer
9752 // size depends on frame count and correct behavior would not be guaranteed
9753 // if frame count is changed after track creation
9754 if (mActiveTracks.size() > 0) {
9755 status = INVALID_OPERATION;
9756 } else {
9757 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009758 }
Eric Laurent10351942014-05-08 18:49:52 -07009759 }
9760 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009761 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009762 }
9763 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9764 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009765 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009766 }
Glenn Kastene198c362013-08-13 09:13:36 -07009767
Eric Laurent10351942014-05-08 18:49:52 -07009768 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009769 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009770 if (status == INVALID_OPERATION) {
9771 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009772 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009773 }
9774 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009775 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009776 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9777 if (mInput->stream->getAudioProperties(&config) == OK &&
9778 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9779 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009780 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009781 status = NO_ERROR;
9782 }
Eric Laurent81784c32012-11-19 14:55:58 -08009783 }
Eric Laurent10351942014-05-08 18:49:52 -07009784 if (status == NO_ERROR) {
9785 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009786 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009787 }
9788 }
Eric Laurent81784c32012-11-19 14:55:58 -08009789 }
Eric Laurent10351942014-05-08 18:49:52 -07009790
Eric Laurent81784c32012-11-19 14:55:58 -08009791 return reconfig;
9792}
9793
Andy Hungee58e4a2023-07-07 13:47:37 -07009794String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009795{
Andy Hung972bec12023-08-31 16:13:39 -07009796 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009797 if (initCheck() == NO_ERROR) {
9798 String8 out_s8;
9799 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9800 return out_s8;
9801 }
Eric Laurent81784c32012-11-19 14:55:58 -08009802 }
Andy Hung920f6572022-10-06 12:09:49 -07009803 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009804}
9805
Andy Hungab65b182023-09-06 19:41:47 -07009806void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009807 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009808 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009809 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009810 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009811 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009812 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009813 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9814 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009815 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009816 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009817 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009818 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009819 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009820 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009821 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009822 break;
9823 }
Andy Hungab65b182023-09-06 19:41:47 -07009824 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009825}
9826
Andy Hungee58e4a2023-07-07 13:47:37 -07009827void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009828{
Dean Wheatley6c009512023-10-23 09:34:14 +11009829 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9830 mSampleRate = audioConfig.sample_rate;
9831 mChannelMask = audioConfig.channel_mask;
9832 if (!audio_is_input_channel(mChannelMask)) {
9833 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9834 }
9835
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009836 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009837
9838 // Get actual HAL format.
9839 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9840 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9841 // Get format from the shim, which will be different than the HAL format
9842 // if recording compressed audio from IEC61937 wrapped sources.
9843 mFormat = audioConfig.format;
9844 if (!audio_is_valid_format(mFormat)) {
9845 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9846 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009847 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009848 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9849 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009850 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009851 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009852 ALOGI("HAL format %#x is not linear pcm", mFormat);
9853 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009854 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009855 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9856 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009857 result = mInput->stream->getBufferSize(&mBufferSize);
9858 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009859 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009860 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9861 "mBufferSize=%zu, mFrameCount=%zu",
9862 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009863
Eric Laurentec376dc2021-04-08 20:41:22 +02009864 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9865 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009866 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009867
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009868 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9869 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009870
9871 audio_input_flags_t flags = mInput->flags;
9872 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9873 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009874 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009875 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9876 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9877 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9878 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9879 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9880 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009881}
9882
Andy Hungee58e4a2023-07-07 13:47:37 -07009883uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009884{
Andy Hung972bec12023-08-31 16:13:39 -07009885 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009886 uint32_t result;
9887 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9888 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009889 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009890 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009891}
9892
Andy Hungee58e4a2023-07-07 13:47:37 -07009893KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009894{
Glenn Kastend848eb42016-03-08 13:42:11 -08009895 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009896 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009897 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009898 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009899 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009900 if (ids.indexOfKey(sessionId) < 0) {
9901 ids.add(sessionId, true);
9902 }
9903 }
9904 return ids;
9905}
9906
Andy Hungee58e4a2023-07-07 13:47:37 -07009907AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009908{
Andy Hung972bec12023-08-31 16:13:39 -07009909 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009910 AudioStreamIn *input = mInput;
9911 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009912 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009913 return input;
9914}
9915
Andy Hungc5007f82023-08-29 14:26:09 -07009916// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009917sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009918{
9919 if (mInput == NULL) {
9920 return NULL;
9921 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009922 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009923}
9924
Andy Hungee58e4a2023-07-07 13:47:37 -07009925status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009926{
Eric Laurent81784c32012-11-19 14:55:58 -08009927 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009928 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009929 chain->setInBuffer(NULL);
9930 chain->setOutBuffer(NULL);
9931
9932 checkSuspendOnAddEffectChain_l(chain);
9933
Eric Laurent1b928682014-10-02 19:41:47 -07009934 // make sure enabled pre processing effects state is communicated to the HAL as we
9935 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009936 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009937
Eric Laurent81784c32012-11-19 14:55:58 -08009938 mEffectChains.add(chain);
9939
9940 return NO_ERROR;
9941}
9942
Andy Hungee58e4a2023-07-07 13:47:37 -07009943size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009944{
9945 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009946
9947 for (size_t i = 0; i < mEffectChains.size(); i++) {
9948 if (chain == mEffectChains[i]) {
9949 mEffectChains.removeAt(i);
9950 break;
9951 }
Eric Laurent81784c32012-11-19 14:55:58 -08009952 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009953 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009954}
9955
Andy Hungee58e4a2023-07-07 13:47:37 -07009956status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009957 audio_patch_handle_t *handle)
9958{
9959 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009960
9961 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009962 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009963 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009964 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009965 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009966 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009967 }
9968
Eric Laurentd8365c52017-07-16 15:27:05 -07009969 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009970
9971 // store new source and send to effects
9972 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9973 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009974 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009975 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009976 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009977 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009978
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009979 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009980 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9981 status = hwDevice->createAudioPatch(patch->num_sources,
9982 patch->sources,
9983 patch->num_sinks,
9984 patch->sinks,
9985 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009986 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009987 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9988 patch->sinks[0].ext.mix.usecase.source,
9989 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009990 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009991 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009992
jiabinc52b1ff2019-10-31 17:20:42 -07009993 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009994 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009995 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009996 }
Eric Laurent296fb132015-05-01 11:38:42 -07009997
Andy Hungc2b11cb2020-04-22 09:04:01 -07009998 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009999 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -070010000 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -070010001 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -070010002 // also dispatch to active AudioRecords
10003 for (const auto &track : mActiveTracks) {
10004 track->logEndInterval();
10005 track->logBeginInterval(pathSourcesAsString);
10006 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010007 // Force meteadata update after a route change
10008 mActiveTracks.setHasChanged();
10009
Eric Laurent1c333e22014-05-20 10:48:17 -070010010 return status;
10011}
10012
Andy Hungee58e4a2023-07-07 13:47:37 -070010013status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010014{
10015 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010016
jiabinc52b1ff2019-10-31 17:20:42 -070010017 mPatch = audio_patch{};
10018 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010019
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010020 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010021 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10022 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010023 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010024 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010025 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010026 // Force meteadata update after a route change
10027 mActiveTracks.setHasChanged();
10028
Eric Laurent1c333e22014-05-20 10:48:17 -070010029 return status;
10030}
10031
Andy Hungee58e4a2023-07-07 13:47:37 -070010032void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010033{
Andy Hung972bec12023-08-31 16:13:39 -070010034 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010035 mOutDevices = outDevices;
10036 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10037 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010038 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010039 }
10040}
10041
Andy Hungee58e4a2023-07-07 13:47:37 -070010042int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010043{
10044 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010045 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010046 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010047 int32_t oldestFront = mRsmpInRear;
10048 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010049 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010050 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010051 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010052 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010053 if (filled > maxFilled) {
10054 oldestFront = front;
10055 maxFilled = filled;
10056 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010057 }
Andy Hung920f6572022-10-06 12:09:49 -070010058 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010059 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10060 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010061 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010062}
10063
Andy Hungee58e4a2023-07-07 13:47:37 -070010064void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010065{
10066 if (offset == 0) {
10067 return;
10068 }
10069 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010070 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010071 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010072 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010073 }
10074}
10075
Andy Hungee58e4a2023-07-07 13:47:37 -070010076void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010077{
10078 // This is the formula for calculating the temporary buffer size.
10079 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10080 // 1 full output buffer, regardless of the alignment of the available input.
10081 // The value is somewhat arbitrary, and could probably be even larger.
10082 // A larger value should allow more old data to be read after a track calls start(),
10083 // without increasing latency.
10084 //
10085 // Note this is independent of the maximum downsampling ratio permitted for capture.
10086 size_t minRsmpInFrames = mFrameCount * 7;
10087
10088 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10089 // capture history available to another client using the same session ID:
10090 // dimension the resampler input buffer accordingly.
10091
10092 // Get oldest client read position: getOldestFront_l() must be called before altering
10093 // mRsmpInRear, or mRsmpInFrames
10094 int32_t previousFront = getOldestFront_l();
10095 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10096 int32_t previousRear = mRsmpInRear;
10097 mRsmpInRear = 0;
10098
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010099 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010100 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010101 "resizeInputBuffer_l() called with invalid max shared history %d",
10102 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010103 if (maxSharedAudioHistoryMs != 0) {
10104 // resizeInputBuffer_l should never be called with a non zero shared history if the
10105 // buffer was not already allocated
10106 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10107 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10108 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10109 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010110 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010111 return;
10112 }
10113 mRsmpInFrames = rsmpInFrames;
10114 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010115 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010116 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10117 // initialized
10118 if (mRsmpInFrames < minRsmpInFrames) {
10119 mRsmpInFrames = minRsmpInFrames;
10120 }
10121 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10122
10123 // TODO optimize audio capture buffer sizes ...
10124 // Here we calculate the size of the sliding buffer used as a source
10125 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10126 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10127 // be better to have it derived from the pipe depth in the long term.
10128 // The current value is higher than necessary. However it should not add to latency.
10129
10130 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10131 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10132
10133 void *rsmpInBuffer;
10134 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10135 // if posix_memalign fails, will segv here.
10136 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10137
10138 // Copy audio history if any from old buffer before freeing it
10139 if (previousRear != 0) {
10140 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10141 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10142
10143 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10144 previousFront &= previousRsmpInFramesP2 - 1;
10145 size_t part1 = previousRsmpInFramesP2 - previousFront;
10146 if (part1 > (size_t) unread) {
10147 part1 = unread;
10148 }
10149 if (part1 != 0) {
10150 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10151 part1 * mFrameSize);
10152 mRsmpInRear = part1;
10153 part1 = unread - part1;
10154 if (part1 != 0) {
10155 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10156 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10157 mRsmpInRear += part1;
10158 }
10159 }
10160 // Update front for all clients according to new rear
10161 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10162 } else {
10163 mRsmpInRear = 0;
10164 }
10165 free(mRsmpInBuffer);
10166 mRsmpInBuffer = rsmpInBuffer;
10167}
10168
Andy Hungee58e4a2023-07-07 13:47:37 -070010169void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010170{
Andy Hung972bec12023-08-31 16:13:39 -070010171 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010172 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010173 if (record->getSource()) {
10174 mSource = record->getSource();
10175 }
Eric Laurent83b88082014-06-20 18:31:16 -070010176}
10177
Andy Hungee58e4a2023-07-07 13:47:37 -070010178void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010179{
Andy Hung972bec12023-08-31 16:13:39 -070010180 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010181 if (mSource == record->getSource()) {
10182 mSource = mInput;
10183 }
Eric Laurent83b88082014-06-20 18:31:16 -070010184 destroyTrack_l(record);
10185}
10186
Andy Hungee58e4a2023-07-07 13:47:37 -070010187void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010188{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010189 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010190 config->role = AUDIO_PORT_ROLE_SINK;
10191 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10192 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010193 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10194 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10195 config->flags.input = mInput->flags;
10196 }
Eric Laurent83b88082014-06-20 18:31:16 -070010197}
Eric Laurent1c333e22014-05-20 10:48:17 -070010198
Eric Laurent6acd1d42017-01-04 14:23:29 -080010199// ----------------------------------------------------------------------------
10200// Mmap
10201// ----------------------------------------------------------------------------
10202
Andy Hung7aa7d102023-07-07 15:58:48 -070010203// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10204// MmapPlaybackThread or MmapCaptureThread instance.
10205class MmapThreadHandle : public MmapStreamInterface {
10206public:
10207 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10208 ~MmapThreadHandle() override;
10209
10210 // MmapStreamInterface virtuals
10211 status_t createMmapBuffer(int32_t minSizeFrames,
10212 struct audio_mmap_buffer_info* info) final;
10213 status_t getMmapPosition(struct audio_mmap_position* position) final;
10214 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10215 status_t start(const AudioClient& client,
10216 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10217 status_t stop(audio_port_handle_t handle) final;
10218 status_t standby() final;
10219 status_t reportData(const void* buffer, size_t frameCount) final;
10220private:
10221 const sp<IAfMmapThread> mThread;
10222};
10223
10224/* static */
10225sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10226 const sp<IAfMmapThread>& mmapThread) {
10227 return sp<MmapThreadHandle>::make(mmapThread);
10228}
10229
10230MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231 : mThread(thread)
10232{
Phil Burk9fabbf82017-08-03 12:02:00 -070010233 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010234}
10235
Andy Hung7aa7d102023-07-07 15:58:48 -070010236// MmapStreamInterface could be directly implemented by MmapThread excepting this
10237// special handling on adapter dtor.
10238MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010239{
Phil Burk9fabbf82017-08-03 12:02:00 -070010240 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010241}
10242
Andy Hung7aa7d102023-07-07 15:58:48 -070010243status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010244 struct audio_mmap_buffer_info *info)
10245{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246 return mThread->createMmapBuffer(minSizeFrames, info);
10247}
10248
Andy Hung7aa7d102023-07-07 15:58:48 -070010249status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010250{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251 return mThread->getMmapPosition(position);
10252}
10253
Andy Hung7aa7d102023-07-07 15:58:48 -070010254status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010255 int64_t *timeNanos) {
10256 return mThread->getExternalPosition(position, timeNanos);
10257}
10258
Andy Hung7aa7d102023-07-07 15:58:48 -070010259status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010260 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261{
jiabind1f1cb62020-03-24 11:57:57 -070010262 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263}
10264
Andy Hung7aa7d102023-07-07 15:58:48 -070010265status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010267 return mThread->stop(handle);
10268}
10269
Andy Hung7aa7d102023-07-07 15:58:48 -070010270status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010271{
Eric Laurent18b57012017-02-13 16:23:52 -080010272 return mThread->standby();
10273}
10274
Andy Hung7aa7d102023-07-07 15:58:48 -070010275status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10276{
jiabinfc791ee2023-02-15 19:43:40 +000010277 return mThread->reportData(buffer, frameCount);
10278}
10279
Eric Laurent6acd1d42017-01-04 14:23:29 -080010280
Andy Hungee58e4a2023-07-07 13:47:37 -070010281MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010282 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010283 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010284 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010285 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010286 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010287 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010288 mActiveTracks(&this->mLocalLog),
10289 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10290 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010291{
Eric Laurent18b57012017-02-13 16:23:52 -080010292 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010293 readHalParameters_l();
10294}
10295
Andy Hungee58e4a2023-07-07 13:47:37 -070010296void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010297{
10298 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10299}
10300
Andy Hungee58e4a2023-07-07 13:47:37 -070010301void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010302{
Andy Hung8d31fd22023-06-26 19:20:57 -070010303 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010304 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010305 {
Andy Hung972bec12023-08-31 16:13:39 -070010306 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010307 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010308 activeTracks.add(t);
10309 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010310 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010311 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010312 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010313 stop(t->portId());
10314 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010315 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010317 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010318 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010319 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010320 }
10321}
10322
10323
Andy Hung8d672e02023-09-15 18:19:28 -070010324void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010325 audio_stream_type_t streamType __unused,
10326 audio_session_t sessionId,
10327 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010328 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010329 audio_port_handle_t portId)
10330{
10331 mAttr = *attr;
10332 mSessionId = sessionId;
10333 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010334 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335 mPortId = portId;
10336}
10337
Andy Hungee58e4a2023-07-07 13:47:37 -070010338status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339 struct audio_mmap_buffer_info *info)
10340{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010341 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342 if (mHalStream == 0) {
10343 return NO_INIT;
10344 }
Eric Laurent18b57012017-02-13 16:23:52 -080010345 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346 return mHalStream->createMmapBuffer(minSizeFrames, info);
10347}
10348
Andy Hungee58e4a2023-07-07 13:47:37 -070010349status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010351 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352 if (mHalStream == 0) {
10353 return NO_INIT;
10354 }
10355 return mHalStream->getMmapPosition(position);
10356}
10357
Andy Hungee58e4a2023-07-07 13:47:37 -070010358status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010359{
Eric Laurentdda206a2022-07-08 17:28:35 +020010360 // The HAL must receive track metadata before starting the stream
10361 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010362 status_t ret = mHalStream->start();
10363 if (ret != NO_ERROR) {
10364 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10365 return ret;
10366 }
Andy Hungcf10d742020-04-28 15:38:24 -070010367 if (mStandby) {
10368 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010369 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010370 mStandby = false;
10371 }
Eric Laurent331679c2018-04-16 17:03:16 -070010372 return NO_ERROR;
10373}
10374
Andy Hungee58e4a2023-07-07 13:47:37 -070010375status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010376 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377 audio_port_handle_t *handle)
10378{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010379 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010380 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010381 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010382 if (mHalStream == 0) {
10383 return NO_INIT;
10384 }
10385
10386 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010387
Eric Laurentdda206a2022-07-08 17:28:35 +020010388 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010389 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010390 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010391 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010392 }
10393
10394 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10395
10396 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010397 AttributionSourceState adjAttributionSource;
10398 if (!com::android::media::audio::audioserver_permissions()) {
10399 adjAttributionSource = afutils::checkAttributionSourcePackage(
10400 client.attributionSource);
10401 } else {
10402 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10403 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10404 client.attributionSource,
10405 mAfThreadCallback->getPermissionProvider()
10406 );
10407 if (!validatedRes.has_value()) {
10408 ALOGE("MMAP client package validation fail: %s",
10409 validatedRes.error().toString8().c_str());
10410 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10411 }
10412 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10413 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010414
Andy Hung3f49ebb2023-09-19 14:48:41 -070010415 const auto localSessionId = mSessionId;
10416 auto localAttr = mAttr;
Andy Hung6b137d12024-08-27 22:35:17 +000010417 float volume = 0.0f;
Eric Laurenta54f1282017-07-01 19:39:32 -070010418 if (isOutput()) {
10419 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10420 config.sample_rate = mSampleRate;
10421 config.channel_mask = mChannelMask;
10422 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010423 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010424 audio_output_flags_t flags =
10425 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010426 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010427 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010428 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010429 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010430 mutex().unlock();
10431 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10432 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010433 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010434 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010435 &config,
10436 flags,
10437 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010438 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010439 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010440 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +000010441 &isBitPerfect,
10442 &volume);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010443 mutex().lock();
10444 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010445 ALOGD_IF(!secondaryOutputs.empty(),
10446 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010447 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010448 audio_config_base_t config;
10449 config.sample_rate = mSampleRate;
10450 config.channel_mask = mChannelMask;
10451 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010452 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010453 mutex().unlock();
10454 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010455 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010456 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010457 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010458 &config,
10459 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10460 &deviceId,
10461 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010462 mutex().lock();
10463 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010464 }
10465 // APM should not chose a different input or output stream for the same set of attributes
10466 // and audo configuration
10467 if (ret != NO_ERROR || io != mId) {
10468 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10469 __FUNCTION__, ret, io, mId);
10470 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010471 }
10472
10473 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010474 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010475 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010476 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010477 } else {
jiabin09609032022-06-15 19:26:01 +000010478 {
10479 // Add the track record before starting input so that the silent status for the
10480 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010481 setClientSilencedState_l(portId, false /*silenced*/);
10482 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010483 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010484 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010485 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010486 }
10487
10488 // abort if start is rejected by audio policy manager
10489 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010490 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010491 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010492 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010493 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010494 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010496 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497 }
Andy Hungc5007f82023-08-29 14:26:09 -070010498 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010499 } else {
10500 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010501 }
jiabin09609032022-06-15 19:26:01 +000010502 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503 return PERMISSION_DENIED;
10504 }
10505
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010506 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010507 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10508 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010509 mChannelMask, mSessionId, isOutput(),
10510 client.attributionSource,
Andy Hung6b137d12024-08-27 22:35:17 +000010511 IPCThreadState::self()->getCallingPid(), portId,
10512 volume);
jiabin09609032022-06-15 19:26:01 +000010513 if (!isOutput()) {
10514 track->setSilenced_l(isClientSilenced_l(portId));
10515 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010516
Eric Laurent4eb58f12018-12-07 16:41:02 -080010517 if (isOutput()) {
10518 // force volume update when a new track is added
10519 mHalVolFloat = -1.0f;
10520 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010521 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010522 if (t->isSilenced_l()
10523 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010524 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010525 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010526 }
10527 }
10528
Eric Laurent6acd1d42017-01-04 14:23:29 -080010529 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010530 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010532 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010533 chain->incTrackCnt();
10534 chain->incActiveTrackCnt();
10535 }
10536
Andy Hungc2b11cb2020-04-22 09:04:01 -070010537 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010538 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010539
10540 if (mActiveTracks.size() == 1) {
10541 ret = exitStandby_l();
10542 }
10543
Eric Laurent6acd1d42017-01-04 14:23:29 -080010544 broadcast_l();
10545
Eric Laurentdda206a2022-07-08 17:28:35 +020010546 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010547
Eric Laurentdda206a2022-07-08 17:28:35 +020010548 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010549}
10550
Andy Hungee58e4a2023-07-07 13:47:37 -070010551status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010552{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010554 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010555
10556 if (mHalStream == 0) {
10557 return NO_INIT;
10558 }
10559
Eric Laurenta54f1282017-07-01 19:39:32 -070010560 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010561 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010562 return NO_ERROR;
10563 }
10564
Andy Hung8d31fd22023-06-26 19:20:57 -070010565 sp<IAfMmapTrack> track;
10566 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567 if (handle == t->portId()) {
10568 track = t;
10569 break;
10570 }
10571 }
10572 if (track == 0) {
10573 return BAD_VALUE;
10574 }
10575
10576 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010577 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578
Andy Hungc5007f82023-08-29 14:26:09 -070010579 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010580 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010581 AudioSystem::stopOutput(track->portId());
10582 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010584 AudioSystem::stopInput(track->portId());
10585 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010586 }
Andy Hungc5007f82023-08-29 14:26:09 -070010587 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588
Andy Hung116bc262023-06-20 18:56:17 -070010589 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010590 if (chain != 0) {
10591 chain->decActiveTrackCnt();
10592 chain->decTrackCnt();
10593 }
10594
Eric Laurentdda206a2022-07-08 17:28:35 +020010595 if (mActiveTracks.isEmpty()) {
10596 mHalStream->stop();
10597 }
10598
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599 broadcast_l();
10600
Eric Laurent6acd1d42017-01-04 14:23:29 -080010601 return NO_ERROR;
10602}
10603
Andy Hungee58e4a2023-07-07 13:47:37 -070010604status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010605NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010606{
10607 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010608 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010609
10610 if (mHalStream == 0) {
10611 return NO_INIT;
10612 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010613 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010614 return INVALID_OPERATION;
10615 }
10616 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010617 if (!mStandby) {
10618 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010619 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010620 mStandby = true;
10621 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010622 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010623 return NO_ERROR;
10624}
10625
Andy Hungee58e4a2023-07-07 13:47:37 -070010626status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010627 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10628 return INVALID_OPERATION;
10629}
10630
Andy Hungee58e4a2023-07-07 13:47:37 -070010631void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632{
10633 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10634 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10635 mFormat = mHALFormat;
10636 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10637 result = mHalStream->getFrameSize(&mFrameSize);
10638 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010639 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10640 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641 result = mHalStream->getBufferSize(&mBufferSize);
10642 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10643 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010644
Andy Hungcf10d742020-04-28 15:38:24 -070010645 // TODO: make a readHalParameters call?
10646 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010647 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010648 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010649 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10650 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10651 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10652 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10653 /*
10654 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10655 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10656 (int32_t)mHapticChannelMask)
10657 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10658 (int32_t)mHapticChannelCount)
10659 */
10660 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010661 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010662 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10663 (int32_t)mFrameCount) // sic - added HAL
10664 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010665}
10666
Andy Hungee58e4a2023-07-07 13:47:37 -070010667bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010668{
Andy Hungab65b182023-09-06 19:41:47 -070010669 {
10670 audio_utils::unique_lock _l(mutex());
10671 checkSilentMode_l();
10672 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010673
10674 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10675
10676 while (!exitPending())
10677 {
Andy Hung116bc262023-06-20 18:56:17 -070010678 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010679
Andy Hung13850be2019-03-14 11:33:09 -070010680 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010681 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010682
Eric Laurent6acd1d42017-01-04 14:23:29 -080010683 if (mSignalPending) {
10684 // A signal was raised while we were unlocked
10685 mSignalPending = false;
10686 } else {
10687 if (mConfigEvents.isEmpty()) {
10688 // we're about to wait, flush the binder command buffer
10689 IPCThreadState::self()->flushCommands();
10690
10691 if (exitPending()) {
10692 break;
10693 }
10694
Eric Laurent6acd1d42017-01-04 14:23:29 -080010695 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010696 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010697 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010698 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699
10700 checkSilentMode_l();
10701
10702 continue;
10703 }
10704 }
10705
10706 processConfigEvents_l();
10707
10708 processVolume_l();
10709
10710 checkInvalidTracks_l();
10711
Andy Hungab65b182023-09-06 19:41:47 -070010712 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010713
Kevin Rocard069c2712018-03-29 19:09:14 -070010714 updateMetadata_l();
10715
Eric Laurent6acd1d42017-01-04 14:23:29 -080010716 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010717 } // release Thread lock
10718
Eric Laurent6acd1d42017-01-04 14:23:29 -080010719 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010720 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010721 }
Andy Hung13850be2019-03-14 11:33:09 -070010722
10723 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010724 unlockEffectChains(effectChains);
10725 // Effect chains will be actually deleted here if they were removed from
10726 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010727 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010728 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010729 mThreadloopExecutor.process(); // process any remaining deferred actions.
10730 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010731
10732 threadLoop_exit();
10733
10734 if (!mStandby) {
10735 threadLoop_standby();
10736 mStandby = true;
10737 }
10738
Eric Laurent6acd1d42017-01-04 14:23:29 -080010739 ALOGV("Thread %p type %d exiting", this, mType);
10740 return false;
10741}
10742
Andy Hungc5007f82023-08-29 14:26:09 -070010743// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010744bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745 status_t& status)
10746{
10747 AudioParameter param = AudioParameter(keyValuePair);
10748 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010749 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010750 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010751 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010752 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010753 if (sendToHal) {
10754 status = mHalStream->setParameters(keyValuePair);
10755 } else {
10756 status = NO_ERROR;
10757 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010758
10759 return false;
10760}
10761
Andy Hungee58e4a2023-07-07 13:47:37 -070010762String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010763{
Andy Hung972bec12023-08-31 16:13:39 -070010764 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010765 String8 out_s8;
10766 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10767 return out_s8;
10768 }
Andy Hung920f6572022-10-06 12:09:49 -070010769 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010770}
10771
Andy Hungab65b182023-09-06 19:41:47 -070010772void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010773 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010774 sp<AudioIoDescriptor> desc;
10775 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776 switch (event) {
10777 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010778 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010779 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010780 isInput = true;
10781 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010782 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010783 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010784 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010785 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10786 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010788 case AUDIO_INPUT_CLOSED:
10789 case AUDIO_OUTPUT_CLOSED:
10790 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010791 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010792 break;
10793 }
Andy Hungab65b182023-09-06 19:41:47 -070010794 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795}
10796
Andy Hungee58e4a2023-07-07 13:47:37 -070010797status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010799NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010800{
10801 status_t status = NO_ERROR;
10802
10803 // store new device and send to effects
10804 audio_devices_t type = AUDIO_DEVICE_NONE;
10805 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010806 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10807 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10808 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010809 if (isOutput()) {
10810 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010811 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10812 && !mAudioHwDev->supportsAudioPatches(),
10813 "Enumerated device type(%#x) must not be used "
10814 "as it does not support audio patches",
10815 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010816 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010817 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10818 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819 }
10820 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010821 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010822 } else {
10823 type = patch->sources[0].ext.device.type;
10824 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010825 numDevices = mPatch.num_sources;
10826 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010827 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010828 }
10829
10830 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010831 if (isOutput()) {
10832 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10833 } else {
10834 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10835 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836 }
10837
jiabinc52b1ff2019-10-31 17:20:42 -070010838 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839 // store new source and send to effects
10840 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10841 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10842 for (size_t i = 0; i < mEffectChains.size(); i++) {
10843 mEffectChains[i]->setAudioSource_l(mAudioSource);
10844 }
10845 }
10846 }
10847
jiabin78b86f22024-02-22 00:39:29 +000010848 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10849 // okay to notify the client earlier before the new patch creation.
10850 if (mDeviceId != deviceId) {
10851 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10852 // The aaudioservice handle the routing changed event asynchronously. In that case,
10853 // it is safe to hold the lock here.
10854 callback->onRoutingChanged(deviceId);
10855 }
10856 }
10857
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010859 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10860 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010862 audio_port_config port;
10863 std::optional<audio_source_t> source;
10864 if (isOutput()) {
10865 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010867 port = patch->sources[0];
10868 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010869 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010870 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010871 *handle = AUDIO_PATCH_HANDLE_NONE;
10872 }
10873
jiabinc52b1ff2019-10-31 17:20:42 -070010874 if (numDevices == 0 || mDeviceId != deviceId) {
10875 if (isOutput()) {
10876 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10877 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010878 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010879 } else {
10880 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10881 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10882 }
jiabinc52b1ff2019-10-31 17:20:42 -070010883 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010884 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010885 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010886 // Force meteadata update after a route change
10887 mActiveTracks.setHasChanged();
10888
Eric Laurent6acd1d42017-01-04 14:23:29 -080010889 return status;
10890}
10891
Andy Hungee58e4a2023-07-07 13:47:37 -070010892status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010893{
10894 status_t status = NO_ERROR;
10895
jiabinc52b1ff2019-10-31 17:20:42 -070010896 mPatch = audio_patch{};
10897 mOutDeviceTypeAddrs.clear();
10898 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010899
10900 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10901 supportsAudioPatches : false;
10902
10903 if (supportsAudioPatches) {
10904 status = mHalDevice->releaseAudioPatch(handle);
10905 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010906 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010907 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010908 // Force meteadata update after a route change
10909 mActiveTracks.setHasChanged();
10910
Eric Laurent6acd1d42017-01-04 14:23:29 -080010911 return status;
10912}
10913
Andy Hungee58e4a2023-07-07 13:47:37 -070010914void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010915NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010916{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010917 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010918 if (isOutput()) {
10919 config->role = AUDIO_PORT_ROLE_SOURCE;
10920 config->ext.mix.hw_module = mAudioHwDev->handle();
10921 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10922 } else {
10923 config->role = AUDIO_PORT_ROLE_SINK;
10924 config->ext.mix.hw_module = mAudioHwDev->handle();
10925 config->ext.mix.usecase.source = mAudioSource;
10926 }
10927}
10928
Andy Hungee58e4a2023-07-07 13:47:37 -070010929status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010930{
10931 audio_session_t session = chain->sessionId();
10932
10933 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10934 // Attach all tracks with same session ID to this chain.
10935 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010936 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937 if (session == track->sessionId()) {
10938 chain->incTrackCnt();
10939 chain->incActiveTrackCnt();
10940 }
10941 }
10942
10943 chain->setThread(this);
10944 chain->setInBuffer(nullptr);
10945 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010946 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010947
10948 mEffectChains.add(chain);
10949 checkSuspendOnAddEffectChain_l(chain);
10950 return NO_ERROR;
10951}
10952
Andy Hungee58e4a2023-07-07 13:47:37 -070010953size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954{
10955 audio_session_t session = chain->sessionId();
10956
10957 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10958
10959 for (size_t i = 0; i < mEffectChains.size(); i++) {
10960 if (chain == mEffectChains[i]) {
10961 mEffectChains.removeAt(i);
10962 // detach all active tracks from the chain
10963 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010964 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010965 if (session == track->sessionId()) {
10966 chain->decActiveTrackCnt();
10967 chain->decTrackCnt();
10968 }
10969 }
10970 break;
10971 }
10972 }
10973 return mEffectChains.size();
10974}
10975
Andy Hungee58e4a2023-07-07 13:47:37 -070010976void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010977{
10978 mHalStream->standby();
10979}
10980
Andy Hungee58e4a2023-07-07 13:47:37 -070010981void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010982{
Phil Burk7dce7282017-09-27 13:51:41 -070010983 // Do not call callback->onTearDown() because it is redundant for thread exit
10984 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010985}
10986
Andy Hungee58e4a2023-07-07 13:47:37 -070010987status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010988{
10989 return BAD_VALUE;
10990}
10991
Andy Hungee58e4a2023-07-07 13:47:37 -070010992bool MmapThread::isValidSyncEvent(
10993 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010994{
10995 return false;
10996}
10997
Andy Hungee58e4a2023-07-07 13:47:37 -070010998status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010999 const effect_descriptor_t *desc, audio_session_t sessionId)
11000{
11001 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080011002 if (audio_is_global_session(sessionId)) {
11003 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080011004 desc->name, mThreadName);
11005 return BAD_VALUE;
11006 }
11007
11008 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11009 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11010 desc->name);
11011 return BAD_VALUE;
11012 }
11013 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011014 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11015 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011016 return BAD_VALUE;
11017 }
11018
11019 // Only allow effects without processing load or latency
11020 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11021 return BAD_VALUE;
11022 }
11023
Andy Hung116bc262023-06-20 18:56:17 -070011024 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011025 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11026 return BAD_VALUE;
11027 }
11028
Eric Laurent6acd1d42017-01-04 14:23:29 -080011029 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011030}
11031
Andy Hungee58e4a2023-07-07 13:47:37 -070011032void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033{
Andy Hung8d31fd22023-06-26 19:20:57 -070011034 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011035 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011036 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11037 // The aaudioservice handle the routing changed event asynchronously. In that case,
11038 // it is safe to hold the lock here.
11039 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
11040 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011041 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11042 mNoCallbackWarningCount++;
11043 }
11044 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045 }
11046 }
11047}
11048
Andy Hungee58e4a2023-07-07 13:47:37 -070011049void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011050{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11052 mAttr.content_type, mAttr.usage, mAttr.source);
11053 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011054 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011055 dprintf(fd, " No active clients\n");
11056 }
11057}
11058
Andy Hungee58e4a2023-07-07 13:47:37 -070011059void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011060{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011061 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011062 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011063 dprintf(fd, " %zu Tracks\n", numtracks);
11064 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011065 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011066 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011067 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011068 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011069 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011070 result.append(prefix);
11071 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011072 }
11073 } else {
11074 dprintf(fd, "\n");
11075 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011076 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077}
11078
Andy Hungee58e4a2023-07-07 13:47:37 -070011079/* static */
11080sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011081 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011082 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011083 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011084}
11085
11086MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011087 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011088 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011089 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011090 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011091 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092{
11093 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11094 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011095 mMasterVolume = afThreadCallback->masterVolume_l();
11096 mMasterMute = afThreadCallback->masterMute_l();
Andy Hung6b137d12024-08-27 22:35:17 +000011097 if (!audioserver_flags::portid_volume_management()) {
11098 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11099 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11100 mStreamTypes[stream].volume = 0.0f;
11101 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11102 }
11103 // Audio patch and call assistant volume are always max
11104 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11105 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11106 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11107 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011108 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011109 if (mAudioHwDev) {
11110 if (mAudioHwDev->canSetMasterVolume()) {
11111 mMasterVolume = 1.0;
11112 }
11113
11114 if (mAudioHwDev->canSetMasterMute()) {
11115 mMasterMute = false;
11116 }
11117 }
11118}
11119
Andy Hungee58e4a2023-07-07 13:47:37 -070011120void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011121 audio_stream_type_t streamType,
11122 audio_session_t sessionId,
11123 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011124 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011125 audio_port_handle_t portId)
11126{
Andy Hung8d672e02023-09-15 18:19:28 -070011127 audio_utils::lock_guard l(mutex());
11128 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011129 mStreamType = streamType;
11130}
11131
Andy Hungee58e4a2023-07-07 13:47:37 -070011132AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011133{
Andy Hung972bec12023-08-31 16:13:39 -070011134 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011135 AudioStreamOut *output = mOutput;
11136 mOutput = NULL;
11137 return output;
11138}
11139
Andy Hungee58e4a2023-07-07 13:47:37 -070011140void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011141{
Andy Hung972bec12023-08-31 16:13:39 -070011142 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011143 // Don't apply master volume in SW if our HAL can do it for us.
11144 if (mAudioHwDev &&
11145 mAudioHwDev->canSetMasterVolume()) {
11146 mMasterVolume = 1.0;
11147 } else {
11148 mMasterVolume = value;
11149 }
11150}
11151
Andy Hungee58e4a2023-07-07 13:47:37 -070011152void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011153{
Andy Hung972bec12023-08-31 16:13:39 -070011154 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011155 // Don't apply master mute in SW if our HAL can do it for us.
11156 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11157 mMasterMute = false;
11158 } else {
11159 mMasterMute = muted;
11160 }
11161}
11162
Andy Hungee58e4a2023-07-07 13:47:37 -070011163void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011164{
Andy Hung972bec12023-08-31 16:13:39 -070011165 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011166 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011167 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011168 broadcast_l();
11169 }
11170}
11171
Andy Hungee58e4a2023-07-07 13:47:37 -070011172float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011173{
Andy Hung972bec12023-08-31 16:13:39 -070011174 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011175 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011176}
11177
Andy Hungee58e4a2023-07-07 13:47:37 -070011178void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011179{
Andy Hung972bec12023-08-31 16:13:39 -070011180 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011181 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011182 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011183 broadcast_l();
11184 }
11185}
11186
Andy Hung6b137d12024-08-27 22:35:17 +000011187status_t MmapPlaybackThread::setPortsVolume(
11188 const std::vector<audio_port_handle_t>& portIds, float volume) {
11189 audio_utils::lock_guard _l(mutex());
11190 for (const auto& portId : portIds) {
11191 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11192 if (portId == track->portId()) {
11193 track->setPortVolume(volume);
11194 break;
11195 }
11196 }
11197 }
11198 broadcast_l();
11199 return NO_ERROR;
11200}
11201
Andy Hungee58e4a2023-07-07 13:47:37 -070011202void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011203{
Andy Hung972bec12023-08-31 16:13:39 -070011204 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011205 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011206 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011207 track->invalidate();
11208 }
11209 broadcast_l();
11210 }
11211}
11212
Andy Hungee58e4a2023-07-07 13:47:37 -070011213void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011214{
Andy Hung972bec12023-08-31 16:13:39 -070011215 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011216 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011217 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011218 if (portIds.find(track->portId()) != portIds.end()) {
11219 track->invalidate();
11220 trackMatch = true;
11221 portIds.erase(track->portId());
11222 }
11223 if (portIds.empty()) {
11224 break;
11225 }
11226 }
11227 if (trackMatch) {
11228 broadcast_l();
11229 }
11230}
11231
Andy Hungee58e4a2023-07-07 13:47:37 -070011232void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011233NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011234{
Andy Hung6b137d12024-08-27 22:35:17 +000011235 float volume = 0;
11236 if (!audioserver_flags::portid_volume_management()) {
11237 if (mMasterMute || streamMuted_l()) {
11238 volume = 0;
11239 } else {
11240 volume = mMasterVolume * streamVolume_l();
11241 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011242 } else {
Andy Hung6b137d12024-08-27 22:35:17 +000011243 if (mMasterMute) {
11244 volume = 0;
11245 } else {
11246 // All mmap tracks are declared with the same audio attributes to the audio policy
11247 // manager. Hence, they follow the same routing / volume group. Any change of volume
11248 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11249 size_t numtracks = mActiveTracks.size();
11250 if (numtracks) {
11251 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11252 }
11253 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011254 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011255 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011256 // Convert volumes from float to 8.24
11257 uint32_t vol = (uint32_t)(volume * (1 << 24));
11258
11259 // Delegate volume control to effect in track effect chain if needed
11260 // only one effect chain can be present on DirectOutputThread, so if
11261 // there is one, the track is connected to it
11262 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011263 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011264 volume = (float)vol / (1 << 24);
11265 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011266 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011267 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11268 mHalVolFloat = volume; // HW volume control worked, so update value.
11269 mNoCallbackWarningCount = 0;
11270 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011271 sp<MmapStreamCallback> callback = mCallback.promote();
11272 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011273 mHalVolFloat = volume; // SW volume control worked, so update value.
11274 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011275 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011276 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011277 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011278 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011279 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11280 ALOGW("Could not set MMAP stream volume: no volume callback!");
11281 mNoCallbackWarningCount++;
11282 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011283 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011284 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011285 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011286 track->setMetadataHasChanged();
Andy Hung6b137d12024-08-27 22:35:17 +000011287 if (!audioserver_flags::portid_volume_management()) {
11288 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11289 /*muteState=*/{mMasterMute,
11290 streamVolume_l() == 0.f,
11291 streamMuted_l(),
11292 // TODO(b/241533526): adjust logic to include mute from AppOps
11293 false /*muteFromPlaybackRestricted*/,
11294 false /*muteFromClientVolume*/,
11295 false /*muteFromVolumeShaper*/});
11296 } else {
11297 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11298 /*muteState=*/{mMasterMute,
11299 track->getPortVolume() == 0.f,
11300 /* muteFromStreamMuted= */ false,
11301 // TODO(b/241533526): adjust logic to include mute from AppOps
11302 false /*muteFromPlaybackRestricted*/,
11303 false /*muteFromClientVolume*/,
11304 false /*muteFromVolumeShaper*/});
11305 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011306 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011307 }
11308}
11309
Andy Hungee58e4a2023-07-07 13:47:37 -070011310ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011311{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011312 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011313 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011314 }
11315 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011316 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011317 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011318 playback_track_metadata_v7_t trackMetadata;
11319 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011320 .usage = track->attributes().usage,
11321 .content_type = track->attributes().content_type,
11322 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011323 };
11324 trackMetadata.channel_mask = track->channelMask(),
11325 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11326 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011327 }
11328 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011329
11330 MetadataUpdate change;
11331 change.playbackMetadataUpdate = metadata.tracks;
11332 return change;
11333};
Kevin Rocard069c2712018-03-29 19:09:14 -070011334
Andy Hungee58e4a2023-07-07 13:47:37 -070011335void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011336{
11337 if (!mMasterMute) {
11338 char value[PROPERTY_VALUE_MAX];
11339 if (property_get("ro.audio.silent", value, "0") > 0) {
11340 char *endptr;
11341 unsigned long ul = strtoul(value, &endptr, 0);
11342 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011343 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011344 // The setprop command will not allow a property to be changed after
11345 // the first time it is set, so we don't have to worry about un-muting.
11346 setMasterMute_l(true);
11347 }
11348 }
11349 }
11350}
11351
Andy Hungee58e4a2023-07-07 13:47:37 -070011352void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011353{
11354 MmapThread::toAudioPortConfig(config);
11355 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11356 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11357 config->flags.output = mOutput->flags;
11358 }
11359}
11360
Andy Hungee58e4a2023-07-07 13:47:37 -070011361status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011362 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011363{
11364 if (mOutput == nullptr) {
11365 return NO_INIT;
11366 }
11367 struct timespec timestamp;
11368 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11369 if (status == NO_ERROR) {
11370 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11371 }
11372 return status;
11373}
11374
Andy Hungee58e4a2023-07-07 13:47:37 -070011375status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011376 // Send to MelProcessor for sound dose measurement.
11377 auto processor = mMelProcessor.load();
11378 if (processor) {
11379 processor->process(buffer, frameCount * mFrameSize);
11380 }
11381
jiabinfc791ee2023-02-15 19:43:40 +000011382 return NO_ERROR;
11383}
11384
Andy Hungc5007f82023-08-29 14:26:09 -070011385// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011386void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011387 const sp<audio_utils::MelProcessor>& processor)
11388{
11389 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011390 mMelProcessor.store(processor);
11391 if (processor) {
11392 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011393 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011394
11395 // no need to update output format for MMapPlaybackThread since it is
11396 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011397}
11398
Andy Hungc5007f82023-08-29 14:26:09 -070011399// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011400void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011401{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011402 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11403 auto melProcessor = mMelProcessor.load();
11404 if (melProcessor != nullptr) {
11405 melProcessor->pause();
11406 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011407}
11408
Andy Hungee58e4a2023-07-07 13:47:37 -070011409void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011410{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011411 MmapThread::dumpInternals_l(fd, args);
Andy Hung6b137d12024-08-27 22:35:17 +000011412 if (!audioserver_flags::portid_volume_management()) {
11413 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11414 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11415 } else {
11416 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11417 }
11418 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011419 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11420}
11421
Andy Hungee58e4a2023-07-07 13:47:37 -070011422/* static */
11423sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011424 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011425 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011426 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011427}
11428
11429MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011430 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011431 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011432 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011433 mInput(input)
11434{
11435 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11436 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11437}
11438
Andy Hungee58e4a2023-07-07 13:47:37 -070011439status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011440{
Phil Burkf054fc32018-12-06 09:45:59 -080011441 {
11442 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011443 if (mInput != nullptr && mInput->stream != nullptr) {
11444 mInput->stream->setGain(1.0f);
11445 }
11446 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011447 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011448}
11449
Andy Hungee58e4a2023-07-07 13:47:37 -070011450AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011451{
Andy Hung972bec12023-08-31 16:13:39 -070011452 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011453 AudioStreamIn *input = mInput;
11454 mInput = NULL;
11455 return input;
11456}
Kevin Rocard069c2712018-03-29 19:09:14 -070011457
Andy Hungee58e4a2023-07-07 13:47:37 -070011458void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011459{
11460 bool changed = false;
11461 bool silenced = false;
11462
11463 sp<MmapStreamCallback> callback = mCallback.promote();
11464 if (callback == 0) {
11465 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11466 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11467 mNoCallbackWarningCount++;
11468 }
11469 }
11470
11471 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11472 // track is silenced and unmute otherwise
11473 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11474 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11475 changed = true;
11476 silenced = mActiveTracks[i]->isSilenced_l();
11477 }
11478 }
11479
11480 if (changed) {
11481 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11482 }
11483}
11484
Andy Hungee58e4a2023-07-07 13:47:37 -070011485ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011486{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011487 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011488 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011489 }
11490 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011491 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011492 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011493 record_track_metadata_v7_t trackMetadata;
11494 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011495 .source = track->attributes().source,
11496 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011497 };
11498 trackMetadata.channel_mask = track->channelMask(),
11499 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11500 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011501 }
11502 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011503 MetadataUpdate change;
11504 change.recordMetadataUpdate = metadata.tracks;
11505 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011506}
11507
Andy Hungee58e4a2023-07-07 13:47:37 -070011508void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011509{
Andy Hung972bec12023-08-31 16:13:39 -070011510 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011511 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011512 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011513 mActiveTracks[i]->setSilenced_l(silenced);
11514 broadcast_l();
11515 }
11516 }
jiabin09609032022-06-15 19:26:01 +000011517 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011518}
11519
Andy Hungee58e4a2023-07-07 13:47:37 -070011520void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011521{
11522 MmapThread::toAudioPortConfig(config);
11523 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11524 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11525 config->flags.input = mInput->flags;
11526 }
11527}
11528
Andy Hungee58e4a2023-07-07 13:47:37 -070011529status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011530 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011531{
11532 if (mInput == nullptr) {
11533 return NO_INIT;
11534 }
11535 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11536}
11537
jiabinc658e452022-10-21 20:52:21 +000011538// ----------------------------------------------------------------------------
11539
Andy Hungee58e4a2023-07-07 13:47:37 -070011540/* static */
11541sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011542 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011543 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011544 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011545}
11546
Andy Hung583043b2023-07-17 17:05:00 -070011547BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011548 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011549 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011550
Andy Hungee58e4a2023-07-07 13:47:37 -070011551PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011552 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011553 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11554 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011555 float volumeLeft = 1.0f;
11556 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011557 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11558 bitPerfectTrack != nullptr) {
11559 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011560 mAudioMixer->setParameter(
11561 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11562 mAudioMixer->setParameter(
11563 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11564 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011565 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011566 mIsBitPerfect = true;
11567 } else {
11568 mIsBitPerfect = false;
11569 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11570 // active.
11571 for (const auto& track : mActiveTracks) {
11572 const int trackId = track->id();
11573 mAudioMixer->setParameter(
11574 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11575 }
11576 }
jiabin76d94692022-12-15 21:51:21 +000011577 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11578 mVolumeLeft = volumeLeft;
11579 mVolumeRight = volumeRight;
11580 setVolumeForOutput_l(volumeLeft, volumeRight);
11581 }
jiabinc658e452022-10-21 20:52:21 +000011582 return result;
11583}
11584
Andy Hungee58e4a2023-07-07 13:47:37 -070011585void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011586 MixerThread::threadLoop_mix();
11587 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11588}
11589
jiabin220eea12024-05-17 17:55:20 +000011590void BitPerfectThread::setTracksInternalMute(
11591 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11592 for (auto& track : mTracks) {
11593 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11594 track->setInternalMute(it->second);
11595 tracksInternalMute->erase(it);
11596 }
11597 }
11598}
11599
11600sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11601 if (com::android::media::audioserver::
11602 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11603 sp<IAfTrack> bitPerfectTrack = nullptr;
11604 bool allOtherTracksMuted = true;
11605 // Return the bit perfect track if all other tracks are muted
11606 for (const auto& track : mActiveTracks) {
11607 if (track->isBitPerfect()) {
11608 bitPerfectTrack = track;
11609 } else if (track->getFinalVolume() != 0.f) {
11610 allOtherTracksMuted = false;
11611 if (bitPerfectTrack != nullptr) {
11612 break;
11613 }
11614 }
11615 }
11616 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11617 } else {
11618 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11619 return mActiveTracks[0];
11620 }
11621 }
11622 return nullptr;
11623}
11624
Glenn Kasten63238ef2015-03-02 15:50:29 -080011625} // namespace android