blob: e42b39e55f784adf2b6f6f022cb028f1230ecd27 [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
Atneya Nairf94040f2024-10-07 16:00:49 -070030#include <afutils/FallibleLockGuard.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070031#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>
Andy Hung88a7afe2024-08-12 20:00:46 -070084#include <psh_utils/AudioPowerManager.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070085#include <system/audio_effects/effect_aec.h>
86#include <system/audio_effects/effect_downmix.h>
87#include <system/audio_effects/effect_ns.h>
88#include <system/audio_effects/effect_spatializer.h>
89#include <utils/Log.h>
90#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080091
Andy Hung25a80ac2023-07-19 12:47:35 -070092#include <fcntl.h>
93#include <linux/futex.h>
94#include <math.h>
95#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070097#include <sstream>
98#include <string>
99#include <sys/stat.h>
100#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -0800101
Eric Laurent81784c32012-11-19 14:55:58 -0800102// ----------------------------------------------------------------------------
103
104// Note: the following macro is used for extremely verbose logging message. In
105// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
106// 0; but one side effect of this is to turn all LOGV's as well. Some messages
107// are so verbose that we want to suppress them even when we have ALOG_ASSERT
108// turned on. Do not uncomment the #def below unless you really know what you
109// are doing and want to see all of the extremely verbose messages.
110//#define VERY_VERY_VERBOSE_LOGGING
111#ifdef VERY_VERY_VERBOSE_LOGGING
112#define ALOGVV ALOGV
113#else
114#define ALOGVV(a...) do { } while(0)
115#endif
116
Andy Hung6770c6f2015-04-07 13:43:36 -0700117// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700118#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700119
Andy Hung6770c6f2015-04-07 13:43:36 -0700120template <typename T>
121static inline T min(const T& a, const T& b)
122{
123 return a < b ? a : b;
124}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700125
Atneya Nair5997a652024-06-14 17:24:45 -0700126using com::android::media::permission::ValidatedAttributionSourceState;
Andy Hung6b137d12024-08-27 22:35:17 +0000127namespace audioserver_flags = com::android::media::audioserver;
Atneya Nair5997a652024-06-14 17:24:45 -0700128
Eric Laurent81784c32012-11-19 14:55:58 -0800129namespace android {
130
Andy Hungee58e4a2023-07-07 13:47:37 -0700131using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700132using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000133using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700134
Andy Hung25a80ac2023-07-19 12:47:35 -0700135// Keep in sync with java definition in media/java/android/media/AudioRecord.java
136static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
137
Eric Laurent81784c32012-11-19 14:55:58 -0800138// retry counts for buffer fill timeout
139// 50 * ~20msecs = 1 second
140static const int8_t kMaxTrackRetries = 50;
141static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700142
Eric Laurent81784c32012-11-19 14:55:58 -0800143// allow less retry attempts on direct output thread.
144// direct outputs can be a scarce resource in audio hardware and should
145// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700146// Notes:
147// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
148// in case the data write is bursty for the AudioTrack. The application
149// should endeavor to write at least once every kMaxTrackRetriesDirectMs
150// to prevent an underrun situation. If the data is bursty, then
151// the application can also throttle the data sent to be even.
152// 2) For compressed audio data, any data present in the AudioTrack buffer
153// will be sent and reset the retry count. This delivers data as
154// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
155// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
156// of data to be available, then any remaining data is delivered.
157// This is required to ensure the last bit of data is delivered before underrun.
158//
159// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
160// or the size of the HAL period for proportional / linear PCM tracks.
161static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800162
163// don't warn about blocked writes or record buffer overflows more often than this
164static const nsecs_t kWarningThrottleNs = seconds(5);
165
166// RecordThread loop sleep time upon application overrun or audio HAL read error
167static const int kRecordThreadSleepUs = 5000;
168
Eric Laurent10351942014-05-08 18:49:52 -0700169// maximum time to wait in sendConfigEvent_l() for a status to be received
170static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent3fddffe2024-07-31 14:18:34 +0000171// longer timeout for create audio patch to account for specific scenarii
172// with Bluetooth devices
173static const nsecs_t kCreatePatchEventTimeoutNs = seconds(4);
Eric Laurent81784c32012-11-19 14:55:58 -0800174
175// minimum sleep time for the mixer thread loop when tracks are active but in underrun
176static const uint32_t kMinThreadSleepTimeUs = 5000;
177// maximum divider applied to the active sleep time in the mixer thread loop
178static const uint32_t kMaxThreadSleepTimeShift = 2;
179
Andy Hung09a50072014-02-27 14:30:47 -0800180// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700181// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800182static const uint32_t kMinNormalSinkBufferSizeMs = 20;
183// maximum normal sink buffer size
184static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800185
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700186// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
187// FIXME This should be based on experimentally observed scheduling jitter
188static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
189
Eric Laurent972a1732013-09-04 09:42:59 -0700190// Offloaded output thread standby delay: allows track transition without going to standby
191static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
192
Eric Laurent51716182016-02-29 18:00:56 -0800193// Direct output thread minimum sleep time in idle or active(underrun) state
194static const nsecs_t kDirectMinSleepTimeUs = 10000;
195
Brian Lindahl65e90012022-07-27 18:01:07 +0200196// Minimum amount of time between checking to see if the timestamp is advancing
197// for underrun detection. If we check too frequently, we may not detect a
198// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800199static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200200
Glenn Kasten1b291842016-07-18 14:55:21 -0700201// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
202// balance between power consumption and latency, and allows threads to be scheduled reliably
203// by the CFS scheduler.
204// FIXME Express other hardcoded references to 20ms with references to this constant and move
205// it appropriately.
206#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800207
Eric Laurent81784c32012-11-19 14:55:58 -0800208// Whether to use fast mixer
209static const enum {
210 FastMixer_Never, // never initialize or use: for debugging only
211 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
212 // normal mixer multiplier is 1
213 FastMixer_Static, // initialize if needed, then use all the time if initialized,
214 // multiplier is calculated based on min & max normal mixer buffer size
215 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
216 // multiplier is calculated based on min & max normal mixer buffer size
217 // FIXME for FastMixer_Dynamic:
218 // Supporting this option will require fixing HALs that can't handle large writes.
219 // For example, one HAL implementation returns an error from a large write,
220 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
221 // We could either fix the HAL implementations, or provide a wrapper that breaks
222 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
223} kUseFastMixer = FastMixer_Static;
224
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700225// Whether to use fast capture
226static const enum {
227 FastCapture_Never, // never initialize or use: for debugging only
228 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
229 FastCapture_Static, // initialize if needed, then use all the time if initialized
230} kUseFastCapture = FastCapture_Static;
231
Eric Laurent81784c32012-11-19 14:55:58 -0800232// Priorities for requestPriority
233static const int kPriorityAudioApp = 2;
234static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700235static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000236// Request real-time priority for PlaybackThread in ARC
237static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800238
Glenn Kastenea38ee72016-04-18 11:08:01 -0700239// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
240// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
241// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700242
243// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800244static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800245
Glenn Kasten03490092014-05-27 12:30:54 -0700246// The minimum and maximum allowed values
247static const int kFastTrackMultiplierMin = 1;
248static const int kFastTrackMultiplierMax = 2;
249
250// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
251static int sFastTrackMultiplier = kFastTrackMultiplier;
252
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700253// See Thread::readOnlyHeap().
254// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
255// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
256// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700257static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700258
Andy Hung25a80ac2023-07-19 12:47:35 -0700259static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700260
261static nsecs_t getStandbyTimeInNanos() {
262 static nsecs_t standbyTimeInNanos = []() {
263 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
264 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
265 ALOGI("%s: Using %d ms as standby time", __func__, ms);
266 return milliseconds(ms);
267 }();
268 return standbyTimeInNanos;
269}
270
Andy Hung81994d62023-07-20 21:44:14 -0700271// Set kEnableExtendedChannels to true to enable greater than stereo output
272// for the MixerThread and device sink. Number of channels allowed is
273// FCC_2 <= channels <= FCC_LIMIT.
274constexpr bool kEnableExtendedChannels = true;
275
276// Returns true if channel mask is permitted for the PCM sink in the MixerThread
277/* static */
278bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
279 switch (audio_channel_mask_get_representation(channelMask)) {
280 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
281 // Haptic channel mask is only applicable for channel position mask.
282 const uint32_t channelCount = audio_channel_count_from_out_mask(
283 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
284 const uint32_t maxChannelCount = kEnableExtendedChannels
285 ? FCC_LIMIT : FCC_2;
286 if (channelCount < FCC_2 // mono is not supported at this time
287 || channelCount > maxChannelCount) {
288 return false;
289 }
290 // check that channelMask is the "canonical" one we expect for the channelCount.
291 return audio_channel_position_mask_is_out_canonical(channelMask);
292 }
293 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
294 if (kEnableExtendedChannels) {
295 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
296 if (channelCount >= FCC_2 // mono is not supported at this time
297 && channelCount <= FCC_LIMIT) {
298 return true;
299 }
300 }
301 return false;
302 default:
303 return false;
304 }
305}
306
307// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
308constexpr bool kEnableExtendedPrecision = true;
309
310// Returns true if format is permitted for the PCM sink in the MixerThread
311/* static */
312bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
313 switch (format) {
314 case AUDIO_FORMAT_PCM_16_BIT:
315 return true;
316 case AUDIO_FORMAT_PCM_FLOAT:
317 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
318 case AUDIO_FORMAT_PCM_32_BIT:
319 case AUDIO_FORMAT_PCM_8_24_BIT:
320 return kEnableExtendedPrecision;
321 default:
322 return false;
323 }
324}
325
Eric Laurent81784c32012-11-19 14:55:58 -0800326// ----------------------------------------------------------------------------
327
Andy Hung25a80ac2023-07-19 12:47:35 -0700328// formatToString() needs to be exact for MediaMetrics purposes.
329// Do not use media/TypeConverter.h toString().
330/* static */
331std::string IAfThreadBase::formatToString(audio_format_t format) {
332 std::string result;
333 FormatConverter::toString(format, result);
334 return result;
335}
336
Andy Hungb68f5eb2019-12-03 16:49:17 -0800337// TODO: move all toString helpers to audio.h
338// under #ifdef __cplusplus #endif
339static std::string patchSinksToString(const struct audio_patch *patch)
340{
Andy Hungc04a8202024-11-01 17:38:06 -0700341 std::string s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800342 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc04a8202024-11-01 17:38:06 -0700343 if (i > 0) s.append("|");
344 if (patch->sinks[i].ext.device.address[0]) {
345 s.append("(").append(toString(patch->sinks[i].ext.device.type))
346 .append(", ").append(patch->sinks[i].ext.device.address).append(")");
347 } else {
348 s.append(toString(patch->sinks[i].ext.device.type));
Andy Hungc2b11cb2020-04-22 09:04:01 -0700349 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800350 }
Andy Hungc04a8202024-11-01 17:38:06 -0700351 return s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800352}
353
354static std::string patchSourcesToString(const struct audio_patch *patch)
355{
Andy Hungc04a8202024-11-01 17:38:06 -0700356 std::string s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800357 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc04a8202024-11-01 17:38:06 -0700358 if (i > 0) s.append("|");
359 if (patch->sources[i].ext.device.address[0]) {
360 s.append("(").append(toString(patch->sources[i].ext.device.type))
361 .append(", ").append(patch->sources[i].ext.device.address).append(")");
362 } else {
363 s.append(toString(patch->sources[i].ext.device.type));
Andy Hungc2b11cb2020-04-22 09:04:01 -0700364 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800365 }
Andy Hungc04a8202024-11-01 17:38:06 -0700366 return s;
Andy Hungb68f5eb2019-12-03 16:49:17 -0800367}
368
Andy Hung4bd53e72022-11-17 17:21:45 -0800369static std::string toString(audio_latency_mode_t mode) {
370 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000371 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
372 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800373}
374
375// Could be made a template, but other toString overloads for std::vector are confused.
376static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
377 std::string s("{ ");
378 for (const auto& e : elements) {
379 s.append(toString(e));
380 s.append(" ");
381 }
382 s.append("}");
383 return s;
384}
385
Glenn Kasten03490092014-05-27 12:30:54 -0700386static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
387
388static void sFastTrackMultiplierInit()
389{
390 char value[PROPERTY_VALUE_MAX];
391 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
392 char *endptr;
393 unsigned long ul = strtoul(value, &endptr, 0);
394 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
395 sFastTrackMultiplier = (int) ul;
396 }
397 }
398}
399
400// ----------------------------------------------------------------------------
401
Eric Laurent81784c32012-11-19 14:55:58 -0800402#ifdef ADD_BATTERY_DATA
403// To collect the amplifier usage
404static void addBatteryData(uint32_t params) {
405 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
406 if (service == NULL) {
407 // it already logged
408 return;
409 }
410
411 service->addBatteryData(params);
412}
413#endif
414
Andy Hung3f0c9022016-01-15 17:49:46 -0800415// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
416struct {
417 // call when you acquire a partial wakelock
418 void acquire(const sp<IBinder> &wakeLockToken) {
419 pthread_mutex_lock(&mLock);
420 if (wakeLockToken.get() == nullptr) {
421 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
422 } else {
423 if (mCount == 0) {
424 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
425 }
426 ++mCount;
427 }
428 pthread_mutex_unlock(&mLock);
429 }
430
431 // call when you release a partial wakelock.
432 void release(const sp<IBinder> &wakeLockToken) {
433 if (wakeLockToken.get() == nullptr) {
434 return;
435 }
436 pthread_mutex_lock(&mLock);
437 if (--mCount < 0) {
438 ALOGE("negative wakelock count");
439 mCount = 0;
440 }
441 pthread_mutex_unlock(&mLock);
442 }
443
444 // retrieves the boottime timebase offset from monotonic.
445 int64_t getBoottimeOffset() {
446 pthread_mutex_lock(&mLock);
447 int64_t boottimeOffset = mBoottimeOffset;
448 pthread_mutex_unlock(&mLock);
449 return boottimeOffset;
450 }
451
452 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
453 // and the selected timebase.
454 // Currently only TIMEBASE_BOOTTIME is allowed.
455 //
456 // This only needs to be called upon acquiring the first partial wakelock
457 // after all other partial wakelocks are released.
458 //
459 // We do an empirical measurement of the offset rather than parsing
460 // /proc/timer_list since the latter is not a formal kernel ABI.
461 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
462 int clockbase;
463 switch (timebase) {
464 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
465 clockbase = SYSTEM_TIME_BOOTTIME;
466 break;
467 default:
468 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
469 break;
470 }
471 // try three times to get the clock offset, choose the one
472 // with the minimum gap in measurements.
473 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700474 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800475 for (int i = 0; i < tries; ++i) {
476 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
477 const nsecs_t tbase = systemTime(clockbase);
478 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
479 const nsecs_t gap = tmono2 - tmono;
480 if (i == 0 || gap < bestGap) {
481 bestGap = gap;
482 measured = tbase - ((tmono + tmono2) >> 1);
483 }
484 }
485
486 // to avoid micro-adjusting, we don't change the timebase
487 // unless it is significantly different.
488 //
489 // Assumption: It probably takes more than toleranceNs to
490 // suspend and resume the device.
491 static int64_t toleranceNs = 10000; // 10 us
492 if (llabs(*offset - measured) > toleranceNs) {
493 ALOGV("Adjusting timebase offset old: %lld new: %lld",
494 (long long)*offset, (long long)measured);
495 *offset = measured;
496 }
497 }
498
499 pthread_mutex_t mLock;
500 int32_t mCount;
501 int64_t mBoottimeOffset;
502} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800503
504// ----------------------------------------------------------------------------
505// CPU Stats
506// ----------------------------------------------------------------------------
507
508class CpuStats {
509public:
510 CpuStats();
511 void sample(const String8 &title);
512#ifdef DEBUG_CPU_USAGE
513private:
514 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700515 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800516
Andy Hung16698b82018-08-01 10:48:38 -0700517 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800518
519 int mCpuNum; // thread's current CPU number
520 int mCpukHz; // frequency of thread's current CPU in kHz
521#endif
522};
523
524CpuStats::CpuStats()
525#ifdef DEBUG_CPU_USAGE
526 : mCpuNum(-1), mCpukHz(-1)
527#endif
528{
529}
530
Glenn Kasten0f11b512014-01-31 16:18:54 -0800531void CpuStats::sample(const String8 &title
532#ifndef DEBUG_CPU_USAGE
533 __unused
534#endif
535 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800536#ifdef DEBUG_CPU_USAGE
537 // get current thread's delta CPU time in wall clock ns
538 double wcNs;
539 bool valid = mCpuUsage.sampleAndEnable(wcNs);
540
541 // record sample for wall clock statistics
542 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700543 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800544 }
545
546 // get the current CPU number
547 int cpuNum = sched_getcpu();
548
549 // get the current CPU frequency in kHz
550 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
551
552 // check if either CPU number or frequency changed
553 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
554 mCpuNum = cpuNum;
555 mCpukHz = cpukHz;
556 // ignore sample for purposes of cycles
557 valid = false;
558 }
559
560 // if no change in CPU number or frequency, then record sample for cycle statistics
561 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700562 const double cycles = wcNs * cpukHz * 0.000001;
563 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800564 }
565
Eric Tan5b13ff82018-07-27 11:20:17 -0700566 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800567 // mCpuUsage.elapsed() is expensive, so don't call it every loop
568 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700569 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800570 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700571 const double perLoop = elapsed / (double) n;
572 const double perLoop100 = perLoop * 0.01;
573 const double perLoop1k = perLoop * 0.001;
574 const double mean = mWcStats.getMean();
575 const double stddev = mWcStats.getStdDev();
576 const double minimum = mWcStats.getMin();
577 const double maximum = mWcStats.getMax();
578 const double meanCycles = mHzStats.getMean();
579 const double stddevCycles = mHzStats.getStdDev();
580 const double minCycles = mHzStats.getMin();
581 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800582 mCpuUsage.resetElapsed();
583 mWcStats.reset();
584 mHzStats.reset();
585 ALOGD("CPU usage for %s over past %.1f secs\n"
586 " (%u mixer loops at %.1f mean ms per loop):\n"
587 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
588 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
589 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000590 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800591 elapsed * .000000001, n, perLoop * .000001,
592 mean * .001,
593 stddev * .001,
594 minimum * .001,
595 maximum * .001,
596 mean / perLoop100,
597 stddev / perLoop100,
598 minimum / perLoop100,
599 maximum / perLoop100,
600 meanCycles / perLoop1k,
601 stddevCycles / perLoop1k,
602 minCycles / perLoop1k,
603 maxCycles / perLoop1k);
604
605 }
606 }
607#endif
608};
609
610// ----------------------------------------------------------------------------
611// ThreadBase
612// ----------------------------------------------------------------------------
613
Glenn Kasten97b7b752014-09-28 13:04:24 -0700614// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700615const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700616{
617 switch (type) {
618 case MIXER:
619 return "MIXER";
620 case DIRECT:
621 return "DIRECT";
622 case DUPLICATING:
623 return "DUPLICATING";
624 case RECORD:
625 return "RECORD";
626 case OFFLOAD:
627 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700628 case MMAP_PLAYBACK:
629 return "MMAP_PLAYBACK";
630 case MMAP_CAPTURE:
631 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200632 case SPATIALIZER:
633 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000634 case BIT_PERFECT:
635 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700636 default:
637 return "unknown";
638 }
639}
640
Andy Hung583043b2023-07-17 17:05:00 -0700641ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700642 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800643 : Thread(false /*canCallJava*/),
644 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700645 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700646 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
647 isOut),
648 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700649 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800650 // are set by PlaybackThread::readOutputParameters_l() or
651 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700652 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700653 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700654 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800655 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700656 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800657 mSystemReady(systemReady),
658 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800659{
Andy Hungcf10d742020-04-28 15:38:24 -0700660 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700661 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800662}
663
Andy Hungee58e4a2023-07-07 13:47:37 -0700664ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800665{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700666 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700667 mConfigEvents.clear();
668
Eric Laurent81784c32012-11-19 14:55:58 -0800669 // do not lock the mutex in destructor
670 releaseWakeLock_l();
671 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800672 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800673 binder->unlinkToDeath(mDeathRecipient);
674 }
Andy Hungd0979812019-02-21 15:51:44 -0800675
676 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800677}
678
Andy Hungee58e4a2023-07-07 13:47:37 -0700679status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700680{
681 status_t status = initCheck();
682 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800683 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700684 } else {
685 ALOGE("No working audio driver found.");
686 }
687 return status;
688}
689
Andy Hungee58e4a2023-07-07 13:47:37 -0700690void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800691{
692 ALOGV("ThreadBase::exit");
693 // do any cleanup required for exit to succeed
694 preExit();
695 {
696 // This lock prevents the following race in thread (uniprocessor for illustration):
697 // if (!exitPending()) {
698 // // context switch from here to exit()
699 // // exit() calls requestExit(), what exitPending() observes
700 // // exit() calls signal(), which is dropped since no waiters
701 // // context switch back from exit() to here
702 // mWaitWorkCV.wait(...);
703 // // now thread is hung
704 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700705 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800706 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700707 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800708 }
709 // When Thread::requestExitAndWait is made virtual and this method is renamed to
710 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700711
712 // For TimeCheck: track waiting on the thread join of getTid().
713 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
714
Eric Laurent81784c32012-11-19 14:55:58 -0800715 requestExitAndWait();
716}
717
Andy Hungee58e4a2023-07-07 13:47:37 -0700718status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800719{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000720 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700721 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800722
Eric Laurent10351942014-05-08 18:49:52 -0700723 return sendSetParameterConfigEvent_l(keyValuePairs);
724}
725
726// sendConfigEvent_l() must be called with ThreadBase::mLock held
727// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700728status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700729NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700730{
731 status_t status = NO_ERROR;
732
Eric Laurent72e3f392015-05-20 14:43:50 -0700733 if (event->mRequiresSystemReady && !mSystemReady) {
734 event->mWaitStatus = false;
735 mPendingConfigEvents.add(event);
736 return status;
737 }
Eric Laurent10351942014-05-08 18:49:52 -0700738 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700739 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700740 mWaitWorkCV.notify_one();
741 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700742 {
Andy Hungc5007f82023-08-29 14:26:09 -0700743 audio_utils::unique_lock _l(event->mutex());
Eric Laurent3fddffe2024-07-31 14:18:34 +0000744 nsecs_t timeoutNs = event->mType == CFG_EVENT_CREATE_AUDIO_PATCH ?
745 kCreatePatchEventTimeoutNs : kConfigEventTimeoutNs;
Eric Laurent10351942014-05-08 18:49:52 -0700746 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800747 if (event->mCondition.wait_for(
Eric Laurent3fddffe2024-07-31 14:18:34 +0000748 _l, std::chrono::nanoseconds(timeoutNs), getTid())
Andy Hung02ea2a02024-01-25 17:02:30 -0800749 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700750 event->mStatus = TIMED_OUT;
751 event->mWaitStatus = false;
752 }
753 }
754 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800755 }
Andy Hungc5007f82023-08-29 14:26:09 -0700756 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800757 return status;
758}
759
Andy Hungee58e4a2023-07-07 13:47:37 -0700760void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700761 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800762{
Andy Hung972bec12023-08-31 16:13:39 -0700763 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700764 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800765}
766
Andy Hungc5007f82023-08-29 14:26:09 -0700767// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700768void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700769 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800770{
Andy Hungd0979812019-02-21 15:51:44 -0800771 // The audio statistics history is exponentially weighted to forget events
772 // about five or more seconds in the past. In order to have
773 // crisper statistics for mediametrics, we reset the statistics on
774 // an IoConfigEvent, to reflect different properties for a new device.
775 mIoJitterMs.reset();
776 mLatencyMs.reset();
777 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000778 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100779 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800780
Eric Laurent09f1ed22019-04-24 17:45:17 -0700781 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700782 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800783}
784
Andy Hungee58e4a2023-07-07 13:47:37 -0700785void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700786{
Andy Hung972bec12023-08-31 16:13:39 -0700787 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800788 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700789}
790
Andy Hungc5007f82023-08-29 14:26:09 -0700791// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700792void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800793 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800794{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800795 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700796 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800797}
798
Andy Hungc5007f82023-08-29 14:26:09 -0700799// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700800status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800801{
Andy Hung2ddee192015-12-18 17:34:44 -0800802 sp<ConfigEvent> configEvent;
803 AudioParameter param(keyValuePair);
804 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700805 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800806 setMasterMono_l(value != 0);
807 if (param.size() == 1) {
808 return NO_ERROR; // should be a solo parameter - we don't pass down
809 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700810 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800811 configEvent = new SetParameterConfigEvent(param.toString());
812 } else {
813 configEvent = new SetParameterConfigEvent(keyValuePair);
814 }
Eric Laurent10351942014-05-08 18:49:52 -0700815 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700816}
817
Andy Hungee58e4a2023-07-07 13:47:37 -0700818status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700819 const struct audio_patch *patch,
820 audio_patch_handle_t *handle)
821{
Andy Hung972bec12023-08-31 16:13:39 -0700822 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700823 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
824 status_t status = sendConfigEvent_l(configEvent);
825 if (status == NO_ERROR) {
826 CreateAudioPatchConfigEventData *data =
827 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
828 *handle = data->mHandle;
829 }
830 return status;
831}
832
Andy Hungee58e4a2023-07-07 13:47:37 -0700833status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700834 const audio_patch_handle_t handle)
835{
Andy Hung972bec12023-08-31 16:13:39 -0700836 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700837 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
838 return sendConfigEvent_l(configEvent);
839}
840
Andy Hungee58e4a2023-07-07 13:47:37 -0700841status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700842 const DeviceDescriptorBaseVector& outDevices)
843{
844 if (type() != RECORD) {
845 // The update out device operation is only for record thread.
846 return INVALID_OPERATION;
847 }
Andy Hung972bec12023-08-31 16:13:39 -0700848 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700849 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
850 return sendConfigEvent_l(configEvent);
851}
852
Andy Hungee58e4a2023-07-07 13:47:37 -0700853void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200854{
855 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
856 sp<ConfigEvent> configEvent =
857 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
858 sendConfigEvent_l(configEvent);
859}
Eric Laurent1c333e22014-05-20 10:48:17 -0700860
Andy Hungee58e4a2023-07-07 13:47:37 -0700861void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200862{
Andy Hung972bec12023-08-31 16:13:39 -0700863 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200864 sendCheckOutputStageEffectsEvent_l();
865}
866
Andy Hungee58e4a2023-07-07 13:47:37 -0700867void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200868{
869 sp<ConfigEvent> configEvent =
870 (ConfigEvent *)new CheckOutputStageEffectsEvent();
871 sendConfigEvent_l(configEvent);
872}
873
Andy Hungee58e4a2023-07-07 13:47:37 -0700874void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200875{
876 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
877 sendConfigEvent_l(configEvent);
878}
879
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700880// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700881void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700882{
Eric Laurent10351942014-05-08 18:49:52 -0700883 bool configChanged = false;
884
Eric Laurent81784c32012-11-19 14:55:58 -0800885 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700886 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700887 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800888 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700889 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700890 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700891 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
892 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800893 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700894 true /*asynchronous*/);
895 if (err != 0) {
896 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700897 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700898 }
899 } break;
900 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700901 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700902 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700903 } break;
904 case CFG_EVENT_SET_PARAMETER: {
905 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
906 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
907 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700908 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000909 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700910 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700911 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700912 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700913 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 CreateAudioPatchConfigEventData *data =
915 (CreateAudioPatchConfigEventData *)event->mData.get();
916 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700917 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200918 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700919 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
920 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
921 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700922 } break;
923 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700924 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700925 ReleaseAudioPatchConfigEventData *data =
926 (ReleaseAudioPatchConfigEventData *)event->mData.get();
927 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700928 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200929 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700930 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
931 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
932 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
933 } break;
934 case CFG_EVENT_UPDATE_OUT_DEVICE: {
935 UpdateOutDevicesConfigEventData *data =
936 (UpdateOutDevicesConfigEventData *)event->mData.get();
937 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700938 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200939 case CFG_EVENT_RESIZE_BUFFER: {
940 ResizeBufferConfigEventData *data =
941 (ResizeBufferConfigEventData *)event->mData.get();
942 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
943 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200944
945 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
946 setCheckOutputStageEffects();
947 } break;
948
Eric Laurent68a40a82022-05-03 18:15:04 +0200949 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
950 onHalLatencyModesChanged_l();
951 } break;
952
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700953 default:
Eric Laurent10351942014-05-08 18:49:52 -0700954 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700955 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800956 }
Eric Laurent10351942014-05-08 18:49:52 -0700957 {
Andy Hung972bec12023-08-31 16:13:39 -0700958 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700959 if (event->mWaitStatus) {
960 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700961 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700962 }
963 }
964 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
965 }
966
967 if (configChanged) {
968 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800969 }
Eric Laurent81784c32012-11-19 14:55:58 -0800970}
971
Marco Nelissenb2208842014-02-07 14:00:50 -0800972String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
973 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700974 const audio_channel_representation_t representation =
975 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700976
977 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800978 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700979 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
980 if (output) {
981 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
982 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
983 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700984 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700985 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
986 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
987 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
988 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
989 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
990 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
991 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
992 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
993 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
994 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
995 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
996 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700997 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
998 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
999 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
1000 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
1001 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
1002 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
1003 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -07001004 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001005 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
1006 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001007 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
1008 } else {
1009 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
1010 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
1011 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1012 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1013 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1014 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1015 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1016 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1017 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1018 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1019 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1020 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001021 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1022 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1023 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001024 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001025 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1026 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001027 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1028 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1029 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1030 }
1031 const int len = s.length();
1032 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001033 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001034 s.unlockBuffer(len - 2); // remove trailing ", "
1035 }
1036 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001037 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001038 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1039 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1040 return s;
1041 default:
1042 s.appendFormat("unknown mask, representation:%d bits:%#x",
1043 representation, audio_channel_mask_get_bits(mask));
1044 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001045 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001046}
1047
Andy Hungee58e4a2023-07-07 13:47:37 -07001048void ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001049{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001050 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1051 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1052
Atneya Nairf94040f2024-10-07 16:00:49 -07001053 {
1054 afutils::FallibleLockGuard l{mutex()};
1055 if (!l) {
1056 dprintf(fd, " Thread may be deadlocked\n");
1057 }
1058 dumpBase_l(fd, args);
1059 dumpInternals_l(fd, args);
1060 dumpTracks_l(fd, args);
1061 dumpEffectChains_l(fd, args);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001062 }
1063
1064 dprintf(fd, " Local log:\n");
Atneya Nairaa3afcb2024-10-08 16:36:19 -07001065 const auto logHeader = this->getLocalLogHeader();
1066 write(fd, logHeader.data(), logHeader.length());
Atneya Nair0423af92024-10-07 21:23:29 -07001067 mLocalLog.dump(fd, " " /* prefix */);
Andy Hungafc51db2022-04-08 17:33:40 -07001068
1069 // --all does the statistics
1070 bool dumpAll = false;
1071 for (const auto &arg : args) {
1072 if (arg == String16("--all")) {
1073 dumpAll = true;
1074 }
1075 }
1076 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001077 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001078 if (!sched.empty()) {
1079 (void)write(fd, sched.c_str(), sched.size());
1080 }
1081 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001082}
1083
Andy Hungee58e4a2023-07-07 13:47:37 -07001084void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001085{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001086 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001087 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001088 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001090 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1091 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001092 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001093 dprintf(fd, " Channel count: %u\n", mChannelCount);
1094 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001095 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001096 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1097 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001098 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001099 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001100 size_t numConfig = mConfigEvents.size();
1101 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001102 const size_t SIZE = 256;
1103 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001104 for (size_t i = 0; i < numConfig; i++) {
1105 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001106 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001107 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001108 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001109 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001110 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001111 }
Andy Hung293558a2017-03-21 12:19:20 -07001112 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001113 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001114 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001115 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001116 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001117 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001118
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001119 // Dump timestamp statistics for the Thread types that support it.
1120 if (mType == RECORD
1121 || mType == MIXER
1122 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001123 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001124 || mType == OFFLOAD
1125 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001126 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001127 dprintf(fd, " Timestamp corrected: %s\n",
1128 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001129 }
1130
Andy Hung446f4df2019-02-21 12:26:41 -08001131 if (mLastIoBeginNs > 0) { // MMAP may not set this
1132 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1133 isOutput() ? "write" : "read",
1134 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1135 }
1136
1137 if (mProcessTimeMs.getN() > 0) {
1138 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1139 }
1140
1141 if (mIoJitterMs.getN() > 0) {
1142 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1143 isOutput() ? "write" : "read",
1144 mIoJitterMs.toString().c_str());
1145 }
1146
Andy Hunge6c37112019-02-26 17:38:10 -08001147 if (mLatencyMs.getN() > 0) {
1148 dprintf(fd, " Threadloop %s latency stats: %s\n",
1149 isOutput() ? "write" : "read",
1150 mLatencyMs.toString().c_str());
1151 }
Robert Wu06db0a32021-08-10 19:05:34 +00001152
1153 if (mMonopipePipeDepthStats.getN() > 0) {
1154 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1155 isOutput() ? "write" : "read",
1156 mMonopipePipeDepthStats.toString().c_str());
1157 }
Eric Laurent81784c32012-11-19 14:55:58 -08001158}
1159
Andy Hungee58e4a2023-07-07 13:47:37 -07001160void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001161{
1162 const size_t SIZE = 256;
1163 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001164
Marco Nelissenb2208842014-02-07 14:00:50 -08001165 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001166 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001167 write(fd, buffer, strlen(buffer));
1168
Marco Nelissenb2208842014-02-07 14:00:50 -08001169 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001170 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001171 if (chain != 0) {
1172 chain->dump(fd, args);
1173 }
1174 }
1175}
1176
Andy Hungee58e4a2023-07-07 13:47:37 -07001177void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001178{
Andy Hung972bec12023-08-31 16:13:39 -07001179 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001180 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001181}
1182
Andy Hungee58e4a2023-07-07 13:47:37 -07001183String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001184{
1185 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001186 case MIXER:
1187 return String16("AudioMix");
1188 case DIRECT:
1189 return String16("AudioDirectOut");
1190 case DUPLICATING:
1191 return String16("AudioDup");
1192 case RECORD:
1193 return String16("AudioIn");
1194 case OFFLOAD:
1195 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001196 case MMAP_PLAYBACK:
1197 return String16("MmapPlayback");
1198 case MMAP_CAPTURE:
1199 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001200 case SPATIALIZER:
1201 return String16("AudioSpatial");
jiabin10b2fb82024-09-03 17:51:35 +00001202 case BIT_PERFECT:
1203 return String16("AudioBitPerfect");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001204 default:
1205 ALOG_ASSERT(false);
1206 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001207 }
1208}
1209
Andy Hungee58e4a2023-07-07 13:47:37 -07001210void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001211{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001212 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001213 if (mPowerManager != 0) {
1214 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001215 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001216 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1217 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001218 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001219 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001220 {} /* workSource */,
1221 {} /* historyTag */);
1222 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001223 mWakeLockToken = binder;
Andy Hung88a7afe2024-08-12 20:00:46 -07001224 if (media::psh_utils::AudioPowerManager::enabled()) {
1225 mThreadToken = media::psh_utils::createAudioThreadToken(
1226 getTid(), String8(getWakeLockTag()).c_str());
1227 }
Eric Laurent81784c32012-11-19 14:55:58 -08001228 }
Chris Ye6597d732020-02-28 22:38:25 -08001229 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001230 }
Wei Jia3f273d12015-11-24 09:06:49 -08001231
Andy Hung3f0c9022016-01-15 17:49:46 -08001232 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001233 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1234 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001235}
1236
Andy Hungee58e4a2023-07-07 13:47:37 -07001237void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001238{
Andy Hung972bec12023-08-31 16:13:39 -07001239 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001240 releaseWakeLock_l();
1241}
1242
Andy Hungee58e4a2023-07-07 13:47:37 -07001243void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001244{
Andy Hung3f0c9022016-01-15 17:49:46 -08001245 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001246 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001247 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001248 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001249 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001250 }
1251 mWakeLockToken.clear();
1252 }
Andy Hung88a7afe2024-08-12 20:00:46 -07001253 mThreadToken.reset();
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001254}
1255
Andy Hungee58e4a2023-07-07 13:47:37 -07001256void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001257 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001258 // use checkService() to avoid blocking if power service is not up yet
1259 sp<IBinder> binder =
1260 defaultServiceManager()->checkService(String16("power"));
1261 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001262 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001263 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001264 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001265 binder->linkToDeath(mDeathRecipient);
1266 }
1267 }
1268}
1269
Andy Hungee58e4a2023-07-07 13:47:37 -07001270void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001271 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001272
1273#if !LOG_NDEBUG
1274 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001275 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001276 s << uid << " ";
1277 }
1278 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1279#endif
1280
Andy Hung438e7572015-12-14 15:51:17 -08001281 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1282 if (mSystemReady) {
1283 ALOGE("no wake lock to update, but system ready!");
1284 } else {
1285 ALOGW("no wake lock to update, system not ready yet");
1286 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001287 return;
1288 }
1289 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001290 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001291 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1292 mWakeLockToken, uidsAsInt);
1293 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001294 }
1295}
1296
Andy Hungee58e4a2023-07-07 13:47:37 -07001297void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001298{
Andy Hung972bec12023-08-31 16:13:39 -07001299 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001300 releaseWakeLock_l();
1301 mPowerManager.clear();
1302}
1303
Andy Hungee58e4a2023-07-07 13:47:37 -07001304void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001305 const DeviceDescriptorBaseVector& outDevices __unused)
1306{
1307 ALOGE("%s should only be called in RecordThread", __func__);
1308}
1309
Andy Hungee58e4a2023-07-07 13:47:37 -07001310void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001311{
1312 ALOGE("%s should only be called in RecordThread", __func__);
1313}
1314
Andy Hungee58e4a2023-07-07 13:47:37 -07001315void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001316{
1317 sp<ThreadBase> thread = mThread.promote();
1318 if (thread != 0) {
1319 thread->clearPowerManager();
1320 }
1321 ALOGW("power manager service died !!!");
1322}
1323
Andy Hungee58e4a2023-07-07 13:47:37 -07001324void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001325 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001326{
Andy Hung116bc262023-06-20 18:56:17 -07001327 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001328 if (chain != 0) {
1329 if (type != NULL) {
1330 chain->setEffectSuspended_l(type, suspend);
1331 } else {
1332 chain->setEffectSuspendedAll_l(suspend);
1333 }
1334 }
1335
1336 updateSuspendedSessions_l(type, suspend, sessionId);
1337}
1338
Andy Hungee58e4a2023-07-07 13:47:37 -07001339void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001340{
1341 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1342 if (index < 0) {
1343 return;
1344 }
1345
1346 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1347 mSuspendedSessions.valueAt(index);
1348
1349 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001350 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001351 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001352 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001353 chain->setEffectSuspendedAll_l(true);
1354 } else {
1355 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1356 desc->mType.timeLow);
1357 chain->setEffectSuspended_l(&desc->mType, true);
1358 }
1359 }
1360 }
1361}
1362
Andy Hungee58e4a2023-07-07 13:47:37 -07001363void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001364 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001365 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001366{
1367 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1368
1369 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1370
1371 if (suspend) {
1372 if (index >= 0) {
1373 sessionEffects = mSuspendedSessions.valueAt(index);
1374 } else {
1375 mSuspendedSessions.add(sessionId, sessionEffects);
1376 }
1377 } else {
1378 if (index < 0) {
1379 return;
1380 }
1381 sessionEffects = mSuspendedSessions.valueAt(index);
1382 }
1383
1384
Andy Hung116bc262023-06-20 18:56:17 -07001385 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001386 if (type != NULL) {
1387 key = type->timeLow;
1388 }
1389 index = sessionEffects.indexOfKey(key);
1390
1391 sp<SuspendedSessionDesc> desc;
1392 if (suspend) {
1393 if (index >= 0) {
1394 desc = sessionEffects.valueAt(index);
1395 } else {
1396 desc = new SuspendedSessionDesc();
1397 if (type != NULL) {
1398 desc->mType = *type;
1399 }
1400 sessionEffects.add(key, desc);
1401 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1402 }
1403 desc->mRefCount++;
1404 } else {
1405 if (index < 0) {
1406 return;
1407 }
1408 desc = sessionEffects.valueAt(index);
1409 if (--desc->mRefCount == 0) {
1410 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1411 sessionEffects.removeItemsAt(index);
1412 if (sessionEffects.isEmpty()) {
1413 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1414 sessionId);
1415 mSuspendedSessions.removeItem(sessionId);
1416 }
1417 }
1418 }
1419 if (!sessionEffects.isEmpty()) {
1420 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1421 }
1422}
1423
Andy Hungee58e4a2023-07-07 13:47:37 -07001424void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001425 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001426 bool threadLocked)
1427NO_THREAD_SAFETY_ANALYSIS // manual locking
1428{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001429 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001430 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001431 }
Eric Laurent81784c32012-11-19 14:55:58 -08001432
Eric Laurent81784c32012-11-19 14:55:58 -08001433 if (mType != RECORD) {
1434 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1435 // another session. This gives the priority to well behaved effect control panels
1436 // and applications not using global effects.
1437 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1438 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001439 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001440 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1441 }
1442 }
1443
Eric Laurent6b446ce2019-12-13 10:56:31 -08001444 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001445 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001446 }
1447}
1448
Andy Hungc5007f82023-08-29 14:26:09 -07001449// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001450status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001451 const effect_descriptor_t *desc, audio_session_t sessionId)
1452{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001453 // No global output effect sessions on record threads
1454 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1455 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001456 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1457 desc->name, mThreadName);
1458 return BAD_VALUE;
1459 }
1460 // only pre processing effects on record thread
1461 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1462 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1463 desc->name, mThreadName);
1464 return BAD_VALUE;
1465 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001466
1467 // always allow effects without processing load or latency
1468 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1469 return NO_ERROR;
1470 }
1471
Eric Laurent4c415062016-06-17 16:14:16 -07001472 audio_input_flags_t flags = mInput->flags;
1473 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1474 if (flags & AUDIO_INPUT_FLAG_RAW) {
1475 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1476 desc->name, mThreadName);
1477 return BAD_VALUE;
1478 }
1479 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1480 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1481 desc->name, mThreadName);
1482 return BAD_VALUE;
1483 }
1484 }
jiabineb3bda02020-06-30 14:07:03 -07001485
Andy Hung116bc262023-06-20 18:56:17 -07001486 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001487 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1488 return BAD_VALUE;
1489 }
Eric Laurent4c415062016-06-17 16:14:16 -07001490 return NO_ERROR;
1491}
1492
Andy Hungc5007f82023-08-29 14:26:09 -07001493// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001494status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001495 const effect_descriptor_t *desc, audio_session_t sessionId)
1496{
1497 // no preprocessing on playback threads
1498 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001499 ALOGW("%s: pre processing effect %s created on playback"
1500 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001501 return BAD_VALUE;
1502 }
1503
Eric Laurent3e4de772017-07-16 16:55:08 -07001504 // always allow effects without processing load or latency
1505 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1506 return NO_ERROR;
1507 }
1508
Andy Hung116bc262023-06-20 18:56:17 -07001509 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001510 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1511 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001512 return BAD_VALUE;
1513 }
1514
Eric Laurent4eb45d02023-12-20 12:07:17 +01001515 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001516 && mType != SPATIALIZER) {
1517 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1518 __func__, mType);
1519 return BAD_VALUE;
1520 }
1521
Eric Laurent4c415062016-06-17 16:14:16 -07001522 switch (mType) {
1523 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001524 audio_output_flags_t flags = mOutput->flags;
1525 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1526 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1527 // global effects are applied only to non fast tracks if they are SW
1528 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1529 break;
1530 }
1531 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1532 // only post processing on output stage session
1533 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001534 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1535 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001536 return BAD_VALUE;
1537 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001538 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1539 // only post processing on output stage session
1540 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001541 ALOGW("%s: non post processing effect %s not allowed on device session",
1542 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001543 return BAD_VALUE;
1544 }
Eric Laurent4c415062016-06-17 16:14:16 -07001545 } else {
1546 // no restriction on effects applied on non fast tracks
1547 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1548 break;
1549 }
1550 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001551
Eric Laurent4c415062016-06-17 16:14:16 -07001552 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001553 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001554 return BAD_VALUE;
1555 }
1556 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001557 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1558 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001559 return BAD_VALUE;
1560 }
1561 }
1562 } break;
1563 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001564 // nothing actionable on offload threads, if the effect:
1565 // - is offloadable: the effect can be created
1566 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1567 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001568 break;
1569 case DIRECT:
1570 // Reject any effect on Direct output threads for now, since the format of
1571 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001572 ALOGW("%s: effect %s on DIRECT output thread %s",
1573 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001574 return BAD_VALUE;
1575 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001576 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001577 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1578 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001579 return BAD_VALUE;
1580 }
1581 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001582 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1583 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001584 return BAD_VALUE;
1585 }
1586 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001587 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1588 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001589 return BAD_VALUE;
1590 }
1591 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001592 case SPATIALIZER:
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001593 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are supported on spatializer mixer, but only
1594 // the spatialized track have global effects applied for now.
Eric Laurentb62d0362021-10-26 17:40:18 +02001595 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1596 // are supported and added after the spatializer.
1597 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00001598 ALOGD("%s: global effect %s on spatializer thread %s", __func__, desc->name,
1599 mThreadName);
Eric Laurentb62d0362021-10-26 17:40:18 +02001600 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1601 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001602 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001603 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1604 break;
1605 }
1606 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1607 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1608 __func__, desc->name);
1609 return BAD_VALUE;
1610 }
1611 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1612 // only post processing on output stage session
1613 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1614 ALOGW("%s: non post processing effect %s not allowed on device session",
1615 __func__, desc->name);
1616 return BAD_VALUE;
1617 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001618 }
1619 break;
jiabinc658e452022-10-21 20:52:21 +00001620 case BIT_PERFECT:
1621 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1622 // Allow HW accelerated effects of tunnel type
1623 break;
1624 }
1625 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1626 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1627 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1628 // 3) there is any bit-perfect track with the given session id.
1629 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1630 sessionId == AUDIO_SESSION_DEVICE) {
1631 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1632 __func__, desc->name, mThreadName);
1633 return BAD_VALUE;
1634 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1635 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1636 __func__, desc->name, sessionId);
1637 return BAD_VALUE;
1638 }
1639 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001640 default:
1641 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1642 }
1643
1644 return NO_ERROR;
1645}
1646
Andy Hungc5007f82023-08-29 14:26:09 -07001647// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001648sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001649 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001650 const sp<IEffectClient>& effectClient,
1651 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001652 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001653 effect_descriptor_t *desc,
1654 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001655 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001656 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001657 bool probe,
1658 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001659{
Andy Hung116bc262023-06-20 18:56:17 -07001660 sp<IAfEffectModule> effect;
1661 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001662 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001663 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001664 bool chainCreated = false;
1665 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001666 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001667
1668 lStatus = initCheck();
1669 if (lStatus != NO_ERROR) {
1670 ALOGW("createEffect_l() Audio driver not initialized.");
1671 goto Exit;
1672 }
1673
Eric Laurent81784c32012-11-19 14:55:58 -08001674 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1675
Andy Hungc5007f82023-08-29 14:26:09 -07001676 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001677 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001678
Eric Laurent4c415062016-06-17 16:14:16 -07001679 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001680 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001681 goto Exit;
1682 }
1683
Eric Laurent81784c32012-11-19 14:55:58 -08001684 // check for existing effect chain with the requested audio session
1685 chain = getEffectChain_l(sessionId);
1686 if (chain == 0) {
1687 // create a new chain for this session
1688 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001689 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001690 addEffectChain_l(chain);
1691 chain->setStrategy(getStrategyForSession_l(sessionId));
1692 chainCreated = true;
1693 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001694 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001695 }
1696
1697 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1698
1699 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001700 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001701 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001702 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001703 if (lStatus != NO_ERROR) {
1704 goto Exit;
1705 }
1706 effectCreated = true;
1707
jiabinc52b1ff2019-10-31 17:20:42 -07001708 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001709 effect->setDevices(outDeviceTypeAddrs());
1710 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001711 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001712 effect->setAudioSource(mAudioSource);
1713 }
jiabin1319f5a2021-03-30 22:21:24 +00001714 if (effect->isHapticGenerator()) {
1715 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1716 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001717 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Yi Kong3ac211f2024-08-12 07:31:44 +08001718 mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01001719 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001720 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001721 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001722 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001723 }
1724 }
Eric Laurent81784c32012-11-19 14:55:58 -08001725 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001726 handle = IAfEffectHandle::create(
1727 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001728 lStatus = handle->initCheck();
1729 if (lStatus == OK) {
1730 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001731 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001732 }
Eric Laurent81784c32012-11-19 14:55:58 -08001733 if (enabled != NULL) {
1734 *enabled = (int)effect->isEnabled();
1735 }
1736 }
1737
1738Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001739 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001740 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001741 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001742 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001743 }
Eric Laurent81784c32012-11-19 14:55:58 -08001744 if (chainCreated) {
1745 removeEffectChain_l(chain);
1746 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001747 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001748 }
1749
Glenn Kasten9156ef32013-08-06 15:39:08 -07001750 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001751 return handle;
1752}
1753
Andy Hungee58e4a2023-07-07 13:47:37 -07001754void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001755 bool unpinIfLast)
1756{
1757 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001758 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001759 {
Andy Hung972bec12023-08-31 16:13:39 -07001760 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001761 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001762 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001763 return;
1764 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001765 effect = effectBase->asEffectModule();
1766 if (effect == nullptr) {
1767 return;
1768 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001769 // restore suspended effects if the disconnected handle was enabled and the last one.
1770 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1771 if (remove) {
1772 removeEffect_l(effect, true);
1773 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001774 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001775 }
1776 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001777 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001778 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001779 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001780 }
1781 }
1782}
1783
Andy Hungee58e4a2023-07-07 13:47:37 -07001784void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001785 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001786 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001787 broadcast_l();
1788 }
1789 if (!effect->isOffloadable()) {
1790 if (mType == ThreadBase::OFFLOAD) {
1791 PlaybackThread *t = (PlaybackThread *)this;
1792 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1793 }
1794 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001795 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001796 }
1797 }
1798}
1799
Andy Hungee58e4a2023-07-07 13:47:37 -07001800void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001801 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001802 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001803 broadcast_l();
1804 }
1805}
1806
Andy Hungee58e4a2023-07-07 13:47:37 -07001807sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001808 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001809{
Andy Hung972bec12023-08-31 16:13:39 -07001810 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001811 return getEffect_l(sessionId, effectId);
1812}
1813
Andy Hungee58e4a2023-07-07 13:47:37 -07001814sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001815 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001816{
Andy Hung116bc262023-06-20 18:56:17 -07001817 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001818 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1819}
1820
Andy Hungee58e4a2023-07-07 13:47:37 -07001821std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001822{
Andy Hung116bc262023-06-20 18:56:17 -07001823 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001824 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001825}
1826
Andy Hung972bec12023-08-31 16:13:39 -07001827// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1828// ThreadBase::mutex() held
1829status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001830{
1831 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001832 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001833 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001834 bool chainCreated = false;
1835
Eric Laurent5baf2af2013-09-12 17:37:00 -07001836 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001837 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1838 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001839
Eric Laurent81784c32012-11-19 14:55:58 -08001840 if (chain == 0) {
1841 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001842 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001843 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001844 addEffectChain_l(chain);
1845 chain->setStrategy(getStrategyForSession_l(sessionId));
1846 chainCreated = true;
1847 }
Andy Hung972bec12023-08-31 16:13:39 -07001848 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001849
1850 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001851 ALOGW("%s: %p effect %s already present in chain %p",
1852 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001853 return BAD_VALUE;
1854 }
1855
Shunkai Yaod125e402024-01-20 03:19:06 +00001856 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001857
Shunkai Yao29d10572024-03-19 04:31:47 +00001858 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001859 if (status != NO_ERROR) {
1860 if (chainCreated) {
1861 removeEffectChain_l(chain);
1862 }
1863 return status;
1864 }
1865
jiabin8f278ee2019-11-11 12:16:27 -08001866 effect->setDevices(outDeviceTypeAddrs());
1867 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001868 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001869 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001870
Eric Laurent81784c32012-11-19 14:55:58 -08001871 return NO_ERROR;
1872}
1873
Andy Hungee58e4a2023-07-07 13:47:37 -07001874void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001875
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001876 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001877 effect_descriptor_t desc = effect->desc();
1878 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1879 detachAuxEffect_l(effect->id());
1880 }
1881
Andy Hung116bc262023-06-20 18:56:17 -07001882 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001883 if (chain != 0) {
1884 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001885 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001886 removeEffectChain_l(chain);
1887 }
1888 } else {
1889 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1890 }
1891}
1892
Shunkai Yaof4847652024-01-12 00:25:20 +00001893void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1894 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001895{
1896 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001897 for (const auto& effectChain : effectChains) {
1898 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001899 }
1900}
1901
Shunkai Yaof4847652024-01-12 00:25:20 +00001902void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1903 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001904{
Shunkai Yaof4847652024-01-12 00:25:20 +00001905 for (const auto& effectChain : effectChains) {
1906 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001907 }
1908}
1909
Andy Hungee58e4a2023-07-07 13:47:37 -07001910sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001911{
Andy Hung972bec12023-08-31 16:13:39 -07001912 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001913 return getEffectChain_l(sessionId);
1914}
1915
Andy Hungee58e4a2023-07-07 13:47:37 -07001916sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001917 const
Eric Laurent81784c32012-11-19 14:55:58 -08001918{
1919 size_t size = mEffectChains.size();
1920 for (size_t i = 0; i < size; i++) {
1921 if (mEffectChains[i]->sessionId() == sessionId) {
1922 return mEffectChains[i];
1923 }
1924 }
1925 return 0;
1926}
1927
Andy Hungee58e4a2023-07-07 13:47:37 -07001928void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001929{
Andy Hung972bec12023-08-31 16:13:39 -07001930 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001931 size_t size = mEffectChains.size();
1932 for (size_t i = 0; i < size; i++) {
1933 mEffectChains[i]->setMode_l(mode);
1934 }
1935}
1936
Andy Hungee58e4a2023-07-07 13:47:37 -07001937void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001938{
1939 config->type = AUDIO_PORT_TYPE_MIX;
1940 config->ext.mix.handle = mId;
1941 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001942 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001943 config->channel_mask = mChannelMask;
1944 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1945 AUDIO_PORT_CONFIG_FORMAT;
1946}
1947
Andy Hungee58e4a2023-07-07 13:47:37 -07001948void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001949{
Andy Hung972bec12023-08-31 16:13:39 -07001950 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001951 if (mSystemReady) {
1952 return;
1953 }
1954 mSystemReady = true;
1955
1956 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1957 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1958 }
1959 mPendingConfigEvents.clear();
1960}
1961
Andy Hungdae27702016-10-31 14:01:16 -07001962template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001963ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001964 ssize_t index = mActiveTracks.indexOf(track);
1965 if (index >= 0) {
1966 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1967 return index;
1968 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001969 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001970 mActiveTracksGeneration++;
1971 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001972 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001973 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001974 return mActiveTracks.add(track);
1975}
1976
1977template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001978ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001979 ssize_t index = mActiveTracks.remove(track);
1980 if (index < 0) {
1981 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1982 return index;
1983 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001984 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001985 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001986 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001987 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001988 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001989#ifdef TEE_SINK
1990 track->dumpTee(-1 /* fd */, "_REMOVE");
1991#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001992 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001993 return index;
1994}
1995
1996template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001997void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001998 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001999 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002000 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07002001 }
2002 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07002003 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07002004 mActiveTracks.clear();
2005 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07002006}
2007
2008template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07002009void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07002010 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07002011 // Updates ActiveTracks client uids to the thread wakelock.
2012 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
2013 thread->updateWakeLockUids_l(getWakeLockUids());
2014 mLastActiveTracksGeneration = mActiveTracksGeneration;
2015 }
Andy Hungdae27702016-10-31 14:01:16 -07002016}
Eric Laurent83b88082014-06-20 18:31:16 -07002017
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002018template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002019bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002020 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002021 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002022
2023 for (const sp<T> &track : mActiveTracks) {
2024 // Do not short-circuit as all hasChanged states must be reset
2025 // as all the metadata are going to be sent
2026 hasChanged |= track->readAndClearHasChanged();
2027 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002028 return hasChanged;
2029}
2030
2031template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002032void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002033 const char *funcName, const sp<T> &track) const {
2034 if (mLocalLog != nullptr) {
2035 String8 result;
2036 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002037 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002038 }
2039}
2040
Andy Hungee58e4a2023-07-07 13:47:37 -07002041void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002042{
2043 // Thread could be blocked waiting for async
2044 // so signal it to handle state changes immediately
2045 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2046 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2047 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002048 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002049}
2050
Andy Hungd0979812019-02-21 15:51:44 -08002051// Call only from threadLoop() or when it is idle.
2052// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002053void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002054NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002055{
2056 // Do not log if we have no stats.
2057 // We choose the timestamp verifier because it is the most likely item to be present.
2058 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2059 if (nstats == 0) {
2060 return;
2061 }
2062
2063 // Don't log more frequently than once per 12 hours.
2064 // We use BOOTTIME to include suspend time.
2065 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2066 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2067 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2068 return;
2069 }
2070
2071 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2072 mLastRecordedTimeNs = timeNs;
2073
Ray Essickf27e9872019-12-07 06:28:46 -08002074 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002075
2076#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2077
2078 // thread configuration
2079 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2080 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2081 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2082 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2083 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2084 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2085 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002086 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2087 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002088
2089 // thread statistics
2090 if (mIoJitterMs.getN() > 0) {
2091 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2092 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2093 }
2094 if (mProcessTimeMs.getN() > 0) {
2095 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2096 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2097 }
2098 const auto tsjitter = mTimestampVerifier.getJitterMs();
2099 if (tsjitter.getN() > 0) {
2100 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2101 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2102 }
2103 if (mLatencyMs.getN() > 0) {
2104 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2105 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2106 }
Robert Wu06db0a32021-08-10 19:05:34 +00002107 if (mMonopipePipeDepthStats.getN() > 0) {
2108 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2109 mMonopipePipeDepthStats.getMean());
2110 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2111 mMonopipePipeDepthStats.getStdDev());
2112 }
Andy Hungd0979812019-02-21 15:51:44 -08002113
2114 item->selfrecord();
2115}
2116
Andy Hungee58e4a2023-07-07 13:47:37 -07002117product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002118{
Andy Hung583043b2023-07-17 17:05:00 -07002119 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002120 return PRODUCT_STRATEGY_NONE;
2121 }
2122 return AudioSystem::getStrategyForStream(stream);
2123}
2124
Andy Hungc5007f82023-08-29 14:26:09 -07002125// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002126void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002127 const sp<audio_utils::MelProcessor>& /*processor*/)
2128{
2129 // Do nothing
2130 ALOGW("%s: ThreadBase does not support CSD", __func__);
2131}
2132
Andy Hungc5007f82023-08-29 14:26:09 -07002133// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002134void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002135{
2136 // Do nothing
2137 ALOGW("%s: ThreadBase does not support CSD", __func__);
2138}
2139
Eric Laurent81784c32012-11-19 14:55:58 -08002140// ----------------------------------------------------------------------------
2141// Playback
2142// ----------------------------------------------------------------------------
2143
Andy Hung583043b2023-07-17 17:05:00 -07002144PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002145 AudioStreamOut* output,
2146 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002147 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002148 bool systemReady,
2149 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002150 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002151 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002152 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002153 mMixerBuffer(NULL),
2154 mMixerBufferSize(0),
2155 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2156 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002157 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002158 mEffectBuffer(NULL),
2159 mEffectBufferSize(0),
2160 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2161 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002162 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002163 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002164 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002165 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002166 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002167 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002168 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002169 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002170 mMixerStatus(MIXER_IDLE),
2171 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002172 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002173 mBytesRemaining(0),
2174 mCurrentWriteLength(0),
2175 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002176 mWriteAckSequence(0),
2177 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002178 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002179 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002180 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002181 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002182 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002183 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002184 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002185{
Glenn Kastend7dca052015-03-05 16:05:54 -08002186 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002187 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002188
Andy Hungc5007f82023-08-29 14:26:09 -07002189 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002190 // it would be safer to explicitly pass initial masterVolume/masterMute as
2191 // parameter.
2192 //
2193 // If the HAL we are using has support for master volume or master mute,
2194 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2195 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002196 mMasterVolume = afThreadCallback->masterVolume_l();
2197 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002198 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002199 if (mOutput->audioHwDev->canSetMasterVolume()) {
2200 mMasterVolume = 1.0;
2201 }
2202
2203 if (mOutput->audioHwDev->canSetMasterMute()) {
2204 mMasterMute = false;
2205 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002206 mIsMsdDevice = strcmp(
2207 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002208 }
2209
Eric Laurentf1f22e72021-07-13 14:04:14 +02002210 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2211 mMixerChannelMask = mixerConfig->channel_mask;
2212 }
2213
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002214 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002215
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002216 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002217 && mMixerChannelMask != mChannelMask) {
2218 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2219 mChannelMask, mMixerChannelMask);
2220 }
2221
Andy Hungc8fddf32018-08-08 18:32:37 -07002222 // TODO: We may also match on address as well as device type for
2223 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002224 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002225 // TODO: This property should be ensure that only contains one single device type.
2226 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2227 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002228 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2229 : AUDIO_DEVICE_NONE));
2230 }
Andy Hung6b137d12024-08-27 22:35:17 +00002231 if (!audioserver_flags::portid_volume_management()) {
2232 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2233 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
2234 mStreamTypes[stream].volume = 0.0f;
2235 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
2236 }
2237 // Audio patch and call assistant volume are always max
2238 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2239 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
2240 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2241 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002242 }
Eric Laurent81784c32012-11-19 14:55:58 -08002243}
2244
Andy Hungee58e4a2023-07-07 13:47:37 -07002245PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002246{
Andy Hung583043b2023-07-17 17:05:00 -07002247 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002248 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002249 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002250 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002251 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002252}
2253
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002254// Thread virtuals
2255
Andy Hungee58e4a2023-07-07 13:47:37 -07002256void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002257{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002258 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002259 ALOGE("The stream is not open yet"); // This should not happen.
2260 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002261 // Callbacks take strong or weak pointers as a parameter.
2262 // Since PlaybackThread passes itself as a callback handler, it can only
2263 // be done outside of the constructor. Creating weak and especially strong
2264 // pointers to a refcounted object in its own constructor is strongly
2265 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2266 // Even if a function takes a weak pointer, it is possible that it will
2267 // need to convert it to a strong pointer down the line.
2268 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2269 mOutput->stream->setCallback(this) == OK) {
2270 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002271 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002272 }
2273
jiabinf6eb4c32020-02-25 14:06:25 -08002274 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002275 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002276 }
2277 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002278 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002279 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002280}
2281
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002282// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002283void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002284{
2285 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002286 status_t result = mOutput->stream->exit();
2287 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002288}
2289
Andy Hungee58e4a2023-07-07 13:47:37 -07002290void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002291{
Eric Laurent81784c32012-11-19 14:55:58 -08002292 String8 result;
Andy Hung6b137d12024-08-27 22:35:17 +00002293 if (!audioserver_flags::portid_volume_management()) {
2294 result.appendFormat(" Stream volumes in dB: ");
2295 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2296 const stream_type_t *st = &mStreamTypes[i];
2297 if (i > 0) {
2298 result.appendFormat(", ");
2299 }
2300 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2301 if (st->mute) {
2302 result.append("M");
2303 }
Eric Laurent81784c32012-11-19 14:55:58 -08002304 }
2305 }
2306 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002307 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002308 result.clear();
2309
Eric Laurent81784c32012-11-19 14:55:58 -08002310 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2311 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002312 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002313 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002314
2315 size_t numtracks = mTracks.size();
2316 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002317 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002318 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002319 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002320 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002321 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002322 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002323 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002324 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002325 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002326 if (track != 0) {
2327 bool active = mActiveTracks.indexOf(track) >= 0;
2328 if (active) {
2329 numactiveseen++;
2330 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002331 result.append(prefix);
2332 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002333 }
2334 }
2335 } else {
2336 result.append("\n");
2337 }
2338 if (numactiveseen != numactive) {
2339 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002340 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002341 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002342 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002343 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002344 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002345 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002346 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002347 result.append(prefix);
2348 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002349 }
2350 }
2351 }
2352
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002353 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002354}
2355
Andy Hungee58e4a2023-07-07 13:47:37 -07002356void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002357{
Andy Hung04cb8f72020-03-20 13:44:33 -07002358 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002359 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002360 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2361 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002362 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2363 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2364 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2365 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002366 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002367 dprintf(fd, " Total writes: %d\n", mNumWrites);
2368 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2369 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002370 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002371 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002372 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002373 AudioStreamOut *output = mOutput;
2374 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002375 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002376 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002377 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2378 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2379 if (mPipeSink.get() != nullptr) {
2380 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2381 }
2382 if (output != nullptr) {
2383 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002384 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002385 }
Eric Laurent81784c32012-11-19 14:55:58 -08002386}
2387
Andy Hungc5007f82023-08-29 14:26:09 -07002388// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002389sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002390 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002391 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002392 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002393 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002394 audio_format_t format,
2395 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002396 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002397 size_t *pNotificationFrameCount,
2398 uint32_t notificationsPerBuffer,
2399 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002400 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002401 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002402 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002403 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002404 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002405 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002406 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002407 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002408 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002409 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002410 bool isBitPerfect,
Andy Hung6b137d12024-08-27 22:35:17 +00002411 audio_output_flags_t *afTrackFlags,
Vlad Popa1e865e62024-08-15 19:11:42 -07002412 float volume,
2413 bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002414{
Glenn Kasten74935e42013-12-19 08:56:45 -08002415 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002416 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002417 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002418 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002419 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002420 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002421 uint32_t sampleRate;
2422
2423 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2424 lStatus = BAD_VALUE;
2425 goto Exit;
2426 }
Eric Laurent21da6472017-11-09 16:29:26 -08002427
2428 if (*pSampleRate == 0) {
2429 *pSampleRate = mSampleRate;
2430 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002431 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002432
2433 // special case for FAST flag considered OK if fast mixer is present
2434 if (hasFastMixer()) {
2435 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2436 }
2437
2438 // Check if requested flags are compatible with output stream flags
2439 if ((*flags & outputFlags) != *flags) {
2440 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2441 *flags, outputFlags);
2442 *flags = (audio_output_flags_t)(*flags & outputFlags);
2443 }
Eric Laurent81784c32012-11-19 14:55:58 -08002444
jiabinc658e452022-10-21 20:52:21 +00002445 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002446 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002447 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002448 if (chain.get() != nullptr) {
2449 // Bit-perfect is required according to the configuration and preferred mixer
2450 // attributes, but it is not in the output flag from the client's request. Explicitly
2451 // adding bit-perfect flag to check the compatibility
2452 audio_output_flags_t flagsToCheck =
2453 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2454 chain->checkOutputFlagCompatibility(&flagsToCheck);
2455 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2456 ALOGE("%s cannot create track as there is data-processing effect attached to "
2457 "given session id(%d)", __func__, sessionId);
2458 lStatus = BAD_VALUE;
2459 goto Exit;
2460 }
2461 *flags = flagsToCheck;
2462 }
2463 }
2464
Eric Laurent81784c32012-11-19 14:55:58 -08002465 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002466 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002467 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002468 // PCM data
2469 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002470 // TODO: extract as a data library function that checks that a computationally
2471 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002472 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002473 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2474 (channelMask == AUDIO_CHANNEL_OUT_MONO
2475 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002476 // hardware sample rate
2477 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002478 // normal mixer has an associated fast mixer
2479 hasFastMixer() &&
2480 // there are sufficient fast track slots available
2481 (mFastTrackAvailMask != 0)
2482 // FIXME test that MixerThread for this fast track has a capable output HAL
2483 // FIXME add a permission test also?
2484 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002485 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2486 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002487 // read the fast track multiplier property the first time it is needed
2488 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2489 if (ok != 0) {
2490 ALOGE("%s pthread_once failed: %d", __func__, ok);
2491 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002492 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002493 }
Eric Laurent4c415062016-06-17 16:14:16 -07002494
2495 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002496 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002497 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002498 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002499 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002500 AUDIO_SESSION_OUTPUT_STAGE,
2501 AUDIO_SESSION_OUTPUT_MIX,
2502 sessionId,
2503 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002504 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002505 if (chain.get() != nullptr) {
2506 audio_output_flags_t old = *flags;
2507 chain->checkOutputFlagCompatibility(flags);
2508 if (old != *flags) {
2509 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2510 (int)session, (int)old, (int)*flags);
2511 }
Eric Laurent4c415062016-06-17 16:14:16 -07002512 }
2513 }
2514 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002515 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002516 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2517 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002518 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002519 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002520 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002521 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002522 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002523 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002524 audio_is_linear_pcm(format), channelMask, sampleRate,
2525 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002526 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002527 }
2528 }
Eric Laurent21da6472017-11-09 16:29:26 -08002529
2530 if (!audio_has_proportional_frames(format)) {
2531 if (sharedBuffer != 0) {
2532 // Same comment as below about ignoring frameCount parameter for set()
2533 frameCount = sharedBuffer->size();
2534 } else if (frameCount == 0) {
2535 frameCount = mNormalFrameCount;
2536 }
2537 if (notificationFrameCount != frameCount) {
2538 notificationFrameCount = frameCount;
2539 }
2540 } else if (sharedBuffer != 0) {
2541 // FIXME: Ensure client side memory buffers need
2542 // not have additional alignment beyond sample
2543 // (e.g. 16 bit stereo accessed as 32 bit frame).
2544 size_t alignment = audio_bytes_per_sample(format);
2545 if (alignment & 1) {
2546 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2547 alignment = 1;
2548 }
2549 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2550 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2551 if (channelCount > 1) {
2552 // More than 2 channels does not require stronger alignment than stereo
2553 alignment <<= 1;
2554 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002555 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002556 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002557 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002558 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002559 goto Exit;
2560 }
Eric Laurent21da6472017-11-09 16:29:26 -08002561
2562 // When initializing a shared buffer AudioTrack via constructors,
2563 // there's no frameCount parameter.
2564 // But when initializing a shared buffer AudioTrack via set(),
2565 // there _is_ a frameCount parameter. We silently ignore it.
2566 frameCount = sharedBuffer->size() / frameSize;
2567 } else {
2568 size_t minFrameCount = 0;
2569 // For fast tracks we try to respect the application's request for notifications per buffer.
2570 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2571 if (notificationsPerBuffer > 0) {
2572 // Avoid possible arithmetic overflow during multiplication.
2573 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2574 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2575 notificationsPerBuffer, mFrameCount);
2576 } else {
2577 minFrameCount = mFrameCount * notificationsPerBuffer;
2578 }
2579 }
2580 } else {
2581 // For normal PCM streaming tracks, update minimum frame count.
2582 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2583 // cover audio hardware latency.
2584 // This is probably too conservative, but legacy application code may depend on it.
2585 // If you change this calculation, also review the start threshold which is related.
2586 uint32_t latencyMs = latency_l();
2587 if (latencyMs == 0) {
2588 ALOGE("Error when retrieving output stream latency");
2589 lStatus = UNKNOWN_ERROR;
2590 goto Exit;
2591 }
2592
2593 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2594 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2595
Eric Laurent81784c32012-11-19 14:55:58 -08002596 }
Eric Laurent21da6472017-11-09 16:29:26 -08002597 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002598 frameCount = minFrameCount;
2599 }
Eric Laurent81784c32012-11-19 14:55:58 -08002600 }
Eric Laurent21da6472017-11-09 16:29:26 -08002601
2602 // Make sure that application is notified with sufficient margin before underrun.
2603 // The client can divide the AudioTrack buffer into sub-buffers,
2604 // and expresses its desire to server as the notification frame count.
2605 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2606 size_t maxNotificationFrames;
2607 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2608 // notify every HAL buffer, regardless of the size of the track buffer
2609 maxNotificationFrames = mFrameCount;
2610 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002611 // Triple buffer the notification period for a triple buffered mixer period;
2612 // otherwise, double buffering for the notification period is fine.
2613 //
2614 // TODO: This should be moved to AudioTrack to modify the notification period
2615 // on AudioTrack::setBufferSizeInFrames() changes.
2616 const int nBuffering =
2617 (uint64_t{frameCount} * mSampleRate)
2618 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2619
Eric Laurent21da6472017-11-09 16:29:26 -08002620 maxNotificationFrames = frameCount / nBuffering;
2621 // If client requested a fast track but this was denied, then use the smaller maximum.
2622 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2623 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2624 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2625 maxNotificationFrames = maxNotificationFramesFastDenied;
2626 }
2627 }
2628 }
2629 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2630 if (notificationFrameCount == 0) {
2631 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2632 maxNotificationFrames, frameCount);
2633 } else {
2634 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2635 notificationFrameCount, maxNotificationFrames, frameCount);
2636 }
2637 notificationFrameCount = maxNotificationFrames;
2638 }
2639 }
2640
Glenn Kasten74935e42013-12-19 08:56:45 -08002641 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002642 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002643
Glenn Kastenc3df8382014-03-13 15:05:25 -07002644 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002645 case BIT_PERFECT:
2646 if (isBitPerfect) {
2647 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2648 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2649 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2650 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2651 mChannelMask);
2652 lStatus = BAD_VALUE;
2653 goto Exit;
2654 }
2655 }
2656 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002657
2658 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002659 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002660 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002661 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2662 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002663 sampleRate, format, channelMask, mOutput, mFormat);
2664 lStatus = BAD_VALUE;
2665 goto Exit;
2666 }
2667 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002668 break;
2669
2670 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002671 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002672 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2673 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 sampleRate, format, channelMask, mOutput, mFormat);
2675 lStatus = BAD_VALUE;
2676 goto Exit;
2677 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002678 break;
2679
2680 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002681 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002682 ALOGE("createTrack_l() Bad parameter: format %#x \""
2683 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002684 format, mOutput, mFormat);
2685 lStatus = BAD_VALUE;
2686 goto Exit;
2687 }
Andy Hungcd044842014-08-07 11:04:34 -07002688 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002689 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2690 lStatus = BAD_VALUE;
2691 goto Exit;
2692 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002693 break;
2694
Eric Laurent81784c32012-11-19 14:55:58 -08002695 }
2696
2697 lStatus = initCheck();
2698 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002699 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002700 goto Exit;
2701 }
2702
Andy Hungc5007f82023-08-29 14:26:09 -07002703 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002704 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002705
2706 // all tracks in same audio session must share the same routing strategy otherwise
2707 // conflicts will happen when tracks are moved from one output to another by audio policy
2708 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002709 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002710 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002711 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002712 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002713 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002714 if (sessionId == t->sessionId() && strategy != actual) {
2715 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2716 strategy, actual);
2717 lStatus = BAD_VALUE;
2718 goto Exit;
2719 }
2720 }
2721 }
2722
Deeraj Soman2b515232024-05-14 12:58:24 +05302723 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2724 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002725 // dynamic audio policy.
2726 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302727 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002728 audio_output_flags_t trackFlags = *flags;
2729 if (mType == DIRECT) {
2730 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302731 } else if (mType == OFFLOAD) {
2732 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2733 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002734 }
jiabin94ed47c2023-07-27 23:34:20 +00002735 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002736
Andy Hung8d31fd22023-06-26 19:20:57 -07002737 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002738 channelMask, frameCount,
2739 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002740 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002741 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
Vlad Popa1e865e62024-08-15 19:11:42 -07002742 speed, isSpatialized, isBitPerfect, volume, muted);
Glenn Kasten03003332013-08-06 15:40:54 -07002743
Glenn Kasten03003332013-08-06 15:40:54 -07002744 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2745 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002746 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002747 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002748 goto Exit;
2749 }
2750 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002751 {
Andy Hung972bec12023-08-31 16:13:39 -07002752 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002753 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002754 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002755 }
2756 }
Eric Laurent81784c32012-11-19 14:55:58 -08002757
Andy Hung116bc262023-06-20 18:56:17 -07002758 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002759 if (chain != 0) {
2760 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2761 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002762 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002763 chain->incTrackCnt();
2764 }
2765
Eric Laurent05067782016-06-01 18:27:28 -07002766 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002767 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2768 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2769 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002770 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002771 }
2772 }
2773
2774 lStatus = NO_ERROR;
2775
2776Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002777 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002778 return track;
2779}
2780
Andy Hung1bc088a2018-02-09 15:57:31 -08002781template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002782ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002783{
Andy Hungc0691382018-09-12 18:01:57 -07002784 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002785 const ssize_t index = mTracks.remove(track);
2786 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002787 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002788 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002789 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002790 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002791 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002792 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002793 }
2794 return index;
2795}
2796
Andy Hungee58e4a2023-07-07 13:47:37 -07002797uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002798{
2799 return latency;
2800}
2801
Andy Hungee58e4a2023-07-07 13:47:37 -07002802uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
Andy Hung972bec12023-08-31 16:13:39 -07002804 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002805 return latency_l();
2806}
Andy Hungee58e4a2023-07-07 13:47:37 -07002807uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002808NO_THREAD_SAFETY_ANALYSIS
2809// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002810{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002811 uint32_t latency;
2812 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2813 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002814 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002815 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002816}
2817
Andy Hungee58e4a2023-07-07 13:47:37 -07002818void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002819{
Andy Hung972bec12023-08-31 16:13:39 -07002820 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002821 // Don't apply master volume in SW if our HAL can do it for us.
2822 if (mOutput && mOutput->audioHwDev &&
2823 mOutput->audioHwDev->canSetMasterVolume()) {
2824 mMasterVolume = 1.0;
2825 } else {
2826 mMasterVolume = value;
2827 }
2828}
2829
Andy Hungee58e4a2023-07-07 13:47:37 -07002830void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002831{
2832 mMasterBalance.store(balance);
2833}
2834
Andy Hungee58e4a2023-07-07 13:47:37 -07002835void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002836{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002837 if (isDuplicating()) {
2838 return;
2839 }
Andy Hung972bec12023-08-31 16:13:39 -07002840 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002841 // Don't apply master mute in SW if our HAL can do it for us.
2842 if (mOutput && mOutput->audioHwDev &&
2843 mOutput->audioHwDev->canSetMasterMute()) {
2844 mMasterMute = false;
2845 } else {
2846 mMasterMute = muted;
2847 }
2848}
2849
Vlad Popa1e865e62024-08-15 19:11:42 -07002850void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002851{
Vlad Popa1e865e62024-08-15 19:11:42 -07002852 ALOGV("%s: stream %d value %f muted %d", __func__, stream, value, muted);
Andy Hung972bec12023-08-31 16:13:39 -07002853 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002854 mStreamTypes[stream].volume = value;
Vlad Popa1e865e62024-08-15 19:11:42 -07002855 if (com_android_media_audio_ring_my_car()) {
2856 mStreamTypes[stream].mute = muted;
2857 }
Eric Laurentede6c3b2013-09-19 14:37:46 -07002858 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002859}
2860
Andy Hungee58e4a2023-07-07 13:47:37 -07002861void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002862{
Andy Hung972bec12023-08-31 16:13:39 -07002863 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002864 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002865 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002866}
2867
Andy Hungee58e4a2023-07-07 13:47:37 -07002868float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002869{
Andy Hung972bec12023-08-31 16:13:39 -07002870 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002871 return mStreamTypes[stream].volume;
2872}
2873
Andy Hung6b137d12024-08-27 22:35:17 +00002874status_t PlaybackThread::setPortsVolume(
Vlad Popa1e865e62024-08-15 19:11:42 -07002875 const std::vector<audio_port_handle_t>& portIds, float volume, bool muted) {
Andy Hung6b137d12024-08-27 22:35:17 +00002876 audio_utils::lock_guard _l(mutex());
2877 for (const auto& portId : portIds) {
2878 for (size_t i = 0; i < mTracks.size(); i++) {
2879 sp<IAfTrack> track = mTracks[i].get();
2880 if (portId == track->portId()) {
2881 track->setPortVolume(volume);
Vlad Popa1e865e62024-08-15 19:11:42 -07002882 track->setPortMute(muted);
Andy Hung6b137d12024-08-27 22:35:17 +00002883 break;
2884 }
2885 }
2886 }
2887 broadcast_l();
2888 return NO_ERROR;
2889}
2890
Andy Hungee58e4a2023-07-07 13:47:37 -07002891void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002892{
2893 mOutput->stream->setVolume(left, right);
2894}
2895
Andy Hungc5007f82023-08-29 14:26:09 -07002896// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002897status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002898{
2899 status_t status = ALREADY_EXISTS;
2900
Eric Laurent81784c32012-11-19 14:55:58 -08002901 if (mActiveTracks.indexOf(track) < 0) {
2902 // the track is newly added, make sure it fills up all its
2903 // buffers before playing. This is to ensure the client will
2904 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002905 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002906 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002907 // Because the track is not on the ActiveTracks,
2908 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002909 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002910 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002911 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002912 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002913 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002914 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002915 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002916 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002917 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002918 }
2919 return INVALID_OPERATION;
2920 }
2921 // abort if start is rejected by audio policy manager
2922 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002923 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2924 // current playback thread is reopened, which may happen when clients set preferred
2925 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2926 // immediately.
2927 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002928 }
2929#ifdef ADD_BATTERY_DATA
2930 // to track the speaker usage
2931 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2932#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002933 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002934 }
2935
Eric Laurent51716182016-02-29 18:00:56 -08002936 // set retry count for buffer fill
2937 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002938 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002939 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002940 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002941 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002942 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002943 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002944 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002945 track->retryCount() = kMaxTrackStartupRetries;
2946 track->fillingStatus() =
2947 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002948 }
2949
Andy Hung116bc262023-06-20 18:56:17 -07002950 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002951 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2952 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002953 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002954 // Unlock due to VibratorService will lock for this call and will
2955 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002956 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002957 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002958 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002959 std::optional<media::AudioVibratorInfo> vibratorInfo;
2960 {
2961 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2962 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002963 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Yi Kong3ac211f2024-08-12 07:31:44 +08002964 vibratorInfo = mAfThreadCallback->getDefaultVibratorInfo_l();
Lais Andradebc3f37a2021-07-02 00:13:19 +01002965 }
Andy Hungc5007f82023-08-29 14:26:09 -07002966 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002967 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002968 if (vibratorInfo) {
2969 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2970 }
2971
jiabin57303cc2018-12-18 15:45:57 -08002972 // Haptic playback should be enabled by vibrator service.
2973 if (track->getHapticPlaybackEnabled()) {
2974 // Disable haptic playback of all active track to ensure only
2975 // one track playing haptic if current track should play haptic.
2976 for (const auto &t : mActiveTracks) {
2977 t->setHapticPlaybackEnabled(false);
2978 }
jiabin245cdd92018-12-07 17:55:15 -08002979 }
jiabine70bc7f2020-06-30 22:07:55 -07002980
2981 // Set haptic intensity for effect
2982 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002983 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002984 }
jiabin245cdd92018-12-07 17:55:15 -08002985 }
2986
Andy Hung8d31fd22023-06-26 19:20:57 -07002987 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002988 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002989
2990 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2991 // all key changes are complete. It is possible that the threadLoop will begin
2992 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002993 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002994
Eric Laurentd0107bc2013-06-11 14:38:48 -07002995 if (chain != 0) {
2996 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2997 track->sessionId());
2998 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002999 }
3000
Andy Hungc2b11cb2020-04-22 09:04:01 -07003001 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08003002 status = NO_ERROR;
3003 }
3004
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08003005 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08003006 return status;
3007}
3008
Andy Hungee58e4a2023-07-07 13:47:37 -07003009bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003010{
Eric Laurentbfb1b832013-01-07 09:53:42 -08003011 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08003012 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003013 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07003014 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003015 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08003016 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07003017 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07003018 if (track->isPausePending()) {
3019 track->pauseAck();
3020 }
Andy Hung8d31fd22023-06-26 19:20:57 -07003021 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08003022 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003023
3024 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08003025}
3026
Andy Hungee58e4a2023-07-07 13:47:37 -07003027void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08003028{
3029 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08003030
Andy Hung2c6c3bb2017-06-16 14:01:45 -07003031 String8 result;
3032 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003033 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08003034
Eric Laurent81784c32012-11-19 14:55:58 -08003035 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07003036 {
Andy Hung972bec12023-08-31 16:13:39 -07003037 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003038 mAudioTrackCallbacks.erase(track);
3039 }
Eric Laurent81784c32012-11-19 14:55:58 -08003040 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003041 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003042 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003043 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3044 mFastTrackAvailMask |= 1 << index;
3045 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003046 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003047 }
Andy Hung116bc262023-06-20 18:56:17 -07003048 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003049 if (chain != 0) {
3050 chain->decTrackCnt();
3051 }
3052}
3053
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003054std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3055{
3056 std::set<int32_t> result;
3057 for (const auto& t : mTracks) {
3058 if (t->isExternalTrack()) {
3059 result.insert(t->portId());
3060 }
3061 }
3062 return result;
3063}
3064
3065std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3066{
3067 audio_utils::lock_guard _l(mutex());
3068 return getTrackPortIds_l();
3069}
3070
Andy Hungee58e4a2023-07-07 13:47:37 -07003071String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003072{
Andy Hung972bec12023-08-31 16:13:39 -07003073 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003074 String8 out_s8;
3075 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3076 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003077 }
Andy Hung920f6572022-10-06 12:09:49 -07003078 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003079}
3080
Andy Hungee58e4a2023-07-07 13:47:37 -07003081status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003082 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003083 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003084 return NO_INIT;
3085 }
3086 return mOutput->stream->selectPresentation(presentationId, programId);
3087}
3088
Andy Hungab65b182023-09-06 19:41:47 -07003089void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003090 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003091 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003092 sp<AudioIoDescriptor> desc;
3093 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003094 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003095 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003096 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003097 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003098 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3099 mSampleRate, mFormat, mChannelMask,
3100 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3101 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003102 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003103 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003104 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003105 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003106 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003107 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003108 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003109 break;
3110 }
Andy Hungab65b182023-09-06 19:41:47 -07003111 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003112}
3113
Andy Hungee58e4a2023-07-07 13:47:37 -07003114void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003115{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003116 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003117}
3118
Andy Hungee58e4a2023-07-07 13:47:37 -07003119void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003120{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003121 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003122}
3123
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003124void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003125{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003126 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003127}
3128
Andy Hungee58e4a2023-07-07 13:47:37 -07003129void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003130 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003131{
Andy Hungee58e4a2023-07-07 13:47:37 -07003132 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003133 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003134 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003135 if (playbackThread == nullptr) {
3136 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3137 return;
3138 }
3139
jiabinf6eb4c32020-02-25 14:06:25 -08003140 audio_utils::metadata::Data metadata =
3141 audio_utils::metadata::dataFromByteString(metadataBs);
3142 if (metadata.empty()) {
3143 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3144 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3145 (int)metadataBs.size());
3146 return;
3147 }
3148
3149 audio_utils::metadata::ByteString metaDataStr =
3150 audio_utils::metadata::byteStringFromData(metadata);
3151 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003152 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003153 for (const auto& callbackPair : mAudioTrackCallbacks) {
3154 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003155 }
3156 }).detach();
3157}
3158
Andy Hungee58e4a2023-07-07 13:47:37 -07003159void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003160{
Andy Hung972bec12023-08-31 16:13:39 -07003161 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003162 // reject out of sequence requests
3163 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3164 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003165 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003166 }
3167}
3168
Andy Hungee58e4a2023-07-07 13:47:37 -07003169void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003170{
Andy Hung972bec12023-08-31 16:13:39 -07003171 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003172 // reject out of sequence requests
3173 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003174 // Register discontinuity when HW drain is completed because that can cause
3175 // the timestamp frame position to reset to 0 for direct and offload threads.
3176 // (Out of sequence requests are ignored, since the discontinuity would be handled
3177 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003178 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003179 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003180 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003181 }
3182}
3183
Andy Hungee58e4a2023-07-07 13:47:37 -07003184void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003185NO_THREAD_SAFETY_ANALYSIS
3186// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003187{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003188 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003189 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3190 mSampleRate = audioConfig.sample_rate;
3191 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003192 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003193 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003194 }
Andy Hung81994d62023-07-20 21:44:14 -07003195 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003196 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3197 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003198 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003199
3200 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3201 mMixerChannelMask = mChannelMask;
3202 }
3203
Andy Hunge5412692014-05-16 11:25:07 -07003204 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003205 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003206
Eric Laurentf1f22e72021-07-13 14:04:14 +02003207 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3208
Phil Burkca5e6142015-07-14 09:42:29 -07003209 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003210 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003211 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003212 // Get format from the shim, which will be different than the HAL format
3213 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003214 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003215 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003216 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003217 }
Andy Hung81994d62023-07-20 21:44:14 -07003218 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003219 LOG_FATAL("HAL format %#x not supported for mixed output",
3220 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003221 }
Phil Burk062e67a2015-02-11 13:40:50 -08003222 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003223 result = mOutput->stream->getBufferSize(&mBufferSize);
3224 LOG_ALWAYS_FATAL_IF(result != OK,
3225 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003226 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003227 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003228 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003229 mFrameCount);
3230 }
3231
Eric Laurentd1f69b02014-12-15 14:33:13 -08003232 mHwSupportsPause = false;
3233 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003234 bool supportsPause = false, supportsResume = false;
3235 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3236 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003237 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003238 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003239 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003240 } else if (supportsResume) {
3241 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003242 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003243 }
3244 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003245 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3246 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3247 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003248
Andy Hungfbfc3952015-01-15 13:33:51 -08003249 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3250 // For best precision, we use float instead of the associated output
3251 // device format (typically PCM 16 bit).
3252
3253 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3254 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3255 mBufferSize = mFrameSize * mFrameCount;
3256
3257 // TODO: We currently use the associated output device channel mask and sample rate.
3258 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3259 // (if a valid mask) to avoid premature downmix.
3260 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3261 // instead of the output device sample rate to avoid loss of high frequency information.
3262 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3263 }
3264
Andy Hung09a50072014-02-27 14:30:47 -08003265 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003266 double multiplier = 1.0;
Henrik Tillman470b3992024-10-08 12:49:28 +02003267 // Note: mType == SPATIALIZER does not support FastMixer and DEEP is by definition not "fast"
3268 if ((mType == MIXER && !(mOutput->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) &&
3269 (kUseFastMixer == FastMixer_Static || kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003270 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3271 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003272
Eric Laurent81784c32012-11-19 14:55:58 -08003273 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3274 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3275 maxNormalFrameCount = maxNormalFrameCount & ~15;
3276 if (maxNormalFrameCount < minNormalFrameCount) {
3277 maxNormalFrameCount = minNormalFrameCount;
3278 }
3279 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3280 if (multiplier <= 1.0) {
3281 multiplier = 1.0;
3282 } else if (multiplier <= 2.0) {
3283 if (2 * mFrameCount <= maxNormalFrameCount) {
3284 multiplier = 2.0;
3285 } else {
3286 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3287 }
3288 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003289 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003290 }
3291 }
3292 mNormalFrameCount = multiplier * mFrameCount;
3293 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003294 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003295 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3296 }
Andy Hungab65b182023-09-06 19:41:47 -07003297 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3298 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003299
Andy Hung08fb1742015-05-31 23:22:10 -07003300 // Check if we want to throttle the processing to no more than 2x normal rate
3301 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003302 mThreadThrottleTimeMs = 0;
3303 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003304 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3305
Andy Hung010a1a12014-03-13 13:57:33 -07003306 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3307 // Originally this was int16_t[] array, need to remove legacy implications.
3308 free(mSinkBuffer);
3309 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003310
Andy Hung5b10a202014-03-13 13:59:29 -07003311 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3312 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3313 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003314 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003315
Andy Hung69aed5f2014-02-25 17:24:40 -08003316 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3317 // drives the output.
3318 free(mMixerBuffer);
3319 mMixerBuffer = NULL;
3320 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003321 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003322 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003323 * audio_bytes_per_sample(mMixerBufferFormat);
3324 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3325 }
Andy Hung98ef9782014-03-04 14:46:50 -08003326 free(mEffectBuffer);
3327 mEffectBuffer = NULL;
3328 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003329 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003330 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003331 * audio_bytes_per_sample(mEffectBufferFormat);
3332 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3333 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003334
Eric Laurentb62d0362021-10-26 17:40:18 +02003335 if (mType == SPATIALIZER) {
3336 free(mPostSpatializerBuffer);
3337 mPostSpatializerBuffer = nullptr;
3338 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3339 * audio_bytes_per_sample(mEffectBufferFormat);
3340 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3341 }
3342
Mikhail Naganov55773032020-10-01 15:08:13 -07003343 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3344 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003345 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3346 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003347 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003348
Eric Laurent81784c32012-11-19 14:55:58 -08003349 // force reconfiguration of effect chains and engines to take new buffer size and audio
3350 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003351 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003352 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3353 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003354 // create a copy of mEffectChains as calling moveEffectChain_ll()
3355 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003356 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003357 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003358 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003359 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003360 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003361
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003362 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003363 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003364 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003365 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003366 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3367 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3368 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3369 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3370 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3371 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3372 (int32_t)mHapticChannelMask)
3373 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3374 (int32_t)mHapticChannelCount)
3375 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003376 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003377 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3378 (int32_t)mFrameCount) // sic - added HAL
3379 ;
3380 uint32_t latencyMs;
3381 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3382 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3383 }
3384 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003385}
3386
Andy Hungee58e4a2023-07-07 13:47:37 -07003387ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003388{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003389 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003390 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003391 }
3392 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003393 static const bool stereo_spatialization_property =
3394 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3395 const bool stereo_spatialization_enabled =
3396 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3397 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003398 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3399 for (const sp<IAfTrack>& track : mActiveTracks) {
3400 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3401 allSessionsMetadata[track->sessionId()];
3402 auto backInserter = std::back_inserter(sessionMetadata);
3403 // No track is invalid as this is called after prepareTrack_l in the same
3404 // critical section
3405 track->copyMetadataTo(backInserter);
3406 }
3407 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3408 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3409 metadata.tracks.insert(metadata.tracks.end(),
3410 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3411 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3412 chain->sendMetadata_l(sessionTrackMetadata, {});
3413 }
3414 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3415 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3416 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3417 }
3418 }
3419 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3420 chain->sendMetadata_l(metadata.tracks, {});
3421 }
3422 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3423 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3424 }
3425 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3426 chain->sendMetadata_l(metadata.tracks, {});
3427 }
3428 } else {
3429 auto backInserter = std::back_inserter(metadata.tracks);
3430 for (const sp<IAfTrack>& track : mActiveTracks) {
3431 // No track is invalid as this is called after prepareTrack_l in the same
3432 // critical section
3433 track->copyMetadataTo(backInserter);
3434 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003435 }
Kevin Rocard12381092018-04-11 09:19:59 -07003436 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003437 MetadataUpdate change;
3438 change.playbackMetadataUpdate = metadata.tracks;
3439 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003440}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003441
Andy Hungee58e4a2023-07-07 13:47:37 -07003442void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003443 const StreamOutHalInterface::SourceMetadata& metadata)
3444{
3445 mOutput->stream->updateSourceMetadata(metadata);
3446};
3447
Andy Hungee58e4a2023-07-07 13:47:37 -07003448status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003449 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003450{
3451 if (halFrames == NULL || dspFrames == NULL) {
3452 return BAD_VALUE;
3453 }
Andy Hung972bec12023-08-31 16:13:39 -07003454 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003455 if (initCheck() != NO_ERROR) {
3456 return INVALID_OPERATION;
3457 }
Andy Hung818e7a32016-02-16 18:08:07 -08003458 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003459 *halFrames = framesWritten;
3460
3461 if (isSuspended()) {
3462 // return an estimation of rendered frames when the output is suspended
3463 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003464 *dspFrames = (uint32_t)
3465 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003466 return NO_ERROR;
3467 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003468 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003469 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003470 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003471 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003472 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003473 }
3474}
3475
Andy Hungee58e4a2023-07-07 13:47:37 -07003476product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003477{
3478 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3479 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3480 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003481 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003482 }
3483 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003484 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003485 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003486 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003487 }
3488 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003489 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003490}
3491
3492
Andy Hungee58e4a2023-07-07 13:47:37 -07003493AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003494{
Andy Hung972bec12023-08-31 16:13:39 -07003495 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003496 return mOutput;
3497}
3498
Andy Hungee58e4a2023-07-07 13:47:37 -07003499AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003500{
Andy Hung972bec12023-08-31 16:13:39 -07003501 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003502 AudioStreamOut *output = mOutput;
3503 mOutput = NULL;
3504 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3505 // must push a NULL and wait for ack
3506 mOutputSink.clear();
3507 mPipeSink.clear();
3508 mNormalSink.clear();
3509 return output;
3510}
3511
Andy Hungc5007f82023-08-29 14:26:09 -07003512// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003513sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003514{
3515 if (mOutput == NULL) {
3516 return NULL;
3517 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003518 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003519}
3520
Andy Hungee58e4a2023-07-07 13:47:37 -07003521uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003522{
3523 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3524}
3525
Andy Hungee58e4a2023-07-07 13:47:37 -07003526status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003527{
3528 if (!isValidSyncEvent(event)) {
3529 return BAD_VALUE;
3530 }
3531
Andy Hung972bec12023-08-31 16:13:39 -07003532 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003533
3534 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003535 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003536 if (event->triggerSession() == track->sessionId()) {
3537 (void) track->setSyncEvent(event);
3538 return NO_ERROR;
3539 }
3540 }
3541
3542 return NAME_NOT_FOUND;
3543}
3544
Andy Hungee58e4a2023-07-07 13:47:37 -07003545bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003546{
3547 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3548}
3549
Andy Hungee58e4a2023-07-07 13:47:37 -07003550void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003551 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003552{
Andy Hungfe726a62018-09-27 15:17:25 -07003553 // Miscellaneous track cleanup when removed from the active list,
3554 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003555#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003556 for (const auto& track : tracksToRemove) {
3557 if (track->isExternalTrack()) {
3558 // to track the speaker usage
3559 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003560 }
3561 }
Andy Hungfe726a62018-09-27 15:17:25 -07003562#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003563}
3564
Andy Hungee58e4a2023-07-07 13:47:37 -07003565void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003566{
Atneya Nair967c85f2024-10-27 16:09:50 -07003567 if (property_get_bool("ro.audio.silent", false)) {
3568 ALOGW("ro.audio.silent is now ignored");
Eric Laurent81784c32012-11-19 14:55:58 -08003569 }
3570}
3571
3572// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003573ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003574{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003575 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003576 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003577 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003578 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003579
3580 // If an NBAIO sink is present, use it to write the normal mixer's submix
3581 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003582
Andy Hung010a1a12014-03-13 13:57:33 -07003583 const size_t count = mBytesRemaining / mFrameSize;
3584
Simon Wilson2d590962012-11-29 15:18:50 -08003585 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003586 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003587 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003588 if (screenState != mScreenState) {
3589 mScreenState = screenState;
3590 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3591 if (pipe != NULL) {
3592 pipe->setAvgFrames((mScreenState & 1) ?
3593 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3594 }
3595 }
Andy Hung010a1a12014-03-13 13:57:33 -07003596 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003597 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003598
Eric Laurent81784c32012-11-19 14:55:58 -08003599 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003600 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003601
Andy Hung8946a282018-04-19 20:04:56 -07003602#ifdef TEE_SINK
3603 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3604#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003605 } else {
3606 bytesWritten = framesWritten;
3607 }
3608 // otherwise use the HAL / AudioStreamOut directly
3609 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003610 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003611
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003613 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3614 mWriteAckSequence += 2;
3615 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003616 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003617 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003619 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003620 // FIXME We should have an implementation of timestamps for direct output threads.
3621 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003622 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003623 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003624
Eric Laurentbfb1b832013-01-07 09:53:42 -08003625 if (mUseAsyncWrite &&
3626 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3627 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003628 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003629 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003630 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003631 }
Eric Laurent81784c32012-11-19 14:55:58 -08003632 }
3633
Eric Laurent81784c32012-11-19 14:55:58 -08003634 mNumWrites++;
3635 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003636 if (mStandby) {
3637 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003638 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003639 mStandby = false;
3640 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003641 return bytesWritten;
3642}
3643
Andy Hungc5007f82023-08-29 14:26:09 -07003644// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003645void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003646 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003647{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003648 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003649 if (outputSink != nullptr) {
3650 outputSink->startMelComputation(processor);
3651 }
Vlad Popab042ee62022-10-20 18:05:00 +02003652}
3653
Andy Hungc5007f82023-08-29 14:26:09 -07003654// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003655void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003656{
3657 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003658 if (outputSink != nullptr) {
3659 outputSink->stopMelComputation();
3660 }
Vlad Popab042ee62022-10-20 18:05:00 +02003661}
3662
Andy Hungee58e4a2023-07-07 13:47:37 -07003663void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003664{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003665 bool supportsDrain = false;
3666 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003667 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3668 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003669 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3670 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003671 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003672 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003673 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003674 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003675 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003676 }
3677}
3678
Andy Hungee58e4a2023-07-07 13:47:37 -07003679void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003680{
Eric Laurent275e8e92014-11-30 15:14:47 -08003681 {
Andy Hung972bec12023-08-31 16:13:39 -07003682 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003683 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003684 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003685 track->invalidate();
3686 }
Andy Hungdae27702016-10-31 14:01:16 -07003687 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3688 // After we exit there are no more track changes sent to BatteryNotifier
3689 // because that requires an active threadLoop.
3690 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3691 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003692 }
Eric Laurent81784c32012-11-19 14:55:58 -08003693}
3694
3695/*
3696The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003697 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003698 - mActiveSleepTimeUs from activeSleepTimeUs()
3699 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003700 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3701 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003702 - maxPeriod from frame count and sample rate (MIXER only)
3703
3704The parameters that affect these derived values are:
3705 - frame count
3706 - frame size
3707 - sample rate
3708 - device type: A2DP or not
3709 - device latency
3710 - format: PCM or not
3711 - active sleep time
3712 - idle sleep time
3713*/
3714
Andy Hungee58e4a2023-07-07 13:47:37 -07003715void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003716{
Andy Hung25c2dac2014-02-27 14:56:00 -08003717 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003718 mActiveSleepTimeUs = activeSleepTimeUs();
3719 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003720
Andy Hung8fe87eb2023-07-20 21:31:38 -07003721 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003722
Eric Laurent42537be2016-01-08 17:16:42 -08003723 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3724 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003725 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003726 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3727 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3728 }
3729 }
Eric Laurent81784c32012-11-19 14:55:58 -08003730}
3731
Andy Hungee58e4a2023-07-07 13:47:37 -07003732bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003733{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003734 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003735 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003736 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003737 size_t size = mTracks.size();
3738 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003739 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003740 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003741 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003742 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003743 }
3744 }
Eric Laurent13084622016-05-17 10:51:49 -07003745 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003746}
3747
Andy Hungee58e4a2023-07-07 13:47:37 -07003748void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003749{
Andy Hung972bec12023-08-31 16:13:39 -07003750 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003751 invalidateTracks_l(streamType);
3752}
3753
Andy Hungee58e4a2023-07-07 13:47:37 -07003754void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003755 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003756 invalidateTracks_l(portIds);
3757}
3758
Andy Hungee58e4a2023-07-07 13:47:37 -07003759bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003760 bool trackMatch = false;
3761 const size_t size = mTracks.size();
3762 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003763 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003764 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3765 t->invalidate();
3766 portIds.erase(t->portId());
3767 trackMatch = true;
3768 }
3769 if (portIds.empty()) {
3770 break;
3771 }
3772 }
3773 return trackMatch;
3774}
3775
jiabinf042b9b2021-05-07 23:46:28 +00003776// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003777IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003778 audio_port_handle_t trackPortId) {
3779 for (size_t i = 0; i < mTracks.size(); i++) {
3780 if (mTracks[i]->portId() == trackPortId) {
3781 return mTracks[i].get();
3782 }
3783 }
3784 return nullptr;
3785}
3786
Andy Hungee58e4a2023-07-07 13:47:37 -07003787status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003788{
Glenn Kastend848eb42016-03-08 13:42:11 -08003789 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003790 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003791 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003792
Andy Hungd3639922022-04-28 18:00:49 -07003793 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003794 if (!audio_is_global_session(session)) {
3795 // player sessions on a spatializer output will use a dedicated input buffer and
3796 // will either output multi channel to mEffectBuffer if the track is spatilaized
3797 // or stereo to mPostSpatializerBuffer if not spatialized.
3798 uint32_t channelMask;
3799 bool isSessionSpatialized =
3800 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3801 if (isSessionSpatialized) {
3802 channelMask = mMixerChannelMask;
3803 } else {
3804 channelMask = mChannelMask;
3805 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003806 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003807 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003808 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003809 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003810 &halInBuffer);
3811 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003812
Andy Hung583043b2023-07-17 17:05:00 -07003813 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003814 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3815 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3816 &halOutBuffer);
3817 if (result != OK) return result;
3818
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003819 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003820
Mikhail Naganov022b9952017-01-04 16:36:51 -08003821 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3822 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003823 } else {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003824 status_t result = INVALID_OPERATION;
3825 // Buffer configuration for global sessions on a SPATIALIZER thread:
3826 // - AUDIO_SESSION_OUTPUT_MIX session uses the mEffectBuffer as input and output buffer
3827 // - AUDIO_SESSION_OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3828 // mPostSpatializerBuffer as output buffer
3829 // - AUDIO_SESSION_DEVICE session uses the mPostSpatializerBuffer as input and output
3830 // buffer
3831 if (session == AUDIO_SESSION_OUTPUT_MIX || session == AUDIO_SESSION_OUTPUT_STAGE) {
3832 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3833 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3834 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003835
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003836 if (session == AUDIO_SESSION_OUTPUT_MIX) {
3837 halOutBuffer = halInBuffer;
3838 }
3839 }
3840
3841 if (session == AUDIO_SESSION_OUTPUT_STAGE || session == AUDIO_SESSION_DEVICE) {
3842 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
3843 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3844 if (result != OK) return result;
3845
3846 if (session == AUDIO_SESSION_DEVICE) {
3847 halInBuffer = halOutBuffer;
3848 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003849 }
3850 }
3851 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003852 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003853 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3854 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3855 &halInBuffer);
3856 if (result != OK) return result;
3857 halOutBuffer = halInBuffer;
3858 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3859 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003860 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003861 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003862 // Only one effect chain can be present in direct output thread and it uses
3863 // the sink buffer as input
3864 if (mType != DIRECT) {
3865 size_t numSamples = mNormalFrameCount
3866 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3867 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003868 const status_t allocateStatus =
3869 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003870 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003871 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003872 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003873
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003874 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003875 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3876 buffer, session);
3877 }
3878 }
3879 }
3880
3881 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003882 // Attach all tracks with same session ID to this chain.
3883 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003884 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003885 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003886 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3887 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003888 track->setMainBuffer(buffer);
3889 chain->incTrackCnt();
3890 }
3891 }
3892
3893 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003894 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003895 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003896 ALOGV("addEffectChain_l() activating track %p on session %d",
3897 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003898 chain->incActiveTrackCnt();
3899 }
3900 }
3901 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003902
Eric Laurentaaa44472014-09-12 17:41:50 -07003903 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003904 chain->setInBuffer(halInBuffer);
3905 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003906 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3907 // chains list in order to be processed last as it contains output device effects.
3908 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3909 // processing effects specific to an output stream before effects applied to all streams
3910 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003911 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3912 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003913 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003914 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003915 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003916 // Effect chain for other sessions are inserted at beginning of effect
3917 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003918 // sessions is not important.
3919 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003920 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3921 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003922 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003923 size_t size = mEffectChains.size();
3924 size_t i = 0;
3925 for (i = 0; i < size; i++) {
3926 if (mEffectChains[i]->sessionId() < session) {
3927 break;
3928 }
3929 }
3930 mEffectChains.insertAt(chain, i);
3931 checkSuspendOnAddEffectChain_l(chain);
3932
3933 return NO_ERROR;
3934}
3935
Andy Hungee58e4a2023-07-07 13:47:37 -07003936size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003937{
Glenn Kastend848eb42016-03-08 13:42:11 -08003938 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003939
3940 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3941
3942 for (size_t i = 0; i < mEffectChains.size(); i++) {
3943 if (chain == mEffectChains[i]) {
3944 mEffectChains.removeAt(i);
3945 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003946 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003947 if (session == track->sessionId()) {
3948 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3949 chain.get(), session);
3950 chain->decActiveTrackCnt();
3951 }
3952 }
3953
3954 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003955 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003956 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003957 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003958 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003959 chain->decTrackCnt();
3960 }
3961 }
3962 break;
3963 }
3964 }
3965 return mEffectChains.size();
3966}
3967
Andy Hungee58e4a2023-07-07 13:47:37 -07003968status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003969 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003970{
Andy Hung972bec12023-08-31 16:13:39 -07003971 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003972 return attachAuxEffect_l(track, EffectId);
3973}
3974
Andy Hungee58e4a2023-07-07 13:47:37 -07003975status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003976 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003977{
3978 status_t status = NO_ERROR;
3979
3980 if (EffectId == 0) {
3981 track->setAuxBuffer(0, NULL);
3982 } else {
3983 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003984 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003985 if (effect != 0) {
3986 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3987 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3988 } else {
3989 status = INVALID_OPERATION;
3990 }
3991 } else {
3992 status = BAD_VALUE;
3993 }
3994 }
3995 return status;
3996}
3997
Andy Hungee58e4a2023-07-07 13:47:37 -07003998void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003999{
4000 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004001 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004002 if (track->auxEffectId() == effectId) {
4003 attachAuxEffect_l(track, 0);
4004 }
4005 }
4006}
4007
Andy Hungee58e4a2023-07-07 13:47:37 -07004008bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07004009NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08004010{
Andy Hung78d8d952023-05-30 18:10:23 -07004011 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08004012
Andy Hung077d62e2023-10-03 10:49:34 -07004013 if (mType == SPATIALIZER) {
4014 const pid_t tid = getTid();
4015 if (tid == -1) { // odd: we are here, we must be a running thread.
4016 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
4017 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00004018 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
4019 if (priorityBoost > 0) {
4020 stream()->setHalThreadPriority(priorityBoost);
4021 }
Andy Hung077d62e2023-10-03 10:49:34 -07004022 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00004023 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
4024 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
4025 // is not enough for PlaybackThread to process audio data in time. We request the lowest
4026 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
4027 // only on ARC.
4028 const pid_t tid = getTid();
4029 if (tid == -1) {
4030 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
4031 } else {
4032 const status_t status = requestPriority(getpid(),
4033 tid,
4034 kPriorityPlaybackThreadArc,
4035 false /* isForApp */,
4036 true /* asynchronous */);
4037 if (status != OK) {
4038 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4039 status);
4040 } else {
4041 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4042 }
4043 }
Andy Hung077d62e2023-10-03 10:49:34 -07004044 }
4045
Andy Hung8d31fd22023-06-26 19:20:57 -07004046 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004047
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004048 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004049 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004050
4051 // MIXER
4052 nsecs_t lastWarning = 0;
4053
4054 // DUPLICATING
4055 // FIXME could this be made local to while loop?
4056 writeFrames = 0;
4057
Andy Hung3f2cee62024-09-17 14:17:15 -07004058 {
4059 audio_utils::lock_guard l(mutex());
4060
4061 cacheParameters_l();
4062 checkSilentMode_l();
4063 }
4064
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004065 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004066
Andy Hungd3639922022-04-28 18:00:49 -07004067 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004068 sleepTimeShift = 0;
4069 }
4070
4071 CpuStats cpuStats;
4072 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4073
4074 acquireWakeLock();
4075
Glenn Kasteneef598c2017-04-03 14:41:13 -07004076 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4077 // thread associated with this PlaybackThread.
4078 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4079 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004080 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4081 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004082 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004083 const char *logString = NULL;
4084
rago1bb90822017-05-02 18:31:48 -07004085 // Estimated time for next buffer to be written to hal. This is used only on
4086 // suspended mode (for now) to help schedule the wait time until next iteration.
4087 nsecs_t timeLoopNextNs = 0;
4088
Andy Hung2dbffc22018-08-08 18:50:41 -07004089 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004090
Eric Laurentb3f315a2021-07-13 15:09:05 +02004091 sendCheckOutputStageEffectsEvent();
4092
Andy Hung446f4df2019-02-21 12:26:41 -08004093 // loopCount is used for statistics and diagnostics.
4094 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004095 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004096 // Log merge requests are performed during AudioFlinger binder transactions, but
4097 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004098 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004099
Eric Laurent81784c32012-11-19 14:55:58 -08004100 cpuStats.sample(myName);
4101
Andy Hung116bc262023-06-20 18:56:17 -07004102 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004103 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004104 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004105 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004106
Andy Hung2dbffc22018-08-08 18:50:41 -07004107 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4108 //
Andy Hungc5007f82023-08-29 14:26:09 -07004109 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004110 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004111 // Here, we try for the AF lock, but do not block on it as the latency
4112 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004113 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004114 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004115 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004116 status_t status = INVALID_OPERATION;
4117 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004118 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004119 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004120 && swPatches.size() > 0) {
4121 status = swPatches[0].getLatencyMs_l(&latencyMs);
4122 downstreamPatchHandle = swPatches[0].getPatchHandle();
4123 }
4124 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004125 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004126 lastDownstreamPatchHandle = downstreamPatchHandle;
4127 }
4128 if (status == OK) {
4129 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004130 // latency of 5 seconds).
4131 const double minLatency = 0., maxLatency = 5000.;
4132 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004133 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004134 } else {
4135 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004136 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004137 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004138 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004139 }
Andy Hung583043b2023-07-17 17:05:00 -07004140 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004141 }
4142 } else {
4143 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4144 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004145 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004146 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4147 }
4148 }
4149
Eric Laurentb3f315a2021-07-13 15:09:05 +02004150 if (mCheckOutputStageEffects.exchange(false)) {
4151 checkOutputStageEffects();
4152 }
4153
Vlad Popa7e81cea2023-01-19 16:34:16 +01004154 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004155 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004156
Andy Hungc5007f82023-08-29 14:26:09 -07004157 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004158
Eric Laurent021cf962014-05-13 10:18:14 -07004159 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004160 if (mCheckOutputStageEffects.load()) {
4161 continue;
4162 }
Eric Laurent10351942014-05-08 18:49:52 -07004163
Andy Hungc5007f82023-08-29 14:26:09 -07004164 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004165 if (logString != NULL) {
4166 mNBLogWriter->logTimestamp();
4167 mNBLogWriter->log(logString);
4168 logString = NULL;
4169 }
4170
Dean Wheatley12473e92021-03-18 23:00:55 +11004171 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004172
Eric Laurent81784c32012-11-19 14:55:58 -08004173 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004174 if (mSignalPending) {
4175 // A signal was raised while we were unlocked
4176 mSignalPending = false;
4177 } else if (waitingAsyncCallback_l()) {
4178 if (exitPending()) {
4179 break;
4180 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004181 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004182 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004183 releaseWakeLock_l();
4184 released = true;
4185 }
Andy Hung10cbff12017-02-21 17:30:14 -08004186
4187 const int64_t waitNs = computeWaitTimeNs_l();
4188 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004189 std::cv_status cvstatus =
4190 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4191 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004192 mSignalPending = true; // if timeout recheck everything
4193 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004194 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004195 if (released) {
4196 acquireWakeLock_l();
4197 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004198 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4199 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004200
4201 continue;
4202 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004203 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004204 isSuspended()) {
4205 // put audio hardware into standby after short delay
4206 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004207
4208 threadLoop_standby();
4209
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004210 // This is where we go into standby
4211 if (!mStandby) {
4212 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004213 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004214 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004215 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004216 }
Andy Hungd0979812019-02-21 15:51:44 -08004217 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004218 }
4219
Eric Tan39ec8d62018-07-24 09:49:29 -07004220 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004221 // we're about to wait, flush the binder command buffer
4222 IPCThreadState::self()->flushCommands();
4223
4224 clearOutputTracks();
4225
4226 if (exitPending()) {
4227 break;
4228 }
4229
4230 releaseWakeLock_l();
4231 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004232 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004233 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004234 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004235 acquireWakeLock_l();
4236
4237 mMixerStatus = MIXER_IDLE;
4238 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4239 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004240 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004241 checkSilentMode_l();
4242
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004243 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4244 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004245 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004246 sleepTimeShift = 0;
4247 }
4248
4249 continue;
4250 }
4251 }
Eric Laurent81784c32012-11-19 14:55:58 -08004252 // mMixerStatusIgnoringFastTracks is also updated internally
4253 mMixerStatus = prepareTracks_l(&tracksToRemove);
4254
Andy Hungab65b182023-09-06 19:41:47 -07004255 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004256
Vlad Popa7e81cea2023-01-19 16:34:16 +01004257 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004258
Andy Hungf302e812024-01-26 11:55:15 -08004259 // Acquire a local copy of active tracks with lock (release w/o lock).
4260 //
4261 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4262 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4263 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4264 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4265
4266 setHalLatencyMode_l();
4267
4268 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4269 // so this is done before we lock our effect chains.
4270 for (const auto& track : mActiveTracks) {
4271 track->updateTeePatches_l();
4272 }
4273
4274 // signal actual start of output stream when the render position reported by
4275 // the kernel starts moving.
4276 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4277 && (mKernelPositionOnStandby
4278 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4279 mHalStarted = true;
4280 mWaitHalStartCV.notify_all();
4281 }
4282
Eric Laurent81784c32012-11-19 14:55:58 -08004283 // prevent any changes in effect chain list and in each effect chain
4284 // during mixing and effect process as the audio buffers could be deleted
4285 // or modified if an effect is created or deleted
4286 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004287
4288 // Determine which session to pick up haptic data.
4289 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004290 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004291 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004292 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004293 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004294 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004295 if (effectChain != nullptr
4296 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004297 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004298 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004299 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004300 break;
4301 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004302 if (activeHapticSessionId == AUDIO_SESSION_NONE
4303 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004304 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004305 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004306 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004307 }
4308 }
4309 }
Andy Hungc5007f82023-08-29 14:26:09 -07004310 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004311
Eric Laurentbfb1b832013-01-07 09:53:42 -08004312 if (mBytesRemaining == 0) {
4313 mCurrentWriteLength = 0;
4314 if (mMixerStatus == MIXER_TRACKS_READY) {
4315 // threadLoop_mix() sets mCurrentWriteLength
4316 threadLoop_mix();
4317 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4318 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004319 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004320 // must be written to HAL
4321 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004322 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004323 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004324
4325 // Tally underrun frames as we are inserting 0s here.
4326 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004327 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004328 && !track->isStopped()
4329 && !track->isPaused()
4330 && !track->isTerminated()) {
4331 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4332 __func__, track->id(), track->getTrackStateAsString(),
4333 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004334 track->audioTrackServerProxy()->tallyUnderrunFrames(
4335 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004336 }
4337 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004338 }
4339 }
Andy Hung98ef9782014-03-04 14:46:50 -08004340 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004341 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004342 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004343 // or mSinkBuffer (if there are no effects and there is no data already copied to
4344 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004345 //
4346 // This is done pre-effects computation; if effects change to
4347 // support higher precision, this needs to move.
4348 //
4349 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004350 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004351 uint32_t mixerChannelCount = mEffectBufferValid ?
4352 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004353 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004354 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4355 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4356
David Li88ee0902022-06-22 10:01:21 +08004357 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4358 // do these processes after effects are applied.
4359 if (!mEffectBufferValid) {
4360 // mono blend occurs for mixer threads only (not direct or offloaded)
4361 // and is handled here if we're going directly to the sink.
4362 if (requireMonoBlend()) {
4363 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4364 mNormalFrameCount, true /*limit*/);
4365 }
Andy Hung2ddee192015-12-18 17:34:44 -08004366
David Li88ee0902022-06-22 10:01:21 +08004367 if (!hasFastMixer()) {
4368 // Balance must take effect after mono conversion.
4369 // We do it here if there is no FastMixer.
4370 // mBalance detects zero balance within the class for speed
4371 // (not needed here).
4372 mBalance.setBalance(mMasterBalance.load());
4373 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4374 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004375 }
4376
Andy Hung98ef9782014-03-04 14:46:50 -08004377 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004378 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004379
4380 // If we're going directly to the sink and there are haptic channels,
4381 // we should adjust channels as the sample data is partially interleaved
4382 // in this case.
4383 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4384 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4385 mChannelCount + mHapticChannelCount,
4386 audio_bytes_per_sample(format),
4387 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4388 }
Andy Hung98ef9782014-03-04 14:46:50 -08004389 }
4390
Eric Laurentbfb1b832013-01-07 09:53:42 -08004391 mBytesRemaining = mCurrentWriteLength;
4392 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004393 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4394 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4395 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4396 mBytesWritten += mBytesRemaining;
4397 mFramesWritten += framesRemaining;
4398 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004399 mBytesRemaining = 0;
4400 }
Eric Laurent81784c32012-11-19 14:55:58 -08004401
Eric Laurentbfb1b832013-01-07 09:53:42 -08004402 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004403 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004404 for (size_t i = 0; i < effectChains.size(); i ++) {
4405 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004406 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004407 if (activeHapticSessionId != AUDIO_SESSION_NONE
4408 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004409 // Haptic data is active in this case, copy it directly from
4410 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004411 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4412 audio_channel_count_from_out_mask(mMixerChannelMask) :
4413 mChannelCount;
4414 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4415 hapticSessionChannelCount = mChannelCount;
4416 }
4417
jiabin47affe52019-04-04 18:02:07 -07004418 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004419 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004420 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004421 memcpy_by_audio_format(
4422 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004423 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004424 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004425 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004426 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004427 }
Eric Laurent81784c32012-11-19 14:55:58 -08004428 }
4429 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004430 // Process effect chains for offloaded thread even if no audio
4431 // was read from audio track: process only updates effect state
4432 // and thus does have to be synchronized with audio writes but may have
4433 // to be called while waiting for async write callback
4434 if (mType == OFFLOAD) {
4435 for (size_t i = 0; i < effectChains.size(); i ++) {
4436 effectChains[i]->process_l();
4437 }
4438 }
Eric Laurent81784c32012-11-19 14:55:58 -08004439
Andy Hung98ef9782014-03-04 14:46:50 -08004440 // Only if the Effects buffer is enabled and there is data in the
4441 // Effects buffer (buffer valid), we need to
4442 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004443 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004444 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004445 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004446 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004447 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004448 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004449 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004450 }
4451
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004452 if (!hasFastMixer()) {
4453 // Balance must take effect after mono conversion.
4454 // We do it here if there is no FastMixer.
4455 // mBalance detects zero balance within the class for speed (not needed here).
4456 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004457 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004458 }
4459
Eric Laurentb62d0362021-10-26 17:40:18 +02004460 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4461 // mPostSpatializerBuffer if the haptics track is spatialized.
4462 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4463 // For other thread types, the haptics channels are already in mEffectBuffer.
4464 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4465 const size_t srcBufferSize = mNormalFrameCount *
4466 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4467 mEffectBufferFormat);
4468 const size_t dstBufferSize = mNormalFrameCount
4469 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4470
4471 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4472 mEffectBufferFormat,
4473 (uint8_t*)mEffectBuffer + srcBufferSize,
4474 mEffectBufferFormat,
4475 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004476 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004477 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4478 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4479 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4480 // Clamp PCM float values more than this distance from 0 to insulate
4481 // a HAL which doesn't handle NaN correctly.
4482 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4483 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4484 static_cast<const float*>(effectBuffer),
4485 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4486 } else {
4487 memcpy_by_audio_format(mSinkBuffer, mFormat,
4488 effectBuffer, mEffectBufferFormat, framesToCopy);
4489 }
jiabin245cdd92018-12-07 17:55:15 -08004490 // The sample data is partially interleaved when haptic channels exist,
4491 // we need to adjust channels here.
4492 if (mHapticChannelCount > 0) {
4493 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4494 mChannelCount + mHapticChannelCount,
4495 audio_bytes_per_sample(mFormat),
4496 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4497 }
Andy Hung98ef9782014-03-04 14:46:50 -08004498 }
4499
Eric Laurent81784c32012-11-19 14:55:58 -08004500 // enable changes in effect chain
4501 unlockEffectChains(effectChains);
4502
Vlad Popafce10862023-02-03 10:37:07 +01004503 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004504 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004505 metadataUpdate.playbackMetadataUpdate);
4506 }
4507
Eric Laurentbfb1b832013-01-07 09:53:42 -08004508 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004509 // mSleepTimeUs == 0 means we must write to audio hardware
4510 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004511 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004512 // writePeriodNs is updated >= 0 when ret > 0.
4513 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004514 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004515 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004516 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004517 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004518 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004519 if (ret < 0) {
4520 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004521 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004522 mBytesWritten += ret;
4523 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004524 const int64_t frames = ret / mFrameSize;
4525 mFramesWritten += frames;
4526
4527 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4528 // process information relating to write time.
4529 if (audio_has_proportional_frames(mFormat)) {
4530 // we are in a continuous mixing cycle
4531 if (mMixerStatus == MIXER_TRACKS_READY &&
4532 loopCount == lastLoopCountWritten + 1) {
4533
4534 const double jitterMs =
4535 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4536 {frames, writePeriodNs},
4537 {0, 0} /* lastTimestamp */, mSampleRate);
4538 const double processMs =
4539 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4540
Andy Hung972bec12023-08-31 16:13:39 -07004541 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004542 mIoJitterMs.add(jitterMs);
4543 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004544
4545 if (mPipeSink.get() != nullptr) {
4546 // Using the Monopipe availableToWrite, we estimate the current
4547 // buffer size.
4548 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4549 const ssize_t
4550 availableToWrite = mPipeSink->availableToWrite();
4551 const size_t pipeFrames = monoPipe->maxFrames();
4552 const size_t
4553 remainingFrames = pipeFrames - max(availableToWrite, 0);
4554 mMonopipePipeDepthStats.add(remainingFrames);
4555 }
Andy Hung446f4df2019-02-21 12:26:41 -08004556 }
4557
4558 // write blocked detection
4559 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004560 if ((mType == MIXER || mType == SPATIALIZER)
4561 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004562 mNumDelayedWrites++;
4563 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4564 ATRACE_NAME("underrun");
4565 ALOGW("write blocked for %lld msecs, "
4566 "%d delayed writes, thread %d",
4567 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4568 mNumDelayedWrites, mId);
4569 lastWarning = lastIoEndNs;
4570 }
4571 }
4572 }
4573 // update timing info.
4574 mLastIoBeginNs = lastIoBeginNs;
4575 mLastIoEndNs = lastIoEndNs;
4576 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004577 }
4578 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4579 (mMixerStatus == MIXER_DRAIN_ALL)) {
4580 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004581 }
Andy Hungd3639922022-04-28 18:00:49 -07004582 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004583
4584 if (mThreadThrottle
4585 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004586 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004587 // Limit MixerThread data processing to no more than twice the
4588 // expected processing rate.
4589 //
4590 // This helps prevent underruns with NuPlayer and other applications
4591 // which may set up buffers that are close to the minimum size, or use
4592 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4593 //
4594 // The throttle smooths out sudden large data drains from the device,
4595 // e.g. when it comes out of standby, which often causes problems with
4596 // (1) mixer threads without a fast mixer (which has its own warm-up)
4597 // (2) minimum buffer sized tracks (even if the track is full,
4598 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004599 //
4600 // Total time spent in last processing cycle equals time spent in
4601 // 1. threadLoop_write, as well as time spent in
4602 // 2. threadLoop_mix (significant for heavy mixing, especially
4603 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004604
Andy Hung446f4df2019-02-21 12:26:41 -08004605 // it's OK if deltaMs is an overestimate.
4606
4607 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004608
Ivan Lozanoea04d392017-11-07 14:37:07 -08004609 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004610 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004611 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004612
Andy Hung08fb1742015-05-31 23:22:10 -07004613 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004614 // notify of throttle start on verbose log
4615 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4616 "mixer(%p) throttle begin:"
4617 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004618 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004619 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004620 // Throttle must be attributed to the previous mixer loop's write time
4621 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004622 // This also ensures proper timing statistics.
4623 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004624 } else {
4625 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4626 if (diff > 0) {
4627 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004628 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004629 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004630 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004631 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004632 outDeviceTypes_l(),
4633 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004634 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004635 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4636 }
Andy Hung08fb1742015-05-31 23:22:10 -07004637 }
4638 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004639 }
Eric Laurent81784c32012-11-19 14:55:58 -08004640
Eric Laurentbfb1b832013-01-07 09:53:42 -08004641 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004642 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004643 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004644 // suspended requires accurate metering of sleep time.
4645 if (isSuspended()) {
4646 // advance by expected sleepTime
4647 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4648 const nsecs_t nowNs = systemTime();
4649
4650 // compute expected next time vs current time.
4651 // (negative deltas are treated as delays).
4652 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4653 if (deltaNs < -kMaxNextBufferDelayNs) {
4654 // Delays longer than the max allowed trigger a reset.
4655 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4656 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4657 timeLoopNextNs = nowNs + deltaNs;
4658 } else if (deltaNs < 0) {
4659 // Delays within the max delay allowed: zero the delta/sleepTime
4660 // to help the system catch up in the next iteration(s)
4661 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4662 deltaNs = 0;
4663 }
4664 // update sleep time (which is >= 0)
4665 mSleepTimeUs = deltaNs / 1000;
4666 }
Eric Laurente93cc032016-05-05 10:15:10 -07004667 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004668 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004669 }
Glenn Kastene7754022014-10-31 12:11:26 -07004670 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004671 }
Eric Laurent81784c32012-11-19 14:55:58 -08004672 }
4673
4674 // Finally let go of removed track(s), without the lock held
4675 // since we can't guarantee the destructors won't acquire that
4676 // same lock. This will also mutate and push a new fast mixer state.
4677 threadLoop_removeTracks(tracksToRemove);
4678 tracksToRemove.clear();
4679
4680 // FIXME I don't understand the need for this here;
4681 // it was in the original code but maybe the
4682 // assignment in saveOutputTracks() makes this unnecessary?
4683 clearOutputTracks();
4684
4685 // Effect chains will be actually deleted here if they were removed from
4686 // mEffectChains list during mixing or effects processing
4687 effectChains.clear();
4688
4689 // FIXME Note that the above .clear() is no longer necessary since effectChains
4690 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004691
4692 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004693 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004694 mThreadloopExecutor.process(); // process any remaining deferred actions.
4695 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004696
Eric Laurentbfb1b832013-01-07 09:53:42 -08004697 threadLoop_exit();
4698
Eric Laurentcf817a22014-08-04 20:36:31 -07004699 if (!mStandby) {
4700 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004701 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004702 }
4703
4704 releaseWakeLock();
4705
4706 ALOGV("Thread %p type %d exiting", this, mType);
4707 return false;
4708}
4709
Andy Hungee58e4a2023-07-07 13:47:37 -07004710void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004711{
Dean Wheatley12473e92021-03-18 23:00:55 +11004712 if (mStandby) {
4713 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4714 return;
4715 } else if (mHwPaused) {
4716 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4717 return;
4718 }
4719
4720 // Gather the framesReleased counters for all active tracks,
4721 // and associate with the sink frames written out. We need
4722 // this to convert the sink timestamp to the track timestamp.
4723 bool kernelLocationUpdate = false;
4724 ExtendedTimestamp timestamp; // use private copy to fetch
4725
4726 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4727 // HAL may be draining some small duration buffered data for fade out.
4728 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4729 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4730 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4731 mSampleRate);
4732
Andy Hungab65b182023-09-06 19:41:47 -07004733 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004734 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4735 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4736 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4737 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4738 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4739 = correctedTimestamp.mFrames;
4740 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4741 = correctedTimestamp.mTimeNs;
4742 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4743 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4744 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4745
4746 // Note: Downstream latency only added if timestamp correction enabled.
4747 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4748 const int64_t newPosition =
4749 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4750 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4751 // prevent retrograde
4752 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4753 newPosition,
4754 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4755 - mSuspendedFrames));
4756 }
4757 }
4758
4759 // We always fetch the timestamp here because often the downstream
4760 // sink will block while writing.
4761
4762 // We keep track of the last valid kernel position in case we are in underrun
4763 // and the normal mixer period is the same as the fast mixer period, or there
4764 // is some error from the HAL.
4765 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4766 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4767 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4768 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4769 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4770
4771 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4772 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4773 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4774 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4775 }
4776
4777 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4778 kernelLocationUpdate = true;
4779 } else {
4780 ALOGVV("getTimestamp error - no valid kernel position");
4781 }
4782
4783 // copy over kernel info
4784 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4785 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4786 + mSuspendedFrames; // add frames discarded when suspended
4787 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4788 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4789 } else {
4790 mTimestampVerifier.error();
4791 }
4792
4793 // mFramesWritten for non-offloaded tracks are contiguous
4794 // even after standby() is called. This is useful for the track frame
4795 // to sink frame mapping.
4796 bool serverLocationUpdate = false;
4797 if (mFramesWritten != mLastFramesWritten) {
4798 serverLocationUpdate = true;
4799 mLastFramesWritten = mFramesWritten;
4800 }
4801 // Only update timestamps if there is a meaningful change.
4802 // Either the kernel timestamp must be valid or we have written something.
4803 if (kernelLocationUpdate || serverLocationUpdate) {
4804 if (serverLocationUpdate) {
4805 // use the time before we called the HAL write - it is a bit more accurate
4806 // to when the server last read data than the current time here.
4807 //
4808 // If we haven't written anything, mLastIoBeginNs will be -1
4809 // and we use systemTime().
4810 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4811 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004812 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004813 }
4814
Andy Hung8d31fd22023-06-26 19:20:57 -07004815 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004816 if (!t->isFastTrack()) {
4817 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004818 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004819 mFramesWritten,
4820 mSampleRate,
4821 mTimestamp);
4822 }
4823 }
4824 }
4825
4826 if (audio_has_proportional_frames(mFormat)) {
4827 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4828 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4829 mLatencyMs.add(latencyMs);
4830 }
4831 }
4832#if 0
4833 // logFormat example
4834 if (z % 100 == 0) {
4835 timespec ts;
4836 clock_gettime(CLOCK_MONOTONIC, &ts);
4837 LOGT("This is an integer %d, this is a float %f, this is my "
4838 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4839 LOGT("A deceptive null-terminated string %\0");
4840 }
4841 ++z;
4842#endif
4843}
4844
Andy Hungc5007f82023-08-29 14:26:09 -07004845// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004846void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004847NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004848{
Andy Hung6c498e92023-12-05 17:28:17 -08004849 if (tracksToRemove.empty()) return;
4850
4851 // Block all incoming TrackHandle requests until we are finished with the release.
4852 setThreadBusy_l(true);
4853
Andy Hungfe726a62018-09-27 15:17:25 -07004854 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004855 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004856 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004857 if (chain != 0) {
4858 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4859 __func__, track->id(), chain.get(), track->sessionId());
4860 chain->decActiveTrackCnt();
4861 }
Andy Hung6c498e92023-12-05 17:28:17 -08004862
Andy Hungfe726a62018-09-27 15:17:25 -07004863 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004864 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004865 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004866 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004867 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004868 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004869 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004870 }
Andy Hung6c498e92023-12-05 17:28:17 -08004871 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004872 }
jiabineb3bda02020-06-30 14:07:03 -07004873 if (mHapticChannelCount > 0 &&
4874 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004875 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004876 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004877 // Unlock due to VibratorService will lock for this call and will
4878 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004879 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004880 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004881
4882 // When the track is stop, set the haptic intensity as MUTE
4883 // for the HapticGenerator effect.
4884 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004885 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004886 }
jiabin245cdd92018-12-07 17:55:15 -08004887 }
Andy Hung6c498e92023-12-05 17:28:17 -08004888
4889 // Under lock, the track is removed from the active tracks list.
4890 //
4891 // Once the track is no longer active, the TrackHandle may directly
4892 // modify it as the threadLoop() is no longer responsible for its maintenance.
4893 // Do not modify the track from threadLoop after the mutex is unlocked
4894 // if it is not active.
4895 mActiveTracks.remove(track);
4896
4897 if (track->isTerminated()) {
4898 // remove from our tracks vector
4899 removeTrack_l(track);
4900 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004901 }
Andy Hung6c498e92023-12-05 17:28:17 -08004902
4903 // Allow incoming TrackHandle requests. We still hold the mutex,
4904 // so pending TrackHandle requests will occur after we unlock it.
4905 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004906}
Eric Laurent81784c32012-11-19 14:55:58 -08004907
Andy Hungee58e4a2023-07-07 13:47:37 -07004908status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004909{
4910 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004911 ExtendedTimestamp ets;
4912 status_t status = mNormalSink->getTimestamp(ets);
4913 if (status == NO_ERROR) {
4914 status = ets.getBestTimestamp(&timestamp);
4915 }
4916 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004917 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004918 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004919 collectTimestamps_l();
4920 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4921 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004922 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004923 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4924 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4925 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4926 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4927 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004928 }
4929 return INVALID_OPERATION;
4930}
Eric Laurent1c333e22014-05-20 10:48:17 -07004931
Eric Laurenteab90452019-06-24 15:17:46 -07004932// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4933// still applied by the mixer.
4934// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4935// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4936// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004937status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004938{
4939 status_t result = NO_ERROR;
4940 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4941 if (*volume != mLeftVolFloat) {
4942 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004943 // HAL can return INVALID_OPERATION if operation is not supported.
4944 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004945 "Error when setting output stream volume: %d", result);
4946 if (result == NO_ERROR) {
4947 mLeftVolFloat = *volume;
4948 }
4949 }
4950 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4951 // remove stream volume contribution from software volume.
4952 if (mLeftVolFloat == *volume) {
4953 *volume = 1.0f;
4954 }
4955 }
4956 return result;
4957}
4958
Andy Hungee58e4a2023-07-07 13:47:37 -07004959status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004960 audio_patch_handle_t *handle)
4961{
Andy Hungf60abce2016-08-26 11:37:54 -07004962 status_t status;
4963 if (property_get_bool("af.patch_park", false /* default_value */)) {
4964 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4965 // or if HAL does not properly lock against access.
4966 AutoPark<FastMixer> park(mFastMixer);
4967 status = PlaybackThread::createAudioPatch_l(patch, handle);
4968 } else {
4969 status = PlaybackThread::createAudioPatch_l(patch, handle);
4970 }
Eric Laurentb0463942022-12-20 16:31:10 +01004971
4972 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004973 return status;
4974}
4975
Andy Hungee58e4a2023-07-07 13:47:37 -07004976status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004977 audio_patch_handle_t *handle)
4978{
4979 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004980
4981 // store new device and send to effects
4982 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004983 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004984 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004985 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4986 && !mOutput->audioHwDev->supportsAudioPatches(),
4987 "Enumerated device type(%#x) must not be used "
4988 "as it does not support audio patches",
4989 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004990 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004991 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4992 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004993 }
4994
François Gaffie0c280aa2018-07-25 10:02:15 +02004995 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004996#ifdef ADD_BATTERY_DATA
4997 // when changing the audio output device, call addBatteryData to notify
4998 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004999 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005000 uint32_t params = 0;
5001 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07005002 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005003 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07005004 }
5005
Eric Laurent054d9d32015-04-24 08:48:48 -07005006 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07005007 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07005008 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
5009 }
5010
5011 if (params != 0) {
5012 addBatteryData(params);
5013 }
5014 }
5015#endif
5016
5017 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08005018 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07005019 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07005020
jiabinc52b1ff2019-10-31 17:20:42 -07005021 // mPatch.num_sinks is not set when the thread is created so that
5022 // the first patch creation triggers an ioConfigChanged callback
5023 bool configChanged = (mPatch.num_sinks == 0) ||
5024 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07005025 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07005026 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07005027 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07005028
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005029 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005030 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5031 status = hwDevice->createAudioPatch(patch->num_sources,
5032 patch->sources,
5033 patch->num_sinks,
5034 patch->sinks,
5035 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005036 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005037 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07005038 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005039 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005040 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005041
5042 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005043 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005044 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005045 // also dispatch to active AudioTracks for MediaMetrics
5046 for (const auto &track : mActiveTracks) {
5047 track->logEndInterval();
5048 track->logBeginInterval(patchSinksAsString);
5049 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005050
Eric Laurente8726fe2015-06-26 09:39:24 -07005051 if (configChanged) {
5052 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5053 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005054 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005055 mActiveTracks.setHasChanged();
5056
Eric Laurent1c333e22014-05-20 10:48:17 -07005057 return status;
5058}
5059
Andy Hungee58e4a2023-07-07 13:47:37 -07005060status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005061{
Andy Hungf60abce2016-08-26 11:37:54 -07005062 status_t status;
5063 if (property_get_bool("af.patch_park", false /* default_value */)) {
5064 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5065 // or if HAL does not properly lock against access.
5066 AutoPark<FastMixer> park(mFastMixer);
5067 status = PlaybackThread::releaseAudioPatch_l(handle);
5068 } else {
5069 status = PlaybackThread::releaseAudioPatch_l(handle);
5070 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005071 return status;
5072}
5073
Andy Hungee58e4a2023-07-07 13:47:37 -07005074status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005075{
5076 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005077
jiabinc52b1ff2019-10-31 17:20:42 -07005078 mPatch = audio_patch{};
5079 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005080
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005081 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005082 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5083 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005084 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005085 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005086 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005087 // Force meteadata update after a route change
5088 mActiveTracks.setHasChanged();
5089
Eric Laurent1c333e22014-05-20 10:48:17 -07005090 return status;
5091}
5092
Andy Hungee58e4a2023-07-07 13:47:37 -07005093void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005094{
Andy Hung972bec12023-08-31 16:13:39 -07005095 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005096 mTracks.add(track);
5097}
5098
Andy Hungee58e4a2023-07-07 13:47:37 -07005099void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005100{
Andy Hung972bec12023-08-31 16:13:39 -07005101 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005102 destroyTrack_l(track);
5103}
5104
Andy Hungee58e4a2023-07-07 13:47:37 -07005105void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005106{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005107 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005108 config->role = AUDIO_PORT_ROLE_SOURCE;
5109 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5110 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005111 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5112 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5113 config->flags.output = mOutput->flags;
5114 }
Eric Laurent83b88082014-06-20 18:31:16 -07005115}
5116
Atneya Nairaa3afcb2024-10-08 16:36:19 -07005117std::string PlaybackThread::getLocalLogHeader() const {
5118 using namespace std::literals;
5119 static constexpr auto indent = " "
5120 " "sv;
5121 return std::string{indent}.append(IAfTrack::getLogHeader());
5122}
Eric Laurent81784c32012-11-19 14:55:58 -08005123// ----------------------------------------------------------------------------
5124
Andy Hungee58e4a2023-07-07 13:47:37 -07005125/* static */
5126sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005127 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005128 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005129 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005130}
5131
Andy Hung583043b2023-07-17 17:05:00 -07005132MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005133 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005134 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005135 // mAudioMixer below
5136 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005137 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005138 mFastMixerFutex(0),
5139 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005140 // mOutputSink below
5141 // mPipeSink below
5142 // mNormalSink below
5143{
jiabinc52b1ff2019-10-31 17:20:42 -07005144 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005145 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005146 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005147 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5148 mNormalFrameCount);
5149 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5150
Andy Hungfbfc3952015-01-15 13:33:51 -08005151 if (type == DUPLICATING) {
5152 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5153 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5154 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
Andy Hung922617c2024-06-25 17:07:58 -07005155 // Balance is *not* set in the DuplicatingThread here (or from AudioFlinger),
5156 // as the downstream MixerThreads implement it.
Andy Hungfbfc3952015-01-15 13:33:51 -08005157 return;
5158 }
Eric Laurent81784c32012-11-19 14:55:58 -08005159 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005160 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005161 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005162 const NBAIO_Format offers[1] = {Format_from_SR_C(
5163 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005164#if !LOG_NDEBUG
5165 ssize_t index =
5166#else
5167 (void)
5168#endif
5169 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005170 ALOG_ASSERT(index == 0);
5171
5172 // initialize fast mixer depending on configuration
5173 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005174 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005175 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005176 } else {
5177 switch (kUseFastMixer) {
5178 case FastMixer_Never:
5179 initFastMixer = false;
5180 break;
5181 case FastMixer_Always:
5182 initFastMixer = true;
5183 break;
5184 case FastMixer_Static:
5185 case FastMixer_Dynamic:
Henrik Tillman470b3992024-10-08 12:49:28 +02005186 if (mType == MIXER && (output->flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER)) {
5187 /* Do not init fast mixer on deep buffer, warn if buffers are confed too small */
5188 initFastMixer = false;
5189 ALOGW_IF(mFrameCount * 1000 / mSampleRate < kMinNormalSinkBufferSizeMs,
5190 "HAL DEEP BUFFER Buffer (%zu ms) is smaller than set minimal buffer "
5191 "(%u ms), seems like a configuration error",
5192 mFrameCount * 1000 / mSampleRate, kMinNormalSinkBufferSizeMs);
5193 } else {
5194 initFastMixer = mFrameCount < mNormalFrameCount;
5195 }
Eric Laurentb62d0362021-10-26 17:40:18 +02005196 break;
5197 }
5198 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5199 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5200 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005201 }
5202 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005203 audio_format_t fastMixerFormat;
5204 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5205 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5206 } else {
5207 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5208 }
5209 if (mFormat != fastMixerFormat) {
5210 // change our Sink format to accept our intermediate precision
5211 mFormat = fastMixerFormat;
5212 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005213 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005214 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5215 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5216 }
Eric Laurent81784c32012-11-19 14:55:58 -08005217
5218 // create a MonoPipe to connect our submix to FastMixer
5219 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005220
Andy Hung1258c1a2014-05-23 21:22:17 -07005221 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005222 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005223 format.mFormat = fastMixerFormat;
5224 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5225
Eric Laurent81784c32012-11-19 14:55:58 -08005226 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5227 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5228 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5229 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005230 const NBAIO_Format offersFast[1] = {format};
5231 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005232#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005233 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005234#else
5235 (void)
5236#endif
Andy Hung920f6572022-10-06 12:09:49 -07005237 monoPipe->negotiate(offersFast, std::size(offersFast),
5238 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005239 ALOG_ASSERT(index == 0);
5240 monoPipe->setAvgFrames((mScreenState & 1) ?
5241 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5242 mPipeSink = monoPipe;
5243
Eric Laurent81784c32012-11-19 14:55:58 -08005244 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005245 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005246 FastMixerStateQueue *sq = mFastMixer->sq();
5247#ifdef STATE_QUEUE_DUMP
5248 sq->setObserverDump(&mStateQueueObserverDump);
5249 sq->setMutatorDump(&mStateQueueMutatorDump);
5250#endif
5251 FastMixerState *state = sq->begin();
5252 FastTrack *fastTrack = &state->mFastTracks[0];
5253 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5254 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5255 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005256 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5257 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5258 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005259 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005260 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Lais Andradee8995e92024-07-24 15:00:38 +01005261 fastTrack->mHapticScale = os::HapticScale::none();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005262 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005263 fastTrack->mGeneration++;
5264 state->mFastTracksGen++;
5265 state->mTrackMask = 1;
5266 // fast mixer will use the HAL output sink
5267 state->mOutputSink = mOutputSink.get();
5268 state->mOutputSinkGen++;
5269 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005270 // specify sink channel mask when haptic channel mask present as it can not
5271 // be calculated directly from channel count
5272 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005273 ? AUDIO_CHANNEL_NONE
5274 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005275 state->mCommand = FastMixerState::COLD_IDLE;
5276 // already done in constructor initialization list
5277 //mFastMixerFutex = 0;
5278 state->mColdFutexAddr = &mFastMixerFutex;
5279 state->mColdGen++;
5280 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005281 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005282 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005283 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07005284 {
5285 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
5286 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5287 }
Eric Laurent81784c32012-11-19 14:55:58 -08005288
Eric Tan0513b5d2018-09-17 10:32:48 -07005289 NBLog::thread_info_t info;
5290 info.id = mId;
5291 info.type = NBLog::FASTMIXER;
5292 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5293
Eric Laurent81784c32012-11-19 14:55:58 -08005294 // start the fast mixer
5295 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5296 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005297 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005298 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005299
5300#ifdef AUDIO_WATCHDOG
5301 // create and start the watchdog
5302 mAudioWatchdog = new AudioWatchdog();
5303 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5304 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5305 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005306 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005307#endif
Andy Hung8946a282018-04-19 20:04:56 -07005308 } else {
5309#ifdef TEE_SINK
5310 // Only use the MixerThread tee if there is no FastMixer.
5311 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5312 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5313#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005314 }
5315
5316 switch (kUseFastMixer) {
5317 case FastMixer_Never:
5318 case FastMixer_Dynamic:
5319 mNormalSink = mOutputSink;
5320 break;
5321 case FastMixer_Always:
5322 mNormalSink = mPipeSink;
5323 break;
5324 case FastMixer_Static:
5325 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5326 break;
5327 }
Andy Hung922617c2024-06-25 17:07:58 -07005328 // setMasterBalance needs to be called after the FastMixer
5329 // (if any) is set up, in order to deliver the balance settings to it.
5330 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurent81784c32012-11-19 14:55:58 -08005331}
5332
Andy Hungee58e4a2023-07-07 13:47:37 -07005333MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005334{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005335 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005336 FastMixerStateQueue *sq = mFastMixer->sq();
5337 FastMixerState *state = sq->begin();
5338 if (state->mCommand == FastMixerState::COLD_IDLE) {
5339 int32_t old = android_atomic_inc(&mFastMixerFutex);
5340 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005341 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005342 }
5343 }
5344 state->mCommand = FastMixerState::EXIT;
5345 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07005346 {
5347 audio_utils::mutex::scoped_join_wait_check queueWaitCheck(mFastMixer->getTid());
5348 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5349 mFastMixer->join();
5350 }
Eric Laurent81784c32012-11-19 14:55:58 -08005351 // Though the fast mixer thread has exited, it's state queue is still valid.
5352 // We'll use that extract the final state which contains one remaining fast track
5353 // corresponding to our sub-mix.
5354 state = sq->begin();
5355 ALOG_ASSERT(state->mTrackMask == 1);
5356 FastTrack *fastTrack = &state->mFastTracks[0];
5357 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5358 delete fastTrack->mBufferProvider;
5359 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005360 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005361#ifdef AUDIO_WATCHDOG
5362 if (mAudioWatchdog != 0) {
5363 mAudioWatchdog->requestExit();
5364 mAudioWatchdog->requestExitAndWait();
5365 mAudioWatchdog.clear();
5366 }
5367#endif
5368 }
Andy Hung583043b2023-07-17 17:05:00 -07005369 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005370 delete mAudioMixer;
5371}
5372
Andy Hungee58e4a2023-07-07 13:47:37 -07005373void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005374 PlaybackThread::onFirstRef();
5375
Andy Hung972bec12023-08-31 16:13:39 -07005376 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005377 if (mOutput != nullptr && mOutput->stream != nullptr) {
5378 status_t status = mOutput->stream->setLatencyModeCallback(this);
5379 if (status != INVALID_OPERATION) {
5380 updateHalSupportedLatencyModes_l();
5381 }
5382 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5383 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5384 mBluetoothLatencyModesEnabled.store(
5385 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5386 }
5387}
Eric Laurent81784c32012-11-19 14:55:58 -08005388
Andy Hungee58e4a2023-07-07 13:47:37 -07005389uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005390{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005391 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005392 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5393 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5394 }
5395 return latency;
5396}
5397
Andy Hungee58e4a2023-07-07 13:47:37 -07005398ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005399{
5400 // FIXME we should only do one push per cycle; confirm this is true
5401 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005402 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005403 FastMixerStateQueue *sq = mFastMixer->sq();
5404 FastMixerState *state = sq->begin();
5405 if (state->mCommand != FastMixerState::MIX_WRITE &&
5406 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5407 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005408
5409 // FIXME workaround for first HAL write being CPU bound on some devices
5410 ATRACE_BEGIN("write");
5411 mOutput->write((char *)mSinkBuffer, 0);
5412 ATRACE_END();
5413
Eric Laurent81784c32012-11-19 14:55:58 -08005414 int32_t old = android_atomic_inc(&mFastMixerFutex);
5415 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005416 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005417 }
5418#ifdef AUDIO_WATCHDOG
5419 if (mAudioWatchdog != 0) {
5420 mAudioWatchdog->resume();
5421 }
5422#endif
5423 }
5424 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005425#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005426 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005427 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005428#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005429 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07005430 {
5431 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
5432 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5433 }
Eric Laurent81784c32012-11-19 14:55:58 -08005434 if (kUseFastMixer == FastMixer_Dynamic) {
5435 mNormalSink = mPipeSink;
5436 }
5437 } else {
5438 sq->end(false /*didModify*/);
5439 }
5440 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005442}
5443
Andy Hungee58e4a2023-07-07 13:47:37 -07005444void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005445{
5446 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005447 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005448 FastMixerStateQueue *sq = mFastMixer->sq();
5449 FastMixerState *state = sq->begin();
5450 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005451 // Report any frames trapped in the Monopipe
5452 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5453 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5454 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5455 "monoPipeWritten:%lld monoPipeLeft:%lld",
5456 (long long)mFramesWritten, (long long)mSuspendedFrames,
5457 (long long)mPipeSink->framesWritten(), pipeFrames);
5458 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5459
Eric Laurent81784c32012-11-19 14:55:58 -08005460 state->mCommand = FastMixerState::COLD_IDLE;
5461 state->mColdFutexAddr = &mFastMixerFutex;
5462 state->mColdGen++;
5463 mFastMixerFutex = 0;
5464 sq->end();
5465 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
Andy Hung82f39d62024-09-30 17:19:14 -07005466 {
5467 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
5468 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5469 }
Eric Laurent81784c32012-11-19 14:55:58 -08005470 if (kUseFastMixer == FastMixer_Dynamic) {
5471 mNormalSink = mOutputSink;
5472 }
5473#ifdef AUDIO_WATCHDOG
5474 if (mAudioWatchdog != 0) {
5475 mAudioWatchdog->pause();
5476 }
5477#endif
5478 } else {
5479 sq->end(false /*didModify*/);
5480 }
5481 }
5482 PlaybackThread::threadLoop_standby();
5483}
5484
Andy Hungee58e4a2023-07-07 13:47:37 -07005485bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005486{
5487 return false;
5488}
5489
Andy Hungee58e4a2023-07-07 13:47:37 -07005490bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005491{
5492 return !mStandby;
5493}
5494
Andy Hungee58e4a2023-07-07 13:47:37 -07005495bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005496{
Andy Hung972bec12023-08-31 16:13:39 -07005497 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005498 return waitingAsyncCallback_l();
5499}
5500
Eric Laurent81784c32012-11-19 14:55:58 -08005501// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005502void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005503{
Andy Hung8d672e02023-09-15 18:19:28 -07005504 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5505 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005506 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005507 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005508 // discard any pending drain or write ack by incrementing sequence
5509 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5510 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005511 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005512 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5513 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005514 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005515 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005516 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005517}
5518
Andy Hungee58e4a2023-07-07 13:47:37 -07005519void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005520{
5521 ALOGV("signal playback thread");
5522 broadcast_l();
5523}
5524
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005525void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005526{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005527 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005528 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5529 invalidateTracks((audio_stream_type_t)i);
5530 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005531 if (isHardError) {
5532 mAfThreadCallback->onHardError(allTrackPortIds);
5533 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005534}
5535
Andy Hungee58e4a2023-07-07 13:47:37 -07005536void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005537{
Eric Laurent81784c32012-11-19 14:55:58 -08005538 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005539 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005540 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005541 // increase sleep time progressively when application underrun condition clears.
5542 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5543 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5544 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005545 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005546 sleepTimeShift--;
5547 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005548 mSleepTimeUs = 0;
5549 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005550 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005551
Eric Laurent81784c32012-11-19 14:55:58 -08005552}
5553
Andy Hungee58e4a2023-07-07 13:47:37 -07005554void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005555{
5556 // If no tracks are ready, sleep once for the duration of an output
5557 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005558 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005559 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005560 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5561 // Using the Monopipe availableToWrite, we estimate the
5562 // sleep time to retry for more data (before we underrun).
5563 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5564 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5565 const size_t pipeFrames = monoPipe->maxFrames();
5566 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5567 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5568 const size_t framesDelay = std::min(
5569 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5570 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5571 pipeFrames, framesLeft, framesDelay);
5572 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5573 } else {
5574 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5575 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5576 mSleepTimeUs = kMinThreadSleepTimeUs;
5577 }
5578 // reduce sleep time in case of consecutive application underruns to avoid
5579 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5580 // duration we would end up writing less data than needed by the audio HAL if
5581 // the condition persists.
5582 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5583 sleepTimeShift++;
5584 }
Eric Laurent81784c32012-11-19 14:55:58 -08005585 }
5586 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005587 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005588 }
5589 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005590 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5591 // before effects processing or output.
5592 if (mMixerBufferValid) {
5593 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005594 if (mType == SPATIALIZER) {
5595 memset(mSinkBuffer, 0, mSinkBufferSize);
5596 }
Andy Hung98ef9782014-03-04 14:46:50 -08005597 } else {
5598 memset(mSinkBuffer, 0, mSinkBufferSize);
5599 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005600 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005601 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5602 "anticipated start");
5603 }
5604 // TODO add standby time extension fct of effect tail
5605}
5606
Andy Hungc5007f82023-08-29 14:26:09 -07005607// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005608PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005609 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005610{
Andy Hungc0691382018-09-12 18:01:57 -07005611 // clean up deleted track ids in AudioMixer before allocating new tracks
5612 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5613 // for each trackId, destroy it in the AudioMixer
5614 if (mAudioMixer->exists(trackId)) {
5615 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005616 }
5617 });
Andy Hungc0691382018-09-12 18:01:57 -07005618 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005619
5620 mixer_state mixerStatus = MIXER_IDLE;
5621 // find out which tracks need to be processed
5622 size_t count = mActiveTracks.size();
5623 size_t mixedTracks = 0;
5624 size_t tracksWithEffect = 0;
5625 // counts only _active_ fast tracks
5626 size_t fastTracks = 0;
5627 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5628
5629 float masterVolume = mMasterVolume;
5630 bool masterMute = mMasterMute;
5631
5632 if (masterMute) {
5633 masterVolume = 0;
5634 }
5635 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005636 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005637 if (chain != 0) {
5638 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005639 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005640 masterVolume = (float)((v + (1 << 23)) >> 24);
5641 chain.clear();
5642 }
5643
5644 // prepare a new state to push
5645 FastMixerStateQueue *sq = NULL;
5646 FastMixerState *state = NULL;
5647 bool didModify = false;
5648 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005649 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005650 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005651 sq = mFastMixer->sq();
5652 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005653 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005654 }
5655
Andy Hung69aed5f2014-02-25 17:24:40 -08005656 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005657 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005658
Andy Hungbd3b2b02018-05-21 10:53:11 -07005659 // DeferredOperations handles statistics after setting mixerStatus.
5660 class DeferredOperations {
5661 public:
Andy Hungea840382020-05-05 21:50:17 -07005662 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5663 : mMixerStatus(mixerStatus)
5664 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005665
5666 // when leaving scope, tally frames properly.
5667 ~DeferredOperations() {
5668 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5669 // because that is when the underrun occurs.
5670 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005671 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005672 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005673 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005674 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005675 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005676 }
5677 }
Andy Hungea840382020-05-05 21:50:17 -07005678 // send the max underrun frames for this mixer period
5679 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005680 }
5681
5682 // tallyUnderrunFrames() is called to update the track counters
5683 // with the number of underrun frames for a particular mixer period.
5684 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005685 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005686 mUnderrunFrames.emplace_back(track, underrunFrames);
5687 }
5688
5689 private:
5690 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005691 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005692 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005693 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005694 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005695
jiabin245cdd92018-12-07 17:55:15 -08005696 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005697 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005698 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005699
5700 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005701 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005702
5703 // process fast tracks
5704 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005705 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5706 "%s(%d): FastTrack(%d) present without FastMixer",
5707 __func__, id(), track->id());
5708
jiabin245cdd92018-12-07 17:55:15 -08005709 if (track->getHapticPlaybackEnabled()) {
5710 noFastHapticTrack = false;
5711 }
Eric Laurent81784c32012-11-19 14:55:58 -08005712
5713 // It's theoretically possible (though unlikely) for a fast track to be created
5714 // and then removed within the same normal mix cycle. This is not a problem, as
5715 // the track never becomes active so it's fast mixer slot is never touched.
5716 // The converse, of removing an (active) track and then creating a new track
5717 // at the identical fast mixer slot within the same normal mix cycle,
5718 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005719 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005720 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005721 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5722 FastTrack *fastTrack = &state->mFastTracks[j];
5723
5724 // Determine whether the track is currently in underrun condition,
5725 // and whether it had a recent underrun.
5726 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5727 FastTrackUnderruns underruns = ftDump->mUnderruns;
5728 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005729 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005730 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005731 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005732 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005733 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005734 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005735 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005736 // don't count underruns that occur while stopping or pausing
5737 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005738 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005739 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5740 recentUnderruns > 0) {
5741 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005742 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005743 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005744 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005745 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005746
5747 // This is similar to the state machine for normal tracks,
5748 // with a few modifications for fast tracks.
5749 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005750 switch (track->state()) {
5751 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005752 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005753 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005754 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005755 }
5756 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005757 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005758 // ramp down is not yet implemented
5759 track->setPaused();
5760 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005761 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005762 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005763 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005764 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005765 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005766 if (recentFull > 0 || recentPartial > 0) {
5767 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005768 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005769 }
5770 if (recentUnderruns == 0) {
5771 // no recent underruns: stay active
5772 break;
5773 }
5774 // there has recently been an underrun of some kind
5775 if (track->sharedBuffer() == 0) {
5776 // were any of the recent underruns "empty" (no frames available)?
5777 if (recentEmpty == 0) {
5778 // no, then ignore the partial underruns as they are allowed indefinitely
5779 break;
5780 }
5781 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005782 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005783 break;
5784 }
5785 // indicate to client process that the track was disabled because of underrun;
5786 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005787 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005788 // remove from active list, but state remains ACTIVE [confusing but true]
5789 isActive = false;
5790 break;
5791 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005792 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005793 case IAfTrackBase::STOPPING_2:
5794 case IAfTrackBase::PAUSED:
5795 case IAfTrackBase::STOPPED:
5796 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005797 // Check for presentation complete if track is inactive
5798 // We have consumed all the buffers of this track.
5799 // This would be incomplete if we auto-paused on underrun
5800 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005801 uint32_t latency = 0;
5802 status_t result = mOutput->stream->getLatency(&latency);
5803 ALOGE_IF(result != OK,
5804 "Error when retrieving output stream latency: %d", result);
5805 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005806 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005807 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5808 // track stays in active list until presentation is complete
5809 break;
5810 }
5811 }
5812 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005813 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005814 }
5815 if (track->isStopped()) {
5816 // Can't reset directly, as fast mixer is still polling this track
5817 // track->reset();
5818 // So instead mark this track as needing to be reset after push with ack
5819 resetMask |= 1 << i;
5820 }
5821 isActive = false;
5822 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005823 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005824 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005825 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005826 }
5827
5828 if (isActive) {
5829 // was it previously inactive?
5830 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005831 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5832 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005833 fastTrack->mBufferProvider = eabp;
5834 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005835 fastTrack->mChannelMask = track->channelMask();
5836 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005837 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005838 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005839 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005840 fastTrack->mGeneration++;
5841 state->mTrackMask |= 1 << j;
5842 didModify = true;
5843 // no acknowledgement required for newly active tracks
5844 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005845 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005846 float volume;
Andy Hung6b137d12024-08-27 22:35:17 +00005847 if (!audioserver_flags::portid_volume_management()) {
5848 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5849 volume = 0.f;
5850 } else {
5851 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5852 }
Eric Laurenteab90452019-06-24 15:17:46 -07005853 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07005854 if (track->isPlaybackRestricted() || track->getPortMute()) {
Andy Hung6b137d12024-08-27 22:35:17 +00005855 volume = 0.f;
5856 } else {
5857 volume = masterVolume * track->getPortVolume();
5858 }
Eric Laurenteab90452019-06-24 15:17:46 -07005859 }
Eric Laurenteab90452019-06-24 15:17:46 -07005860 handleVoipVolume_l(&volume);
5861
Eric Laurent81784c32012-11-19 14:55:58 -08005862 // cache the combined master volume and stream type volume for fast mixer; this
5863 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005864 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005865 proxy->framesReleased()).first;
5866 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005867 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005868 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005869 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5870 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Andy Hung6b137d12024-08-27 22:35:17 +00005871 if (!audioserver_flags::portid_volume_management()) {
5872 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5873 /*muteState=*/{masterVolume == 0.f,
5874 mStreamTypes[track->streamType()].volume == 0.f,
5875 mStreamTypes[track->streamType()].mute,
5876 track->isPlaybackRestricted(),
5877 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07005878 vh == 0.f,
5879 /*muteFromPortVolume=*/false});
Andy Hung6b137d12024-08-27 22:35:17 +00005880 } else {
5881 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
5882 /*muteState=*/{masterVolume == 0.f,
5883 track->getPortVolume() == 0.f,
5884 /* muteFromStreamMuted= */ false,
5885 track->isPlaybackRestricted(),
5886 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07005887 vh == 0.f,
5888 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +00005889 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005890 vlf *= volume;
5891 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005892
jiabin220eea12024-05-17 17:55:20 +00005893 if (track->getInternalMute()) {
5894 vlf = 0.f;
5895 vrf = 0.f;
5896 }
5897
jiabin76d94692022-12-15 21:51:21 +00005898 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005899 ++fastTracks;
5900 } else {
5901 // was it previously active?
5902 if (state->mTrackMask & (1 << j)) {
5903 fastTrack->mBufferProvider = NULL;
5904 fastTrack->mGeneration++;
5905 state->mTrackMask &= ~(1 << j);
5906 didModify = true;
5907 // If any fast tracks were removed, we must wait for acknowledgement
5908 // because we're about to decrement the last sp<> on those tracks.
5909 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5910 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005911 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5912 // AudioTrack may start (which may not be with a start() but with a write()
5913 // after underrun) and immediately paused or released. In that case the
5914 // FastTrack state hasn't had time to update.
5915 // TODO Remove the ALOGW when this theory is confirmed.
5916 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005917 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005918 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005919 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005920 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005921 }
5922 tracksToRemove->add(track);
5923 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005924 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005925 }
jiabin245cdd92018-12-07 17:55:15 -08005926 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5927 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5928 didModify = true;
5929 }
Eric Laurent81784c32012-11-19 14:55:58 -08005930 continue;
5931 }
5932
5933 { // local variable scope to avoid goto warning
5934
5935 audio_track_cblk_t* cblk = track->cblk();
5936
5937 // The first time a track is added we wait
5938 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005939 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005940
5941 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005942 // use the trackId as the AudioMixer name.
5943 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005944 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005945 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005946 track->channelMask(),
5947 track->format(),
5948 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005949 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005950 ALOGW("%s(): AudioMixer cannot create track(%d)"
5951 " mask %#x, format %#x, sessionId %d",
5952 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005953 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005954 tracksToRemove->add(track);
5955 track->invalidate(); // consider it dead.
5956 continue;
5957 }
5958 }
5959
Eric Laurent81784c32012-11-19 14:55:58 -08005960 // make sure that we have enough frames to mix one full buffer.
5961 // enforce this condition only once to enable draining the buffer in case the client
5962 // app does not call stop() and relies on underrun to stop:
5963 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5964 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005965 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005966 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5967 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005968
5969 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005970 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005971 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5972 // add frames already consumed but not yet released by the resampler
5973 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005974 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005975
Eric Laurent81784c32012-11-19 14:55:58 -08005976 uint32_t minFrames = 1;
5977 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5978 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005979 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005980 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005981
5982 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005983 if (ATRACE_ENABLED()) {
5984 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005985 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005986 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005987 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005988 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005989 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005990 !track->isPaused() && !track->isTerminated())
5991 {
Andy Hungc0691382018-09-12 18:01:57 -07005992 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005993
5994 mixedTracks++;
5995
Shunkai Yaof4847652024-01-12 00:25:20 +00005996 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005997 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005998 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005999 if (track->mainBuffer() != mSinkBuffer &&
6000 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08006001 if (mEffectBufferEnabled) {
6002 mEffectBufferValid = true; // Later can set directly.
6003 }
Eric Laurent81784c32012-11-19 14:55:58 -08006004 chain = getEffectChain_l(track->sessionId());
6005 // Delegate volume control to effect in track effect chain if needed
6006 if (chain != 0) {
6007 tracksWithEffect++;
6008 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006009 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08006010 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07006011 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08006012 }
6013 }
6014
6015
6016 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07006017 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08006018 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07006019 track->fillingStatus() = IAfTrack::FS_ACTIVE;
6020 if (track->state() == IAfTrackBase::RESUMING) {
6021 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08006022 // If a new track is paused immediately after start, do not ramp on resume.
6023 if (cblk->mServer != 0) {
6024 param = AudioMixer::RAMP_VOLUME;
6025 }
Eric Laurent81784c32012-11-19 14:55:58 -08006026 }
Andy Hungc0691382018-09-12 18:01:57 -07006027 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07006028 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07006029 // FIXME should not make a decision based on mServer
6030 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006031 // If the track is stopped before the first frame was mixed,
6032 // do not apply ramp
6033 param = AudioMixer::RAMP_VOLUME;
6034 }
6035
6036 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07006037 uint32_t vl, vr; // in U8.24 integer format
6038 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07006039 // read original volumes with volume control
Andy Hung333ab962019-05-28 20:23:35 -07006040 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07006041 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07006042 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07006043 track->audioTrackServerProxy()->framesReleased()).first;
Andy Hung6b137d12024-08-27 22:35:17 +00006044 float v;
6045 if (!audioserver_flags::portid_volume_management()) {
6046 v = masterVolume * mStreamTypes[track->streamType()].volume;
6047 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
6048 v = 0;
6049 }
6050 } else {
6051 v = masterVolume * track->getPortVolume();
Vlad Popa1e865e62024-08-15 19:11:42 -07006052 if (track->isPlaybackRestricted() || track->getPortMute()) {
Andy Hung6b137d12024-08-27 22:35:17 +00006053 v = 0;
6054 }
Eric Laurenteab90452019-06-24 15:17:46 -07006055 }
Eric Laurenteab90452019-06-24 15:17:46 -07006056 handleVoipVolume_l(&v);
6057
6058 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07006059 vl = vr = 0;
6060 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07006061 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08006062 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07006063 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07006064 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
6065 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08006066 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07006067 if (vlf > GAIN_FLOAT_UNITY) {
6068 ALOGV("Track left volume out of range: %.3g", vlf);
6069 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006070 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006071 if (vrf > GAIN_FLOAT_UNITY) {
6072 ALOGV("Track right volume out of range: %.3g", vrf);
6073 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08006074 }
Andy Hung6b137d12024-08-27 22:35:17 +00006075 if (!audioserver_flags::portid_volume_management()) {
6076 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6077 /*muteState=*/{masterVolume == 0.f,
6078 mStreamTypes[track->streamType()].volume == 0.f,
6079 mStreamTypes[track->streamType()].mute,
6080 track->isPlaybackRestricted(),
6081 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07006082 vh == 0.f,
6083 /*muteFromPortVolume=*/false});
Andy Hung6b137d12024-08-27 22:35:17 +00006084 } else {
6085 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6086 /*muteState=*/{masterVolume == 0.f,
6087 track->getPortVolume() == 0.f,
6088 /* muteFromStreamMuted= */ false,
6089 track->isPlaybackRestricted(),
6090 vlf == 0.f && vrf == 0.f,
Vlad Popa1e865e62024-08-15 19:11:42 -07006091 vh == 0.f,
6092 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +00006093 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006094 // now apply the master volume and stream type volume and shaper volume
6095 vlf *= v * vh;
6096 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08006097 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07006098 // then derive vl and vr as U8.24 versions for the effect chain
6099 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
6100 vl = (uint32_t) (scaleto8_24 * vlf);
6101 vr = (uint32_t) (scaleto8_24 * vrf);
6102 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006103 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006104 // send level comes from shared memory and so may be corrupt
6105 if (sendLevel > MAX_GAIN_INT) {
6106 ALOGV("Track send level out of range: %04X", sendLevel);
6107 sendLevel = MAX_GAIN_INT;
6108 }
Andy Hung6be49402014-05-30 10:42:03 -07006109 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6110 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006111 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006112
jiabin220eea12024-05-17 17:55:20 +00006113 if (track->getInternalMute()) {
6114 vrf = 0.f;
6115 vlf = 0.f;
6116 }
6117
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006118 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006119
Eric Laurent81784c32012-11-19 14:55:58 -08006120 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006121 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006122 // Do not ramp volume if volume is controlled by effect
6123 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006124 // Update remaining floating point volume levels
6125 vlf = (float)vl / (1 << 24);
6126 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006127 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006128 } else {
6129 // force no volume ramp when volume controller was just disabled or removed
6130 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006131 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006132 param = AudioMixer::VOLUME;
6133 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006134 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006135 }
6136
Eric Laurent81784c32012-11-19 14:55:58 -08006137 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006138 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006139 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006140
Andy Hungc0691382018-09-12 18:01:57 -07006141 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6142 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6143 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006144 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006145 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006146 AudioMixer::TRACK,
6147 AudioMixer::FORMAT, (void *)track->format());
6148 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006149 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006150 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006151 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006152
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006153 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006154 mAudioMixer->setParameter(
6155 trackId,
6156 AudioMixer::TRACK,
6157 AudioMixer::MIXER_CHANNEL_MASK,
6158 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6159 } else {
6160 mAudioMixer->setParameter(
6161 trackId,
6162 AudioMixer::TRACK,
6163 AudioMixer::MIXER_CHANNEL_MASK,
6164 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6165 }
6166
Glenn Kastene3aa6592012-12-04 12:22:46 -08006167 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006168 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006169 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006170 if (reqSampleRate == 0) {
6171 reqSampleRate = mSampleRate;
6172 } else if (reqSampleRate > maxSampleRate) {
6173 reqSampleRate = maxSampleRate;
6174 }
Eric Laurent81784c32012-11-19 14:55:58 -08006175 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006176 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006177 AudioMixer::RESAMPLE,
6178 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006179 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006180
Andy Hung8edb8dc2015-03-26 19:13:55 -07006181 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006182 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006183 AudioMixer::TIMESTRETCH,
6184 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006185 // cast away constness for this generic API.
6186 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006187
Andy Hung69aed5f2014-02-25 17:24:40 -08006188 /*
6189 * Select the appropriate output buffer for the track.
6190 *
Andy Hung98ef9782014-03-04 14:46:50 -08006191 * Tracks with effects go into their own effects chain buffer
6192 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006193 *
6194 * Other tracks can use mMixerBuffer for higher precision
6195 * channel accumulation. If this buffer is enabled
6196 * (mMixerBufferEnabled true), then selected tracks will accumulate
6197 * into it.
6198 *
6199 */
6200 if (mMixerBufferEnabled
6201 && (track->mainBuffer() == mSinkBuffer
6202 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006203 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006204 mAudioMixer->setParameter(
6205 trackId,
6206 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006207 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006208 mAudioMixer->setParameter(
6209 trackId,
6210 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006211 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006212 } else {
6213 mAudioMixer->setParameter(
6214 trackId,
6215 AudioMixer::TRACK,
6216 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6217 mAudioMixer->setParameter(
6218 trackId,
6219 AudioMixer::TRACK,
6220 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6221 // TODO: override track->mainBuffer()?
6222 mMixerBufferValid = true;
6223 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006224 } else {
6225 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006226 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006227 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006228 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006229 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006230 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006231 AudioMixer::TRACK,
6232 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6233 }
Eric Laurent81784c32012-11-19 14:55:58 -08006234 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006235 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006236 AudioMixer::TRACK,
6237 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006238 mAudioMixer->setParameter(
6239 trackId,
6240 AudioMixer::TRACK,
6241 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006242 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006243 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006244 trackId,
6245 AudioMixer::TRACK,
6246 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006247 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006248 mAudioMixer->setParameter(
6249 trackId,
6250 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006251 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006252
6253 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006254 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006255
6256 // If one track is ready, set the mixer ready if:
6257 // - the mixer was not ready during previous round OR
6258 // - no other track is not ready
6259 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6260 mixerStatus != MIXER_TRACKS_ENABLED) {
6261 mixerStatus = MIXER_TRACKS_READY;
6262 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006263
6264 // Enable the next few lines to instrument a test for underrun log handling.
6265 // TODO: Remove when we have a better way of testing the underrun log.
6266#if 0
6267 static int i;
6268 if ((++i & 0xf) == 0) {
6269 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6270 }
6271#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006272 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006273 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006274 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006275 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6276 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006277 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006278 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006279 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006280
Eric Laurent81784c32012-11-19 14:55:58 -08006281 // clear effect chain input buffer if an active track underruns to avoid sending
6282 // previous audio buffer again to effects
6283 chain = getEffectChain_l(track->sessionId());
6284 if (chain != 0) {
6285 chain->clearInputBuffer();
6286 }
6287
Andy Hungc0691382018-09-12 18:01:57 -07006288 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006289 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6290 track->isStopped() || track->isPaused()) {
6291 // We have consumed all the buffers of this track.
6292 // Remove it from the list of active tracks.
6293 // TODO: use actual buffer filling status instead of latency when available from
6294 // audio HAL
6295 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006296 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006297 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6298 if (track->isStopped()) {
6299 track->reset();
6300 }
6301 tracksToRemove->add(track);
6302 }
6303 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006304 // No buffers for this track. Give it a few chances to
6305 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006306 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006307 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6308 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006309 tracksToRemove->add(track);
6310 // indicate to client process that the track was disabled because of underrun;
6311 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006312 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006313 // If one track is not ready, mark the mixer also not ready if:
6314 // - the mixer was ready during previous round OR
6315 // - no other track is ready
6316 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6317 mixerStatus != MIXER_TRACKS_READY) {
6318 mixerStatus = MIXER_TRACKS_ENABLED;
6319 }
6320 }
Andy Hungc0691382018-09-12 18:01:57 -07006321 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006322 }
6323
6324 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006325
6326 }
6327
jiabin245cdd92018-12-07 17:55:15 -08006328 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6329 // When there is no fast track playing haptic and FastMixer exists,
6330 // enabling the first FastTrack, which provides mixed data from normal
6331 // tracks, to play haptic data.
6332 FastTrack *fastTrack = &state->mFastTracks[0];
6333 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6334 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6335 didModify = true;
6336 }
6337 }
6338
Eric Laurent81784c32012-11-19 14:55:58 -08006339 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006340 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006341 if (didModify) {
6342 state->mFastTracksGen++;
6343 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6344 if (kUseFastMixer == FastMixer_Dynamic &&
6345 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6346 state->mCommand = FastMixerState::COLD_IDLE;
6347 state->mColdFutexAddr = &mFastMixerFutex;
6348 state->mColdGen++;
6349 mFastMixerFutex = 0;
6350 if (kUseFastMixer == FastMixer_Dynamic) {
6351 mNormalSink = mOutputSink;
6352 }
6353 // If we go into cold idle, need to wait for acknowledgement
6354 // so that fast mixer stops doing I/O.
6355 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6356 pauseAudioWatchdog = true;
6357 }
Eric Laurent81784c32012-11-19 14:55:58 -08006358 }
6359 if (sq != NULL) {
6360 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006361 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6362 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6363 // when bringing the output sink into standby.)
6364 //
6365 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6366 //
6367 // This occurs with BT suspend when we idle the FastMixer with
6368 // active tracks, which may be added or removed.
Andy Hung82f39d62024-09-30 17:19:14 -07006369 {
6370 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastMixer->getTid());
6371 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
6372 }
Eric Laurent81784c32012-11-19 14:55:58 -08006373 }
6374#ifdef AUDIO_WATCHDOG
6375 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6376 mAudioWatchdog->pause();
6377 }
6378#endif
6379
6380 // Now perform the deferred reset on fast tracks that have stopped
6381 while (resetMask != 0) {
6382 size_t i = __builtin_ctz(resetMask);
6383 ALOG_ASSERT(i < count);
6384 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006385 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006386 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6387 track->reset();
6388 }
6389
Andy Hung80d03d22018-04-10 10:32:11 -07006390 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6391 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6392 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6393 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6394 // See also the implementation of destroyTrack_l().
6395 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006396 const int trackId = track->id();
6397 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6398 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006399 }
6400 }
6401
Eric Laurent81784c32012-11-19 14:55:58 -08006402 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006403 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006404
Eric Laurentb3f315a2021-07-13 15:09:05 +02006405 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6406 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006407 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006408 }
6409
6410 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006411 // as long as there are effects we should clear the effects buffer, to avoid
6412 // passing a non-clean buffer to the effect chain
6413 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006414 if (mType == SPATIALIZER) {
6415 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6416 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006417 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006418 // sink or mix buffer must be cleared if all tracks are connected to an
6419 // effect chain as in this case the mixer will not write to the sink or mix buffer
6420 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006421 // always clear sink buffer for spatializer output as the output of the spatializer
6422 // effect will be accumulated into it
6423 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6424 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006425 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006426 if (mMixerBufferValid) {
6427 memset(mMixerBuffer, 0, mMixerBufferSize);
6428 // TODO: In testing, mSinkBuffer below need not be cleared because
6429 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6430 // after mixing.
6431 //
6432 // To enforce this guarantee:
6433 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6434 // (mixedTracks == 0 && fastTracks > 0))
6435 // must imply MIXER_TRACKS_READY.
6436 // Later, we may clear buffers regardless, and skip much of this logic.
6437 }
Andy Hung98ef9782014-03-04 14:46:50 -08006438 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006439 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006440 }
6441
6442 // if any fast tracks, then status is ready
6443 mMixerStatusIgnoringFastTracks = mixerStatus;
6444 if (fastTracks > 0) {
6445 mixerStatus = MIXER_TRACKS_READY;
6446 }
6447 return mixerStatus;
6448}
6449
Andy Hungc5007f82023-08-29 14:26:09 -07006450// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006451uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006452{
6453 uint32_t trackCount = 0;
6454 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006455 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006456 trackCount++;
6457 }
6458 }
6459 return trackCount;
6460}
6461
Andy Hungee58e4a2023-07-07 13:47:37 -07006462bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006463{
Brian Lindahl65e90012022-07-27 18:01:07 +02006464 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6465 // could falsely detect that the frame position has stalled due to underrun because we haven't
6466 // given the Audio HAL enough time to update.
6467 const nsecs_t nowNs = systemTime();
6468 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6469 return mLatchedValue;
6470 }
6471 mPreviousNs = nowNs;
6472 mLatchedValue = false;
6473 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006474 uint64_t position = 0;
6475 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006476 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006477 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006478 if (position != mPreviousPosition) {
6479 mPreviousPosition = position;
6480 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006481 }
6482 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006483 return mLatchedValue;
6484}
6485
Andy Hungee58e4a2023-07-07 13:47:37 -07006486void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006487{
6488 mLatchedValue = true;
6489 mPreviousPosition = 0;
6490 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006491}
6492
Andy Hungc5007f82023-08-29 14:26:09 -07006493// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006494bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006495 audio_channel_mask_t channelMask, audio_format_t format,
6496 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006497{
Andy Hung1bc088a2018-02-09 15:57:31 -08006498 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6499 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006500 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006501 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006502 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006503 ALOGW("%s: invalid format: %#x", __func__, format);
6504 return false;
6505 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006506 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006507 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6508 return false;
6509 }
6510 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006511}
6512
Andy Hungc5007f82023-08-29 14:26:09 -07006513// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006514bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006515 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006516{
Eric Laurent81784c32012-11-19 14:55:58 -08006517 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006518 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006519
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006520 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006521
Eric Laurent10351942014-05-08 18:49:52 -07006522 AudioParameter param = AudioParameter(keyValuePair);
6523 int value;
6524 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6525 reconfig = true;
6526 }
6527 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006528 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006529 status = BAD_VALUE;
6530 } else {
6531 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006532 reconfig = true;
6533 }
Eric Laurent10351942014-05-08 18:49:52 -07006534 }
6535 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006536 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006537 status = BAD_VALUE;
6538 } else {
6539 // no need to save value, since it's constant
6540 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006541 }
Eric Laurent10351942014-05-08 18:49:52 -07006542 }
6543 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6544 // do not accept frame count changes if tracks are open as the track buffer
6545 // size depends on frame count and correct behavior would not be guaranteed
6546 // if frame count is changed after track creation
6547 if (!mTracks.isEmpty()) {
6548 status = INVALID_OPERATION;
6549 } else {
6550 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006551 }
Eric Laurent10351942014-05-08 18:49:52 -07006552 }
6553 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006554 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006555 }
Eric Laurent81784c32012-11-19 14:55:58 -08006556
Eric Laurent10351942014-05-08 18:49:52 -07006557 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006558 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006559 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006560 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6561 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006562 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006563 mThreadMetrics.logEndInterval();
6564 mThreadSnapshot.onEnd();
6565 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006566 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006567 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006568 }
Eric Laurent10351942014-05-08 18:49:52 -07006569 if (status == NO_ERROR && reconfig) {
6570 readOutputParameters_l();
6571 delete mAudioMixer;
6572 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006573 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006574 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006575 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006576 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006577 track->channelMask(),
6578 track->format(),
6579 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006580 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006581 "%s(): AudioMixer cannot create track(%d)"
6582 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006583 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006584 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006585 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006586 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006587 }
Eric Laurent81784c32012-11-19 14:55:58 -08006588 }
6589
Dean Wheatley68918102021-03-19 22:09:19 +11006590 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006591}
6592
6593
Andy Hungee58e4a2023-07-07 13:47:37 -07006594void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006595{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006596 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006597 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006598 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006599 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006600 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6601 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6602 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006603 if (hasFastMixer()) {
6604 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6605
6606 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6607 // while we are dumping it. It may be inconsistent, but it won't mutate!
6608 // This is a large object so we place it on the heap.
6609 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006610 const std::unique_ptr<FastMixerDumpState> copy =
6611 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006612 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006613
6614#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006615 // Similar for state queue
6616 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6617 observerCopy.dump(fd);
6618 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6619 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006620#endif
6621
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006622#ifdef AUDIO_WATCHDOG
6623 if (mAudioWatchdog != 0) {
6624 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6625 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6626 wdCopy.dump(fd);
6627 }
6628#endif
6629
6630 } else {
6631 dprintf(fd, " No FastMixer\n");
6632 }
Eric Laurent90cea102023-05-15 15:08:27 +02006633
6634 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6635 mBluetoothLatencyModesEnabled ? "" : "not ");
6636 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6637 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6638 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006639}
6640
Andy Hungee58e4a2023-07-07 13:47:37 -07006641uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006642{
6643 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6644}
6645
Andy Hungee58e4a2023-07-07 13:47:37 -07006646uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006647{
6648 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6649}
6650
Andy Hungee58e4a2023-07-07 13:47:37 -07006651void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006652{
6653 PlaybackThread::cacheParameters_l();
6654
6655 // FIXME: Relaxed timing because of a certain device that can't meet latency
6656 // Should be reduced to 2x after the vendor fixes the driver issue
6657 // increase threshold again due to low power audio mode. The way this warning
6658 // threshold is calculated and its usefulness should be reconsidered anyway.
6659 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6660}
6661
Andy Hungee58e4a2023-07-07 13:47:37 -07006662void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006663 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006664}
6665
Andy Hungee58e4a2023-07-07 13:47:37 -07006666void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006667 // Only handle latency mode if:
6668 // - mBluetoothLatencyModesEnabled is true
6669 // - the HAL supports latency modes
6670 // - the selected device is Bluetooth LE or A2DP
6671 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6672 return;
6673 }
6674 if (mOutDeviceTypeAddrs.size() != 1
6675 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6676 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6677 return;
6678 }
6679
6680 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6681 if (mSupportedLatencyModes.size() == 1) {
6682 // If the HAL only support one latency mode currently, confirm the choice
6683 latencyMode = mSupportedLatencyModes[0];
6684 } else if (mSupportedLatencyModes.size() > 1) {
6685 // Request low latency if:
6686 // - At least one active track is either:
6687 // - a fast track with gaming usage or
6688 // - a track with acessibility usage
6689 for (const auto& track : mActiveTracks) {
6690 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6691 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6692 latencyMode = AUDIO_LATENCY_MODE_LOW;
6693 break;
6694 }
6695 }
6696 }
6697
6698 if (latencyMode != mSetLatencyMode) {
6699 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6700 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6701 __func__, mId, toString(latencyMode).c_str(), status);
6702 if (status == NO_ERROR) {
6703 mSetLatencyMode = latencyMode;
6704 }
6705 }
6706}
6707
Andy Hungee58e4a2023-07-07 13:47:37 -07006708void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006709
6710 if (mOutput == nullptr || mOutput->stream == nullptr) {
6711 return;
6712 }
6713 std::vector<audio_latency_mode_t> latencyModes;
6714 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6715 if (status != NO_ERROR) {
6716 latencyModes.clear();
6717 }
6718 if (latencyModes != mSupportedLatencyModes) {
6719 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6720 __func__, mId, status, toString(latencyModes).c_str());
6721 mSupportedLatencyModes.swap(latencyModes);
6722 sendHalLatencyModesChangedEvent_l();
6723 }
6724}
6725
Andy Hungee58e4a2023-07-07 13:47:37 -07006726status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006727 std::vector<audio_latency_mode_t>* modes) {
6728 if (modes == nullptr) {
6729 return BAD_VALUE;
6730 }
Andy Hung972bec12023-08-31 16:13:39 -07006731 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006732 *modes = mSupportedLatencyModes;
6733 return NO_ERROR;
6734}
6735
Andy Hungee58e4a2023-07-07 13:47:37 -07006736void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006737 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006738 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006739 if (modes != mSupportedLatencyModes) {
6740 ALOGD("%s: thread(%d) supported latency modes: %s",
6741 __func__, mId, toString(modes).c_str());
6742 mSupportedLatencyModes.swap(modes);
6743 sendHalLatencyModesChangedEvent_l();
6744 }
6745}
6746
Andy Hungee58e4a2023-07-07 13:47:37 -07006747status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006748 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6749 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6750 return INVALID_OPERATION;
6751 }
6752 mBluetoothLatencyModesEnabled.store(enabled);
6753 return NO_ERROR;
6754}
6755
Eric Laurent81784c32012-11-19 14:55:58 -08006756// ----------------------------------------------------------------------------
6757
Andy Hungee58e4a2023-07-07 13:47:37 -07006758/* static */
6759sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006760 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006761 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6762 const audio_offload_info_t& offloadInfo) {
6763 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006764 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006765}
6766
Andy Hung583043b2023-07-17 17:05:00 -07006767DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006768 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6769 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006770 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006771 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006772{
Andy Hung583043b2023-07-17 17:05:00 -07006773 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006774}
6775
Andy Hungee58e4a2023-07-07 13:47:37 -07006776DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006777{
6778}
6779
Andy Hungee58e4a2023-07-07 13:47:37 -07006780void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006781{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006782 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006783 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6784 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6785}
6786
Andy Hungee58e4a2023-07-07 13:47:37 -07006787void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006788{
Andy Hung972bec12023-08-31 16:13:39 -07006789 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006790 if (mMasterBalance != balance) {
6791 mMasterBalance.store(balance);
6792 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6793 broadcast_l();
6794 }
6795}
6796
Andy Hungee58e4a2023-07-07 13:47:37 -07006797void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006798{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006799 float left, right;
6800
Andy Hung333ab962019-05-28 20:23:35 -07006801 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006802 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006803
Andy Hung398ffa22022-12-13 19:19:53 -08006804 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6805 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6806
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006807 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6808 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006809
6810 const int64_t volumeShaperFrames =
6811 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6812 const auto [shaperVolume, shaperActive] =
6813 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006814 mVolumeShaperActive = shaperActive;
6815
Vlad Popae2f5aef2022-07-25 16:00:20 +02006816 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6817 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6818 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6819
6820 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6821
Andy Hung6b137d12024-08-27 22:35:17 +00006822 if (!audioserver_flags::portid_volume_management()) {
6823 if (mMasterMute || mStreamTypes[track->streamType()].mute ||
6824 track->isPlaybackRestricted()) {
6825 left = right = 0;
6826 } else {
6827 float typeVolume = mStreamTypes[track->streamType()].volume;
6828 const float v = mMasterVolume * typeVolume * shaperVolume;
Eric Laurent277a37e2024-07-29 18:37:52 +00006829
Andy Hung6b137d12024-08-27 22:35:17 +00006830 if (left > GAIN_FLOAT_UNITY) {
6831 left = GAIN_FLOAT_UNITY;
6832 }
6833 if (right > GAIN_FLOAT_UNITY) {
6834 right = GAIN_FLOAT_UNITY;
6835 }
6836 left *= v;
6837 right *= v;
6838 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006839 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
Andy Hung6b137d12024-08-27 22:35:17 +00006840 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6841 right *= mMasterBalanceRight;
6842 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006843 }
Andy Hung6b137d12024-08-27 22:35:17 +00006844 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6845 /*muteState=*/{mMasterMute,
6846 mStreamTypes[track->streamType()].volume == 0.f,
6847 mStreamTypes[track->streamType()].mute,
6848 track->isPlaybackRestricted(),
6849 clientVolumeMute,
Vlad Popa1e865e62024-08-15 19:11:42 -07006850 shaperVolume == 0.f,
6851 /*muteFromPortVolume=*/false});
Andy Hung6b137d12024-08-27 22:35:17 +00006852 } else {
6853 if (mMasterMute || track->isPlaybackRestricted()) {
6854 left = right = 0;
6855 } else {
6856 float typeVolume = track->getPortVolume();
6857 const float v = mMasterVolume * typeVolume * shaperVolume;
Liana Kazanova (xWF)d3e99d22024-08-23 22:15:51 +00006858
Andy Hung6b137d12024-08-27 22:35:17 +00006859 if (left > GAIN_FLOAT_UNITY) {
6860 left = GAIN_FLOAT_UNITY;
6861 }
6862 if (right > GAIN_FLOAT_UNITY) {
6863 right = GAIN_FLOAT_UNITY;
6864 }
6865 left *= v;
6866 right *= v;
6867 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
6868 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6869 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6870 right *= mMasterBalanceRight;
6871 }
6872 }
6873 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
6874 /*muteState=*/{mMasterMute,
6875 track->getPortVolume() == 0.f,
6876 /* muteFromStreamMuted= */ false,
6877 track->isPlaybackRestricted(),
6878 clientVolumeMute,
Vlad Popa1e865e62024-08-15 19:11:42 -07006879 shaperVolume == 0.f,
6880 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +00006881 }
Pechetty Sravani (xWF)2e077f02024-08-27 01:46:20 +00006882
Eric Laurentbfb1b832013-01-07 09:53:42 -08006883 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006884 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006885 if (left != mLeftVolFloat || right != mRightVolFloat) {
6886 mLeftVolFloat = left;
6887 mRightVolFloat = right;
6888
Eric Laurentbfb1b832013-01-07 09:53:42 -08006889 // Delegate volume control to effect in track effect chain if needed
6890 // only one effect chain can be present on DirectOutputThread, so if
6891 // there is one, the track is connected to it
6892 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006893 // if effect chain exists, volume is handled by it.
6894 // Convert volumes from float to 8.24
6895 uint32_t vl = (uint32_t)(left * (1 << 24));
6896 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006897 // Direct/Offload effect chains set output volume in setVolume().
6898 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006899 } else {
6900 // otherwise we directly set the volume.
6901 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006902 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006903 }
6904 }
6905}
6906
Andy Hungee58e4a2023-07-07 13:47:37 -07006907void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006908{
Andy Hung8d31fd22023-06-26 19:20:57 -07006909 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6910 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006911
Eric Laurent0f0631e2015-07-06 18:01:25 -07006912 if (previousTrack != 0 && latestTrack != 0) {
6913 if (mType == DIRECT) {
6914 if (previousTrack.get() != latestTrack.get()) {
6915 mFlushPending = true;
6916 }
6917 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006918 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6919 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006920 mFlushPending = true;
6921 }
6922 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006923 } else if (previousTrack == 0) {
6924 // there could be an old track added back during track transition for direct
6925 // output, so always issues flush to flush data of the previous track if it
6926 // was already destroyed with HAL paused, then flush can resume the playback
6927 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006928 }
6929 PlaybackThread::onAddNewTrack_l();
6930}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006931
Andy Hungee58e4a2023-07-07 13:47:37 -07006932PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006933 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006934)
6935{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006936 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006937 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006938 bool doHwPause = false;
6939 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006940
6941 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006942 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006943 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006944 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006945 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006946 continue;
6947 }
6948
Andy Hung8d31fd22023-06-26 19:20:57 -07006949 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006950#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006951 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006952#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006953 // Only consider last track started for volume and mixer state control.
6954 // In theory an older track could underrun and restart after the new one starts
6955 // but as we only care about the transition phase between two tracks on a
6956 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006957 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006958 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006959
Kuowei Li23666472021-01-20 10:23:25 +08006960 if (track->isPausePending()) {
6961 track->pauseAck();
6962 // It is possible a track might have been flushed or stopped.
6963 // Other operations such as flush pending might occur on the next prepare.
6964 if (track->isPausing()) {
6965 track->setPaused();
6966 }
6967 // Always perform pause, as an immediate flush will change
6968 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006969 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006970 doHwPause = true;
6971 mHwPaused = true;
6972 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006973 } else if (track->isFlushPending()) {
6974 track->flushAck();
6975 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006976 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006977 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006978 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006979 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006980 if (last) {
6981 mLeftVolFloat = mRightVolFloat = -1.0;
6982 if (mHwPaused) {
6983 doHwResume = true;
6984 mHwPaused = false;
6985 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006986 }
6987 }
6988
Eric Laurent81784c32012-11-19 14:55:58 -08006989 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006990 // for all its buffers to be filled before processing it.
6991 // Allow draining the buffer in case the client
6992 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006993 // hence the test on (track->retryCount() > 1).
6994 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006995 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6996 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006997 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006998
6999 // target retry count that we will use is based on the time we wait for retries.
7000 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
7001 // the retry threshold is when we accept any size for PCM data. This is slightly
7002 // smaller than the retry count so we can push small bits of data without a glitch.
7003 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08007004 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08007005 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07007006 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007007 minFrames = mNormalFrameCount;
7008 } else {
7009 minFrames = 1;
7010 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007011
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07007012 const size_t framesReady = track->framesReady();
7013 const int trackId = track->id();
7014 if (ATRACE_ENABLED()) {
7015 std::string traceName("nRdy");
7016 traceName += std::to_string(trackId);
7017 ATRACE_INT(traceName.c_str(), framesReady);
7018 }
7019 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07007020 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08007021 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07007022 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08007023
Andy Hung8d31fd22023-06-26 19:20:57 -07007024 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7025 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007026 if (last) {
7027 // make sure processVolume_l() will apply new volume even if 0
7028 mLeftVolFloat = mRightVolFloat = -1.0;
7029 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08007030 if (!mHwSupportsPause) {
7031 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08007032 }
7033 }
7034
7035 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08007036 processVolume_l(track, last);
7037 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007038 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007039 if (previousTrack != 0) {
7040 if (track != previousTrack.get()) {
7041 // Flush any data still being written from last track
7042 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07007043 // Invalidate previous track to force a seek when resuming.
7044 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007045 }
7046 }
7047 mPreviousTrack = track;
7048
Eric Laurentd595b7c2013-04-03 17:27:56 -07007049 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07007050 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08007051 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07007052 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07007053 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007054 doHwResume = true;
7055 mHwPaused = false;
7056 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007057 }
Eric Laurent81784c32012-11-19 14:55:58 -08007058 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07007059 // clear effect chain input buffer if the last active track started underruns
7060 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07007061 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08007062 mEffectChains[0]->clearInputBuffer();
7063 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007064 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007065 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07007066 if (last && mHwPaused) {
7067 doHwResume = true;
7068 mHwPaused = false;
7069 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007070 }
7071 if ((track->sharedBuffer() != 0) || track->isStopped() ||
7072 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007073 // We have consumed all the buffers of this track.
7074 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04007075 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07007076 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04007077 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08007078 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04007079 if (presComplete) {
7080 mOutput->presentationComplete();
7081 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07007082 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007083 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07007084 }
Eric Laurent81784c32012-11-19 14:55:58 -08007085 if (track->isStopped()) {
7086 track->reset();
7087 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07007088 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08007089 }
7090 } else {
7091 // No buffers for this track. Give it a few chances to
7092 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07007093 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02007094 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007095 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007096 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007097 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007098 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08007099 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007100 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7101 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08007102 tracksToRemove->add(track);
7103 // indicate to client process that the track was disabled because of
7104 // underrun; it will then automatically call start() when data is available
7105 track->disable();
7106 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
7107 // unlike mixerthread, HAL can be paused for direct output
7108 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
7109 "minFrames = %u, mFormat = %#x",
7110 framesReady, minFrames, mFormat);
7111 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
7112 doHwPause = true;
7113 mHwPaused = true;
7114 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007115 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08007116 } else if (last) {
7117 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08007118 }
7119 }
7120 }
7121 }
7122
Eric Laurentd1f69b02014-12-15 14:33:13 -08007123 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07007124 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007125 for (size_t i = 0; i < mTracks.size(); i++) {
7126 if (mTracks[i]->isFlushPending()) {
7127 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007128 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007129 }
7130 }
7131 }
7132
7133 // make sure the pause/flush/resume sequence is executed in the right order.
7134 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7135 // before flush and then resume HW. This can happen in case of pause/flush/resume
7136 // if resume is received before pause is executed.
7137 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007138 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007139 status_t result = mOutput->stream->pause();
7140 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007141 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007142 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007143 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007144 flushHw_l();
7145 }
7146 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007147 status_t result = mOutput->stream->resume();
7148 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007149 }
Eric Laurent81784c32012-11-19 14:55:58 -08007150 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007151 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007152
7153 return mixerStatus;
7154}
7155
Andy Hungee58e4a2023-07-07 13:47:37 -07007156void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007157{
Eric Laurent81784c32012-11-19 14:55:58 -08007158 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007159 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007160 // output audio to hardware
7161 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007162 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007163 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007164 status_t status = mActiveTrack->getNextBuffer(&buffer);
7165 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007166 // no need to pad with 0 for compressed audio
7167 if (audio_has_proportional_frames(mFormat)) {
7168 memset(curBuf, 0, frameCount * mFrameSize);
7169 }
Eric Laurent81784c32012-11-19 14:55:58 -08007170 break;
7171 }
7172 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7173 frameCount -= buffer.frameCount;
7174 curBuf += buffer.frameCount * mFrameSize;
7175 mActiveTrack->releaseBuffer(&buffer);
7176 }
Andy Hung2098f272014-02-27 14:00:06 -08007177 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007178 mSleepTimeUs = 0;
7179 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007180 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007181}
7182
Andy Hungee58e4a2023-07-07 13:47:37 -07007183void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007184{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007185 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007186 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007187 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007188 return;
7189 }
Andy Hung85ba3332021-04-27 17:40:26 -07007190 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7191 mSleepTimeUs = mActiveSleepTimeUs;
7192 } else {
7193 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007194 }
Andy Hung85ba3332021-04-27 17:40:26 -07007195 // Note: In S or later, we do not write zeroes for
7196 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007197}
7198
Andy Hungee58e4a2023-07-07 13:47:37 -07007199void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007200{
7201 {
Andy Hung972bec12023-08-31 16:13:39 -07007202 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007203 for (size_t i = 0; i < mTracks.size(); i++) {
7204 if (mTracks[i]->isFlushPending()) {
7205 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007206 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007207 }
7208 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007209 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007210 flushHw_l();
7211 }
7212 }
7213 PlaybackThread::threadLoop_exit();
7214}
7215
7216// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007217bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007218{
7219 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007220 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007221 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007222
Eric Laurent022a5132024-04-12 17:02:51 +00007223 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007224 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007225 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007226 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007227 const auto& mainTrack = mTracks[mTracks.size() - 1];
7228
7229 trackPaused = mainTrack->isPaused();
7230 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7231 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007232 }
7233
Eric Laurent022a5132024-04-12 17:02:51 +00007234 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007235}
7236
Andy Hungc5007f82023-08-29 14:26:09 -07007237// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007238bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007239 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007240{
7241 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007242 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007243
Eric Laurent10351942014-05-08 18:49:52 -07007244 AudioParameter param = AudioParameter(keyValuePair);
7245 int value;
7246 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007247 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007248 }
Eric Laurent10351942014-05-08 18:49:52 -07007249 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7250 // do not accept frame count changes if tracks are open as the track buffer
7251 // size depends on frame count and correct behavior would not be garantied
7252 // if frame count is changed after track creation
7253 if (!mTracks.isEmpty()) {
7254 status = INVALID_OPERATION;
7255 } else {
7256 reconfig = true;
7257 }
7258 }
7259 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007260 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007261 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007262 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007263 if (!mStandby) {
7264 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007265 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007266 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007267 }
Eric Laurent10351942014-05-08 18:49:52 -07007268 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007269 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007270 }
7271 if (status == NO_ERROR && reconfig) {
7272 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007273 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007274 }
7275 }
7276
Dean Wheatley68918102021-03-19 22:09:19 +11007277 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007278}
7279
Andy Hungee58e4a2023-07-07 13:47:37 -07007280uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007281{
7282 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007283 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007284 time = PlaybackThread::activeSleepTimeUs();
7285 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007286 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007287 }
7288 return time;
7289}
7290
Andy Hungee58e4a2023-07-07 13:47:37 -07007291uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007292{
7293 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007294 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007295 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7296 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007297 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007298 }
7299 return time;
7300}
7301
Andy Hungee58e4a2023-07-07 13:47:37 -07007302uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007303{
7304 uint32_t time;
Andy Hunge8273252024-08-07 16:42:42 -07007305 if (audio_has_proportional_frames(mFormat) && mType != OFFLOAD) {
Eric Laurent81784c32012-11-19 14:55:58 -08007306 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7307 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007308 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007309 }
7310 return time;
7311}
7312
Andy Hungee58e4a2023-07-07 13:47:37 -07007313void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007314{
7315 PlaybackThread::cacheParameters_l();
7316
7317 // use shorter standby delay as on normal output to release
7318 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007319 // no delay on outputs with HW A/V sync
7320 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007321 mStandbyDelayNs = 0;
Andy Hunge8273252024-08-07 16:42:42 -07007322 } else if (mType == OFFLOAD) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007323 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007324 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007325 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007326 }
Eric Laurent81784c32012-11-19 14:55:58 -08007327}
7328
Andy Hungee58e4a2023-07-07 13:47:37 -07007329void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007330{
ziyangch8f194f12021-12-01 13:48:04 -08007331 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007332 mOutput->flush();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007333 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007334 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007335 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007336 mMonotonicFrameCounter.onFlush();
Haofan Wang0770bc82024-10-03 17:37:55 +00007337 // We do not reset mHwPaused which is hidden from the Track client.
7338 // Note: the client track in Tracks.cpp and AudioTrack.cpp
7339 // has a FLUSHED state but the DirectOutputThread does not;
7340 // those tracks will continue to show isStopped().
Eric Laurente659ef42014-09-29 13:06:46 -07007341}
7342
Andy Hungee58e4a2023-07-07 13:47:37 -07007343int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007344 // If a VolumeShaper is active, we must wake up periodically to update volume.
7345 const int64_t NS_PER_MS = 1000000;
7346 return mVolumeShaperActive ?
7347 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7348}
7349
Eric Laurent81784c32012-11-19 14:55:58 -08007350// ----------------------------------------------------------------------------
7351
Andy Hungee58e4a2023-07-07 13:47:37 -07007352AsyncCallbackThread::AsyncCallbackThread(
7353 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007354 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007355 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007356 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007357 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007358 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007359{
7360}
7361
Andy Hungee58e4a2023-07-07 13:47:37 -07007362void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007363{
7364 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7365}
7366
Andy Hungee58e4a2023-07-07 13:47:37 -07007367bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007368{
7369 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007370 uint32_t writeAckSequence;
7371 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007372 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007373
7374 {
Andy Hungc5007f82023-08-29 14:26:09 -07007375 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007376 while (!((mWriteAckSequence & 1) ||
7377 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007378 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007379 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007380 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007381 }
7382
Eric Laurentbfb1b832013-01-07 09:53:42 -08007383 if (exitPending()) {
7384 break;
7385 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007386 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7387 mWriteAckSequence, mDrainSequence);
7388 writeAckSequence = mWriteAckSequence;
7389 mWriteAckSequence &= ~1;
7390 drainSequence = mDrainSequence;
7391 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007392 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007393 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007394 }
7395 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007396 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007397 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007398 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007399 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007400 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007401 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007402 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007403 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007404 if (asyncError != ASYNC_ERROR_NONE) {
7405 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007406 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007407 }
7408 }
7409 }
7410 return false;
7411}
7412
Andy Hungee58e4a2023-07-07 13:47:37 -07007413void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007414{
7415 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007416 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007417 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007418 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007419}
7420
Andy Hungee58e4a2023-07-07 13:47:37 -07007421void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007422{
Andy Hung972bec12023-08-31 16:13:39 -07007423 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007424 // bit 0 is cleared
7425 mWriteAckSequence = sequence << 1;
7426}
7427
Andy Hungee58e4a2023-07-07 13:47:37 -07007428void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007429{
Andy Hung972bec12023-08-31 16:13:39 -07007430 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007431 // ignore unexpected callbacks
7432 if (mWriteAckSequence & 2) {
7433 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007434 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007435 }
7436}
7437
Andy Hungee58e4a2023-07-07 13:47:37 -07007438void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007439{
Andy Hung972bec12023-08-31 16:13:39 -07007440 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007441 // bit 0 is cleared
7442 mDrainSequence = sequence << 1;
7443}
7444
Andy Hungee58e4a2023-07-07 13:47:37 -07007445void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007446{
Andy Hung972bec12023-08-31 16:13:39 -07007447 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007448 // ignore unexpected callbacks
7449 if (mDrainSequence & 2) {
7450 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007451 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007452 }
7453}
7454
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007455void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007456{
Andy Hung972bec12023-08-31 16:13:39 -07007457 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007458 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007459 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007460}
7461
Eric Laurentbfb1b832013-01-07 09:53:42 -08007462
7463// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007464
7465/* static */
7466sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007467 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007468 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7469 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007470 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007471}
7472
Andy Hung583043b2023-07-17 17:05:00 -07007473OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007474 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7475 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007476 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007477 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007478{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007479 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007480 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007481 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007482}
7483
Andy Hungee58e4a2023-07-07 13:47:37 -07007484void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007485{
7486 if (mFlushPending || mHwPaused) {
7487 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007488 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007489 flushHw_l();
7490 } else {
7491 mMixerStatus = MIXER_DRAIN_ALL;
7492 threadLoop_drain();
7493 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007494 if (mUseAsyncWrite) {
7495 ALOG_ASSERT(mCallbackThread != 0);
7496 mCallbackThread->exit();
7497 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007498 PlaybackThread::threadLoop_exit();
7499}
7500
Andy Hungee58e4a2023-07-07 13:47:37 -07007501PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007502 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007503)
7504{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007505 size_t count = mActiveTracks.size();
7506
7507 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007508 bool doHwPause = false;
7509 bool doHwResume = false;
7510
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007511 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007512
Eric Laurentbfb1b832013-01-07 09:53:42 -08007513 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007514 for (const sp<IAfTrack>& t : mActiveTracks) {
7515 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007516#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007517 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007518#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007519 // Only consider last track started for volume and mixer state control.
7520 // In theory an older track could underrun and restart after the new one starts
7521 // but as we only care about the transition phase between two tracks on a
7522 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007523 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007524 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007525
Haynes Mathew George7844f672014-01-15 12:32:55 -08007526 if (track->isInvalid()) {
7527 ALOGW("An invalidated track shouldn't be in active list");
7528 tracksToRemove->add(track);
7529 continue;
7530 }
7531
Andy Hung8d31fd22023-06-26 19:20:57 -07007532 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007533 ALOGW("An idle track shouldn't be in active list");
7534 continue;
7535 }
7536
Kuowei Li23666472021-01-20 10:23:25 +08007537 if (track->isPausePending()) {
7538 track->pauseAck();
7539 // It is possible a track might have been flushed or stopped.
7540 // Other operations such as flush pending might occur on the next prepare.
7541 if (track->isPausing()) {
7542 track->setPaused();
7543 }
7544 // Always perform pause if last, as an immediate flush will change
7545 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007546 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007547 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007548 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007549 mHwPaused = true;
7550 }
7551 // If we were part way through writing the mixbuffer to
7552 // the HAL we must save this until we resume
7553 // BUG - this will be wrong if a different track is made active,
7554 // in that case we want to discard the pending data in the
7555 // mixbuffer and tell the client to present it again when the
7556 // track is resumed
7557 mPausedWriteLength = mCurrentWriteLength;
7558 mPausedBytesRemaining = mBytesRemaining;
7559 mBytesRemaining = 0; // stop writing
7560 }
7561 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007562 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007563 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007564 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007565 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007566 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007567 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007568 track->flushAck();
7569 if (last) {
7570 mFlushPending = true;
7571 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007572 } else if (track->isResumePending()){
7573 track->resumeAck();
7574 if (last) {
7575 if (mPausedBytesRemaining) {
7576 // Need to continue write that was interrupted
7577 mCurrentWriteLength = mPausedWriteLength;
7578 mBytesRemaining = mPausedBytesRemaining;
7579 mPausedBytesRemaining = 0;
7580 }
7581 if (mHwPaused) {
7582 doHwResume = true;
7583 mHwPaused = false;
7584 // threadLoop_mix() will handle the case that we need to
7585 // resume an interrupted write
7586 }
7587 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007588 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007589
Eric Laurent3df841a2016-07-15 15:15:40 -07007590 mLeftVolFloat = mRightVolFloat = -1.0;
7591
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007592 // Do not handle new data in this iteration even if track->framesReady()
7593 mixerStatus = MIXER_TRACKS_ENABLED;
7594 }
7595 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007596 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007597 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007598 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7599 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007600 if (last) {
7601 // make sure processVolume_l() will apply new volume even if 0
7602 mLeftVolFloat = mRightVolFloat = -1.0;
7603 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007604 }
7605
7606 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007607 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007608 if (previousTrack != 0) {
7609 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007610 // Flush any data still being written from last track
7611 mBytesRemaining = 0;
7612 if (mPausedBytesRemaining) {
7613 // Last track was paused so we also need to flush saved
7614 // mixbuffer state and invalidate track so that it will
7615 // re-submit that unwritten data when it is next resumed
7616 mPausedBytesRemaining = 0;
7617 // Invalidate is a bit drastic - would be more efficient
7618 // to have a flag to tell client that some of the
7619 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007620 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007621 }
7622 // flush data already sent to the DSP if changing audio session as audio
7623 // comes from a different source. Also invalidate previous track to force a
7624 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007625 if (previousTrack->sessionId() != track->sessionId()) {
7626 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007627 }
7628 }
7629 }
7630 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007631 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007632 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007633 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007634 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007635 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007636 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007637 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007638 mixerStatus = MIXER_TRACKS_READY;
7639 }
7640 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007641 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007642 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007643 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007644 // Hardware buffer can hold a large amount of audio so we must
7645 // wait for all current track's data to drain before we say
7646 // that the track is stopped.
7647 if (mBytesRemaining == 0) {
7648 // Only start draining when all data in mixbuffer
7649 // has been written
7650 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007651 track->setState(IAfTrackBase::STOPPING_2);
7652 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007653 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7654 if (last && !mStandby) {
7655 // do not modify drain sequence if we are already draining. This happens
7656 // when resuming from pause after drain.
7657 if ((mDrainSequence & 1) == 0) {
7658 mSleepTimeUs = 0;
7659 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7660 mixerStatus = MIXER_DRAIN_TRACK;
7661 mDrainSequence += 2;
7662 }
7663 if (mHwPaused) {
7664 // It is possible to move from PAUSED to STOPPING_1 without
7665 // a resume so we must ensure hardware is running
7666 doHwResume = true;
7667 mHwPaused = false;
7668 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007669 }
7670 }
Eric Laurente93cc032016-05-05 10:15:10 -07007671 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007672 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007673 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007674 }
7675 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007676 // Drain has completed or we are in standby, signal presentation complete
7677 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007678 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007679 mOutput->presentationComplete();
7680 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007681 track->reset();
7682 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007683 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007684 if (!mUseAsyncWrite) {
7685 // If we don't get explicit drain notification we must
7686 // register discontinuity regardless of whether this is
7687 // the previous (!last) or the upcoming (last) track
7688 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007689 mTimestampVerifier.discontinuity(
7690 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007691 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007692 }
7693 } else {
7694 // No buffers for this track. Give it a few chances to
7695 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007696 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007697 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007698 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007699 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007700 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007701 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007702 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7703 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007704 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007705 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007706 // it will then automatically call start() when data is available
7707 track->disable();
7708 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007709 } else if (last){
7710 mixerStatus = MIXER_TRACKS_ENABLED;
7711 }
7712 }
7713 }
7714 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007715 if (track->isReady()) { // check ready to prevent premature start.
7716 processVolume_l(track, last);
7717 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007718 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007719
Eric Laurentea0fade2013-10-04 16:23:48 -07007720 // make sure the pause/flush/resume sequence is executed in the right order.
7721 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7722 // before flush and then resume HW. This can happen in case of pause/flush/resume
7723 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007724 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007725 status_t result = mOutput->stream->pause();
7726 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007727 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007728 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007729 if (mFlushPending) {
7730 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007731 }
Eric Laurentfd477972013-10-25 18:10:40 -07007732 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007733 status_t result = mOutput->stream->resume();
7734 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007735 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007736
Eric Laurentbfb1b832013-01-07 09:53:42 -08007737 // remove all the tracks that need to be...
7738 removeTracks_l(*tracksToRemove);
7739
7740 return mixerStatus;
7741}
7742
Eric Laurentbfb1b832013-01-07 09:53:42 -08007743// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007744bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007745{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007746 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7747 mWriteAckSequence, mDrainSequence);
7748 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007749 return true;
7750 }
7751 return false;
7752}
7753
Andy Hungee58e4a2023-07-07 13:47:37 -07007754bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007755{
Andy Hung972bec12023-08-31 16:13:39 -07007756 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007757 return waitingAsyncCallback_l();
7758}
7759
Andy Hungee58e4a2023-07-07 13:47:37 -07007760void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007761{
Eric Laurente659ef42014-09-29 13:06:46 -07007762 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007763 // Flush anything still waiting in the mixbuffer
7764 mCurrentWriteLength = 0;
7765 mBytesRemaining = 0;
7766 mPausedWriteLength = 0;
7767 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007768 // reset bytes written count to reflect that DSP buffers are empty after flush.
7769 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007770
Eric Laurentbfb1b832013-01-07 09:53:42 -08007771 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007772 // discard any pending drain or write ack by incrementing sequence
7773 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7774 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007775 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007776 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7777 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007778 }
7779}
7780
Andy Hungee58e4a2023-07-07 13:47:37 -07007781void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007782{
Andy Hung972bec12023-08-31 16:13:39 -07007783 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007784 if (PlaybackThread::invalidateTracks_l(streamType)) {
7785 mFlushPending = true;
7786 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007787}
7788
Andy Hungee58e4a2023-07-07 13:47:37 -07007789void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007790 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007791 if (PlaybackThread::invalidateTracks_l(portIds)) {
7792 mFlushPending = true;
7793 }
7794}
7795
Eric Laurentbfb1b832013-01-07 09:53:42 -08007796// ----------------------------------------------------------------------------
7797
Andy Hungee58e4a2023-07-07 13:47:37 -07007798/* static */
7799sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007800 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007801 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007802 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007803}
7804
Andy Hung583043b2023-07-17 17:05:00 -07007805DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007806 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007807 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007808 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007809 mWaitTimeMs(UINT_MAX)
7810{
7811 addOutputTrack(mainThread);
7812}
7813
Andy Hungee58e4a2023-07-07 13:47:37 -07007814DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007815{
7816 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7817 mOutputTracks[i]->destroy();
7818 }
7819}
7820
Andy Hungee58e4a2023-07-07 13:47:37 -07007821void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007822{
7823 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007824 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007825 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007826 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007827 if (mMixerBufferValid) {
7828 memset(mMixerBuffer, 0, mMixerBufferSize);
7829 } else {
7830 memset(mSinkBuffer, 0, mSinkBufferSize);
7831 }
Eric Laurent81784c32012-11-19 14:55:58 -08007832 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007833 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007834 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007835 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007836 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007837}
7838
Andy Hungee58e4a2023-07-07 13:47:37 -07007839void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007840{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007841 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007842 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007843 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007844 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007845 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007846 }
7847 } else if (mBytesWritten != 0) {
7848 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7849 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007850 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007851 } else {
7852 // flush remaining overflow buffers in output tracks
7853 writeFrames = 0;
7854 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007855 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007856 }
7857}
7858
Andy Hungee58e4a2023-07-07 13:47:37 -07007859ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007860{
Jiabin Huang4d0c9e82024-10-28 21:51:36 +00007861 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08007862 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007863 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7864
7865 // Consider the first OutputTrack for timestamp and frame counting.
7866
7867 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7868 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7869 // we always claim success.
7870 if (i == 0) {
7871 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7872 ALOGD_IF(correction != 0 && writeFrames != 0,
7873 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7874 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7875 mFramesWritten -= correction;
7876 }
7877
7878 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007879 }
Jiabin Huang4d0c9e82024-10-28 21:51:36 +00007880 ATRACE_END();
Andy Hungcf10d742020-04-28 15:38:24 -07007881 if (mStandby) {
7882 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007883 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007884 mStandby = false;
7885 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007886 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007887}
7888
Andy Hungee58e4a2023-07-07 13:47:37 -07007889void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007890{
7891 // DuplicatingThread implements standby by stopping all tracks
7892 for (size_t i = 0; i < outputTracks.size(); i++) {
7893 outputTracks[i]->stop();
7894 }
7895}
7896
Andy Hung8a5abfd2023-12-07 19:35:12 -08007897void DuplicatingThread::threadLoop_exit()
7898{
7899 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7900 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7901 // Do so here in the threadLoop_exit().
7902
7903 SortedVector <sp<IAfOutputTrack>> localTracks;
7904 {
7905 audio_utils::lock_guard l(mutex());
7906 localTracks = std::move(mOutputTracks);
7907 mOutputTracks.clear();
jiabinc62d6032024-09-03 23:39:57 +00007908 for (size_t i = 0; i < localTracks.size(); ++i) {
7909 localTracks[i]->destroy();
7910 }
Andy Hung8a5abfd2023-12-07 19:35:12 -08007911 }
7912 localTracks.clear();
7913 outputTracks.clear();
7914 PlaybackThread::threadLoop_exit();
7915}
7916
Andy Hungee58e4a2023-07-07 13:47:37 -07007917void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007918{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007919 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007920
7921 std::stringstream ss;
7922 const size_t numTracks = mOutputTracks.size();
7923 ss << " " << numTracks << " OutputTracks";
7924 if (numTracks > 0) {
7925 ss << ":";
7926 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007927 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007928 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007929 if (thread.get() != nullptr) {
7930 ss << thread.get() << ", " << thread->id();
7931 } else {
7932 ss << "null";
7933 }
7934 ss << ")";
7935 }
7936 }
7937 ss << "\n";
7938 std::string result = ss.str();
7939 write(fd, result.c_str(), result.size());
7940}
7941
Andy Hungee58e4a2023-07-07 13:47:37 -07007942void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007943{
7944 outputTracks = mOutputTracks;
7945}
7946
Andy Hungee58e4a2023-07-07 13:47:37 -07007947void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007948{
7949 outputTracks.clear();
7950}
7951
Andy Hungee58e4a2023-07-07 13:47:37 -07007952void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007953{
Andy Hung972bec12023-08-31 16:13:39 -07007954 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007955 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7956 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7957 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7958 const size_t frameCount =
7959 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7960 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7961 // from different OutputTracks and their associated MixerThreads (e.g. one may
7962 // nearly empty and the other may be dropping data).
7963
Svet Ganov33761132021-05-13 22:51:08 +00007964 // TODO b/182392769: use attribution source util, move to server edge
7965 AttributionSourceState attributionSource = AttributionSourceState();
7966 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007967 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007968 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007969 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007970 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007971 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007972 this,
7973 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007974 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007975 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007976 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007977 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007978 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7979 if (status != NO_ERROR) {
7980 ALOGE("addOutputTrack() initCheck failed %d", status);
7981 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007982 }
Andy Hung6b137d12024-08-27 22:35:17 +00007983 if (!audioserver_flags::portid_volume_management()) {
Vlad Popa1e865e62024-08-15 19:11:42 -07007984 thread->setStreamVolume(AUDIO_STREAM_PATCH, /*volume=*/1.0f, /*muted=*/false);
Andy Hung6b137d12024-08-27 22:35:17 +00007985 }
Vlad Popa1e865e62024-08-15 19:11:42 -07007986
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007987 mOutputTracks.add(outputTrack);
7988 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7989 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007990}
7991
Andy Hungee58e4a2023-07-07 13:47:37 -07007992void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007993{
Andy Hung972bec12023-08-31 16:13:39 -07007994 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007995 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7996 if (mOutputTracks[i]->thread() == thread) {
7997 mOutputTracks[i]->destroy();
7998 mOutputTracks.removeAt(i);
7999 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07008000 // NO_THREAD_SAFETY_ANALYSIS
8001 // Lambda workaround: as thread != this
8002 // we can safely call the remote thread getOutput.
8003 const bool equalOutput =
8004 [&](){ return thread->getOutput() == mOutput; }();
8005 if (equalOutput) {
8006 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07008007 }
Eric Laurent81784c32012-11-19 14:55:58 -08008008 return;
8009 }
8010 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07008011 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08008012}
8013
Andy Hungc5007f82023-08-29 14:26:09 -07008014// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07008015void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008016{
8017 mWaitTimeMs = UINT_MAX;
8018 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07008019 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008020 if (strong != 0) {
8021 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
8022 if (waitTimeMs < mWaitTimeMs) {
8023 mWaitTimeMs = waitTimeMs;
8024 }
8025 }
8026 }
8027}
8028
Andy Hungee58e4a2023-07-07 13:47:37 -07008029bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08008030{
8031 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07008032 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08008033 if (thread == 0) {
8034 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
8035 outputTracks[i].get());
8036 return false;
8037 }
Andy Hung87c693c2023-07-06 20:56:16 -07008038 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08008039 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07008040 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08008041 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
8042 thread.get());
8043 return false;
8044 }
8045 }
8046 return true;
8047}
8048
Andy Hungee58e4a2023-07-07 13:47:37 -07008049void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07008050 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07008051{
Kevin Rocard12381092018-04-11 09:19:59 -07008052 for (auto& outputTrack : outputTracks) { // not mOutputTracks
8053 outputTrack->setMetadatas(metadata.tracks);
8054 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008055}
8056
Andy Hungee58e4a2023-07-07 13:47:37 -07008057uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08008058{
Andy Hung7a6a0f02023-11-29 13:42:08 -08008059 // return half the wait time in microseconds.
8060 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08008061}
8062
Andy Hungee58e4a2023-07-07 13:47:37 -07008063void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008064{
8065 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
8066 updateWaitTime_l();
8067
8068 MixerThread::cacheParameters_l();
8069}
8070
Eric Laurentb3f315a2021-07-13 15:09:05 +02008071// ----------------------------------------------------------------------------
8072
Andy Hungee58e4a2023-07-07 13:47:37 -07008073/* static */
8074sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07008075 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07008076 AudioStreamOut* output,
8077 audio_io_handle_t id,
8078 bool systemReady,
8079 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07008080 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07008081}
8082
Andy Hung583043b2023-07-17 17:05:00 -07008083SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02008084 AudioStreamOut* output,
8085 audio_io_handle_t id,
8086 bool systemReady,
8087 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07008088 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02008089{
8090}
8091
Andy Hungee58e4a2023-07-07 13:47:37 -07008092void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02008093 // if mSupportedLatencyModes is empty, the HAL stream does not support
8094 // latency mode control and we can exit.
8095 if (mSupportedLatencyModes.empty()) {
8096 return;
8097 }
Eric Laurent4c85e372024-02-23 16:50:06 +00008098 // Do not update the HAL latency mode if no track is active
8099 if (mActiveTracks.isEmpty()) {
8100 return;
8101 }
8102
Eric Laurent68a40a82022-05-03 18:15:04 +02008103 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
8104 if (mSupportedLatencyModes.size() == 1) {
8105 // If the HAL only support one latency mode currently, confirm the choice
8106 latencyMode = mSupportedLatencyModes[0];
8107 } else if (mSupportedLatencyModes.size() > 1) {
8108 // Request low latency if:
8109 // - The low latency mode is requested by the spatializer controller
8110 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
8111 // AND
8112 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02008113 for (const auto& track : mActiveTracks) {
8114 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01008115 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02008116 break;
8117 }
8118 }
Eric Laurent68a40a82022-05-03 18:15:04 +02008119 }
8120
8121 if (latencyMode != mSetLatencyMode) {
8122 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08008123 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
8124 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02008125 if (status == NO_ERROR) {
8126 mSetLatencyMode = latencyMode;
8127 }
8128 }
8129}
8130
Andy Hungee58e4a2023-07-07 13:47:37 -07008131status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01008132 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02008133 return BAD_VALUE;
8134 }
Andy Hung972bec12023-08-31 16:13:39 -07008135 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02008136 mRequestedLatencyMode = mode;
8137 return NO_ERROR;
8138}
8139
Andy Hungee58e4a2023-07-07 13:47:37 -07008140void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07008141NO_THREAD_SAFETY_ANALYSIS
8142// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02008143{
8144 bool hasVirtualizer = false;
8145 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07008146 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008147 {
Andy Hung972bec12023-08-31 16:13:39 -07008148 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008149 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008150 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008151 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008152 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8153 }
8154
8155 finalDownMixer = mFinalDownMixer;
8156 mFinalDownMixer.clear();
8157 }
8158
8159 if (hasVirtualizer) {
8160 if (finalDownMixer != nullptr) {
8161 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008162 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008163 }
8164 finalDownMixer.clear();
8165 } else if (!hasDownMixer) {
8166 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008167 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008168 EFFECT_UIID_DOWNMIX, &descriptors);
8169 if (status != NO_ERROR) {
8170 return;
8171 }
8172 ALOG_ASSERT(!descriptors.empty(),
8173 "%s getDescriptors() returned no error but empty list", __func__);
8174
8175 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8176 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008177 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008178
8179 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8180 ALOGW("%s error creating downmixer %d", __func__, status);
8181 finalDownMixer.clear();
8182 } else {
8183 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008184 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008185 }
8186 }
8187
8188 {
Andy Hung972bec12023-08-31 16:13:39 -07008189 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008190 mFinalDownMixer = finalDownMixer;
8191 }
8192}
8193
Andy Hunge2514462023-12-06 14:59:24 -08008194void SpatializerThread::threadLoop_exit()
8195{
8196 // The Spatializer EffectHandle must be released on the PlaybackThread
8197 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8198 mFinalDownMixer.clear();
8199
8200 PlaybackThread::threadLoop_exit();
8201}
8202
Eric Laurent81784c32012-11-19 14:55:58 -08008203// ----------------------------------------------------------------------------
8204// Record
8205// ----------------------------------------------------------------------------
8206
Andy Hung583043b2023-07-17 17:05:00 -07008207sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008208 AudioStreamIn* input,
8209 audio_io_handle_t id,
8210 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008211 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008212}
8213
Andy Hung583043b2023-07-17 17:05:00 -07008214RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008215 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008216 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008217 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008218 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008219 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008220 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008221 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008222 mActiveTracks(&this->mLocalLog),
8223 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008224 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008225 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008226 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8227 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008228 // mFastCapture below
8229 , mFastCaptureFutex(0)
8230 // mInputSource
8231 // mPipeSink
8232 // mPipeSource
8233 , mPipeFramesP2(0)
8234 // mPipeMemory
8235 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008236 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008237 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008238{
Glenn Kastend7dca052015-03-05 16:05:54 -08008239 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008240 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008241
George Burgess IVa8f90c12020-05-14 11:27:19 -07008242 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008243 mIsMsdDevice = strcmp(
8244 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8245 }
8246
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008247 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008248
Andy Hungc8fddf32018-08-08 18:32:37 -07008249 // TODO: We may also match on address as well as device type for
8250 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008251 // TODO: This property should be ensure that only contains one single device type.
8252 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8253 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008254 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8255 : AUDIO_DEVICE_NONE));
8256
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008257 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008258 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008259 size_t numCounterOffers = 0;
8260 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008261#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008262 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008263#else
8264 (void)
8265#endif
8266 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008267 ALOG_ASSERT(index == 0);
8268
8269 // initialize fast capture depending on configuration
8270 bool initFastCapture;
8271 switch (kUseFastCapture) {
8272 case FastCapture_Never:
8273 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008274 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008275 break;
8276 case FastCapture_Always:
8277 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008278 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279 break;
8280 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008281 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008282 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008283 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008284 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8285 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8286 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008287 break;
8288 // case FastCapture_Dynamic:
8289 }
8290
8291 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008292 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008293 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008294 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8295 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008296 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008297 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008298 const sp<MemoryDealer> roHeap(readOnlyHeap());
8299 sp<IMemory> pipeMemory;
8300 if ((roHeap == 0) ||
8301 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008302 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008303 ALOGE("not enough memory for pipe buffer size=%zu; "
8304 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8305 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8306 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008307 goto failed;
8308 }
8309 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8310 memset(pipeBuffer, 0, pipeSize);
8311 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008312 const NBAIO_Format offersFast[1] = {format};
8313 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008314 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008315 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008316 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008317 mPipeSink = pipe;
8318 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008319 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008320 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008321 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008322 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008323 mPipeSource = pipeReader;
8324 mPipeFramesP2 = pipeFramesP2;
8325 mPipeMemory = pipeMemory;
8326
8327 // create fast capture
8328 mFastCapture = new FastCapture();
8329 FastCaptureStateQueue *sq = mFastCapture->sq();
8330#ifdef STATE_QUEUE_DUMP
8331 // FIXME
8332#endif
8333 FastCaptureState *state = sq->begin();
8334 state->mCblk = NULL;
8335 state->mInputSource = mInputSource.get();
8336 state->mInputSourceGen++;
8337 state->mPipeSink = pipe;
8338 state->mPipeSinkGen++;
8339 state->mFrameCount = mFrameCount;
8340 state->mCommand = FastCaptureState::COLD_IDLE;
8341 // already done in constructor initialization list
8342 //mFastCaptureFutex = 0;
8343 state->mColdFutexAddr = &mFastCaptureFutex;
8344 state->mColdGen++;
8345 state->mDumpState = &mFastCaptureDumpState;
8346#ifdef TEE_SINK
8347 // FIXME
8348#endif
Andy Hung583043b2023-07-17 17:05:00 -07008349 mFastCaptureNBLogWriter =
8350 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008351 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8352 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07008353 {
8354 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastCapture->getTid());
8355 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8356 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008357 // start the fast capture
8358 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8359 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008360 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008361 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008362#ifdef AUDIO_WATCHDOG
8363 // FIXME
8364#endif
8365
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008366 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008367 }
Andy Hung8946a282018-04-19 20:04:56 -07008368#ifdef TEE_SINK
8369 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8370 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8371#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008372failed: ;
8373
8374 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008375}
8376
Andy Hungee58e4a2023-07-07 13:47:37 -07008377RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008378{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008379 if (mFastCapture != 0) {
8380 FastCaptureStateQueue *sq = mFastCapture->sq();
8381 FastCaptureState *state = sq->begin();
8382 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8383 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8384 if (old == -1) {
8385 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8386 }
8387 }
8388 state->mCommand = FastCaptureState::EXIT;
8389 sq->end();
Andy Hung82f39d62024-09-30 17:19:14 -07008390 {
8391 audio_utils::mutex::scoped_join_wait_check queueWaitCheck(mFastCapture->getTid());
8392 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8393 mFastCapture->join();
8394 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008395 mFastCapture.clear();
8396 }
Andy Hung583043b2023-07-17 17:05:00 -07008397 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8398 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008399 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008400}
8401
Andy Hungee58e4a2023-07-07 13:47:37 -07008402void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008403{
Glenn Kastend7dca052015-03-05 16:05:54 -08008404 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008405}
8406
Andy Hungee58e4a2023-07-07 13:47:37 -07008407void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008408{
8409 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008410 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008411 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008412 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008413 track->invalidate();
8414 }
8415 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008416 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008417}
8418
Andy Hungee58e4a2023-07-07 13:47:37 -07008419bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008420{
Eric Laurent81784c32012-11-19 14:55:58 -08008421 nsecs_t lastWarning = 0;
8422
8423 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008424
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008425reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008426 {
Andy Hung972bec12023-08-31 16:13:39 -07008427 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008428 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008429 }
8430
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008431 // used to request a deferred sleep, to be executed later while mutex is unlocked
8432 uint32_t sleepUs = 0;
8433
Andy Hung95c94a22023-10-20 16:41:18 -07008434 // timestamp correction enable is determined under lock, used in processing step.
8435 bool timestampCorrectionEnabled = false;
8436
Andy Hung446f4df2019-02-21 12:26:41 -08008437 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8438
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008439 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008440 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008441 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8442 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008443 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008444 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008445
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008446 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008447 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008448
Glenn Kasten735f45f2014-08-18 15:51:59 -07008449 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008450 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008451
Glenn Kasten735f45f2014-08-18 15:51:59 -07008452 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008453 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008454
Eric Laurent33403f02020-05-29 18:35:06 -07008455 bool silenceFastCapture = false;
8456
Andy Hungc5007f82023-08-29 14:26:09 -07008457 { // scope for mutex()
8458 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008459
Eric Laurent021cf962014-05-13 10:18:14 -07008460 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008461
Eric Laurent000a4192014-01-29 15:17:32 -08008462 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008463 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008464 if (exitPending()) {
8465 break;
8466 }
8467
Eric Laurent5c25d562016-07-13 17:17:45 -07008468 // sleep with mutex unlocked
8469 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008470 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008471 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008472 ATRACE_END();
8473 sleepUs = 0;
8474 continue;
8475 }
8476
Glenn Kasten2b806402013-11-20 16:37:38 -08008477 // if no active track(s), then standby and release wakelock
8478 size_t size = mActiveTracks.size();
8479 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008480 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008481 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008482 releaseWakeLock_l();
8483 ALOGV("RecordThread: loop stopping");
8484 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008485 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008486 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008487 goto reacquire_wakelock;
8488 }
8489
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008490 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008491 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008492 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008493 if (activeTrack) { // ensure track release is outside lock.
8494 oldActiveTracks.emplace_back(std::move(activeTrack));
8495 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008496 activeTrack = mActiveTracks[i];
8497 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008498 if (activeTrack->isFastTrack()) {
8499 ALOG_ASSERT(fastTrackToRemove == 0);
8500 fastTrackToRemove = activeTrack;
8501 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008502 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008503 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008504 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008505 continue;
8506 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008507
Andy Hung8d31fd22023-06-26 19:20:57 -07008508 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008509 switch (activeTrackState) {
8510
Andy Hung8d31fd22023-06-26 19:20:57 -07008511 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008512 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008513 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008514 if (activeTrack->isFastTrack()) {
8515 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8516 // Keep a ref on fast track to wait for FastCapture thread to get updated
8517 // state before potential track removal
8518 fastTrackToRemove = activeTrack;
8519 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008520 doBroadcast = true;
8521 size--;
8522 continue;
8523
Andy Hung8d31fd22023-06-26 19:20:57 -07008524 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008525 sleepUs = 10000;
8526 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008527 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008528 continue;
8529
Andy Hung8d31fd22023-06-26 19:20:57 -07008530 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008531 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008532 if (mStandby) {
8533 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008534 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008535 mStandby = false;
8536 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008537 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008538 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008539 break;
8540
Andy Hung8d31fd22023-06-26 19:20:57 -07008541 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008542 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008543 break;
8544
Andy Hung8d31fd22023-06-26 19:20:57 -07008545 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8546 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8547 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008548 default:
Andy Hungce685402018-10-05 17:23:27 -07008549 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8550 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008551 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008552
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008553 if (activeTrack->isFastTrack()) {
8554 ALOG_ASSERT(!mFastTrackAvail);
8555 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008556 // if the active fast track is silenced either:
8557 // 1) silence the whole capture from fast capture buffer if this is
8558 // the only active track
8559 // 2) invalidate this track: this will cause the client to reconnect and possibly
8560 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008561 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008562 if (activeTrack->isSilenced()) {
8563 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008564 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008565 } else {
8566 silenceFastCapture = true;
8567 }
8568 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008569 // Invalidate fast tracks if access to audio history is required as this is not
8570 // possible with fast tracks. Once the fast track has been invalidated, no new
8571 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8572 if (mMaxSharedAudioHistoryMs != 0) {
8573 invalidate = true;
8574 }
8575 if (invalidate) {
8576 activeTrack->invalidate();
8577 ALOG_ASSERT(fastTrackToRemove == 0);
8578 fastTrackToRemove = activeTrack;
8579 removeTrack_l(activeTrack);
8580 mActiveTracks.remove(activeTrack);
8581 size--;
8582 continue;
8583 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008584 fastTrack = activeTrack;
8585 }
Eric Laurent33403f02020-05-29 18:35:06 -07008586
8587 activeTracks.add(activeTrack);
8588 i++;
8589
Glenn Kasten9e982352013-08-14 14:39:50 -07008590 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008591
Andy Hungab65b182023-09-06 19:41:47 -07008592 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008593
Kevin Rocard069c2712018-03-29 19:09:14 -07008594 updateMetadata_l();
8595
Eric Laurent5c25d562016-07-13 17:17:45 -07008596 if (allStopped) {
8597 standbyIfNotAlreadyInStandby();
8598 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008599 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008600 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008601 }
8602
8603 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008604 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008605 if (sleepUs == 0) {
8606 sleepUs = kRecordThreadSleepUs;
8607 }
8608 continue;
8609 }
8610 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008611
Andy Hung95c94a22023-10-20 16:41:18 -07008612 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008613 lockEffectChains_l(effectChains);
8614 }
8615
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008616 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008617
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008618 size_t size = effectChains.size();
8619 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008620 // thread mutex is not locked, but effect chain is locked
8621 effectChains[i]->process_l();
8622 }
8623
Glenn Kasten735f45f2014-08-18 15:51:59 -07008624 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008625 if (mFastCapture != 0) {
8626 FastCaptureStateQueue *sq = mFastCapture->sq();
8627 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008628 bool didModify = false;
8629 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008630 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8631 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8632 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8633 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8634 if (old == -1) {
8635 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8636 }
8637 }
8638 state->mCommand = FastCaptureState::READ_WRITE;
8639#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008640 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008641 FastThreadDumpState::kSamplingNforLowRamDevice :
8642 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008643#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008644 didModify = true;
8645 }
8646 audio_track_cblk_t *cblkOld = state->mCblk;
8647 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8648 if (cblkNew != cblkOld) {
8649 state->mCblk = cblkNew;
8650 // block until acked if removing a fast track
8651 if (cblkOld != NULL) {
8652 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8653 }
8654 didModify = true;
8655 }
jiabin01c8f562018-07-19 17:47:28 -07008656 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8657 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8658 if (state->mFastPatchRecordBufferProvider != abp) {
8659 state->mFastPatchRecordBufferProvider = abp;
8660 state->mFastPatchRecordFormat = fastTrack == 0 ?
8661 AUDIO_FORMAT_INVALID : fastTrack->format();
8662 didModify = true;
8663 }
Eric Laurent33403f02020-05-29 18:35:06 -07008664 if (state->mSilenceCapture != silenceFastCapture) {
8665 state->mSilenceCapture = silenceFastCapture;
8666 didModify = true;
8667 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008668 sq->end(didModify);
8669 if (didModify) {
8670 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008671#if 0
8672 if (kUseFastCapture == FastCapture_Dynamic) {
8673 mNormalSource = mPipeSource;
8674 }
8675#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008676 }
8677 }
8678
Glenn Kasten735f45f2014-08-18 15:51:59 -07008679 // now run the fast track destructor with thread mutex unlocked
8680 fastTrackToRemove.clear();
8681
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008682 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8683 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8684 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8685 // If destination is non-contiguous, first read past the nominal end of buffer, then
8686 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008687
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008688 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008689 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008690 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008691
8692 // If an NBAIO source is present, use it to read the normal capture's data
8693 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008694 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008695
8696 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8697 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8698 // we immediately retry the read() to get data and prevent another overflow.
8699 for (int retries = 0; retries <= 2; ++retries) {
8700 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8701 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8702 framesToRead);
8703 if (framesRead != OVERRUN) break;
8704 }
8705
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008706 const ssize_t availableToRead = mPipeSource->availableToRead();
8707 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008708 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008709 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008710 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8711 "more frames to read than fifo size, %zd > %zu",
8712 availableToRead, mPipeFramesP2);
8713 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8714 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8715 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8716 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008717 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8718 }
8719 if (framesRead < 0) {
8720 status_t status = (status_t) framesRead;
8721 switch (status) {
8722 case OVERRUN:
8723 ALOGW("overrun on read from pipe");
8724 framesRead = 0;
8725 break;
8726 case NEGOTIATE:
8727 ALOGE("re-negotiation is needed");
8728 framesRead = -1; // Will cause an attempt to recover.
8729 break;
8730 default:
8731 ALOGE("unknown error %d on read from pipe", status);
8732 break;
8733 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008734 }
8735 // otherwise use the HAL / AudioStreamIn directly
8736 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008737 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008738 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008739 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008740 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008741 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008742 if (result < 0) {
8743 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008744 } else {
8745 framesRead = bytesRead / mFrameSize;
8746 }
8747 }
8748
Andy Hung446f4df2019-02-21 12:26:41 -08008749 const int64_t lastIoEndNs = systemTime(); // end IO timing
8750
Andy Hung3f0c9022016-01-15 17:49:46 -08008751 // Update server timestamp with server stats
8752 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008753 if (framesRead >= 0) {
8754 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8755 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8756 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008757
8758 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008759 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008760 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008761 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008762 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8763 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8764 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008765 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008766 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8767
8768 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008769 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008770 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008771 id(), (long long)time, (long long)position);
8772 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8773 position = correctedTimestamp.mFrames;
8774 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008775 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008776 id(), (long long)time, (long long)position);
8777 }
8778
Andy Hung3f0c9022016-01-15 17:49:46 -08008779 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8780 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8781 // Note: In general record buffers should tend to be empty in
8782 // a properly running pipeline.
8783 //
8784 // Also, it is not advantageous to call get_presentation_position during the read
8785 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008786 } else {
8787 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008788 }
8789 }
Andy Hunge6c37112019-02-26 17:38:10 -08008790
8791 // From the timestamp, input read latency is negative output write latency.
8792 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008793 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008794 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8795 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8796 mLatencyMs.add(latencyMs);
8797 }
8798
Andy Hung3f0c9022016-01-15 17:49:46 -08008799 // Use this to track timestamp information
8800 // ALOGD("%s", mTimestamp.toString().c_str());
8801
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008802 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008803 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008804 // Force input into standby so that it tries to recover at next read attempt
8805 inputStandBy();
8806 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008807 }
8808 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008809 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008810 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008811 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008812 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008813
Andy Hung8946a282018-04-19 20:04:56 -07008814#ifdef TEE_SINK
8815 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8816#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008817 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008818 {
8819 size_t part1 = mRsmpInFramesP2 - rear;
8820 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008821 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008822 (framesRead - part1) * mFrameSize);
8823 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008824 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008825 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008826
8827 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008828
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008829 // loop over each active track
8830 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008831 if (activeTrack) { // ensure track release is outside lock.
8832 oldActiveTracks.emplace_back(std::move(activeTrack));
8833 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008834 activeTrack = activeTracks[i];
8835
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008836 // skip fast tracks, as those are handled directly by FastCapture
8837 if (activeTrack->isFastTrack()) {
8838 continue;
8839 }
8840
Andy Hung73c02e42015-03-29 01:13:58 -07008841 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008842 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8843
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008844 enum {
8845 OVERRUN_UNKNOWN,
8846 OVERRUN_TRUE,
8847 OVERRUN_FALSE
8848 } overrun = OVERRUN_UNKNOWN;
8849
8850 // loop over getNextBuffer to handle circular sink
8851 for (;;) {
8852
Andy Hung8d31fd22023-06-26 19:20:57 -07008853 activeTrack->sinkBuffer().frameCount = ~0;
8854 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8855 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008856 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8857
Andy Hung73c02e42015-03-29 01:13:58 -07008858 // check available frames and handle overrun conditions
8859 // if the record track isn't draining fast enough.
8860 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008861 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008862 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008863 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008864 overrun = OVERRUN_TRUE;
8865 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008866 if (framesOut == 0 || framesIn == 0) {
8867 break;
8868 }
8869
Andy Hung6770c6f2015-04-07 13:43:36 -07008870 // Don't allow framesOut to be larger than what is possible with resampling
8871 // from framesIn.
8872 // This isn't strictly necessary but helps limit buffer resizing in
8873 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008874 if (audio_is_linear_pcm(activeTrack->format())) {
8875 framesOut = min(framesOut,
8876 destinationFramesPossible(
8877 framesIn, mSampleRate, activeTrack->sampleRate()));
8878 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008879
8880 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008881 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008882 // straight from RecordThread buffer to RecordTrack buffer.
8883 AudioBufferProvider::Buffer buffer;
8884 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008885 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008886 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008887 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008888 ALOGV_IF(buffer.frameCount != framesOut,
8889 "%s() read less than expected (%zu vs %zu)",
8890 __func__, buffer.frameCount, framesOut);
8891 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008892 memcpy(activeTrack->sinkBuffer().raw,
8893 buffer.raw, buffer.frameCount * mFrameSize);
8894 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008895 } else {
8896 framesOut = 0;
8897 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008898 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008899 }
8900 } else {
8901 // process frames from the RecordThread buffer provider to the RecordTrack
8902 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008903 framesOut = activeTrack->recordBufferConverter()->convert(
8904 activeTrack->sinkBuffer().raw,
8905 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008906 framesOut);
8907 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008908
8909 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8910 overrun = OVERRUN_FALSE;
8911 }
8912
Andy Hung93bb5732023-05-04 21:16:34 -07008913 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8914 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008915 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008916 if (framesToDrop == 0) {
8917 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008918 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008919 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008920 // Sanitize before releasing if the track has no access to the source data
8921 // An idle UID receives silence from non virtual devices until active
8922 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008923 memset(activeTrack->sinkBuffer().raw,
8924 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008925 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008926 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008927 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008928 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008929 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008930 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008931 }
8932 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008933
8934 switch (overrun) {
8935 case OVERRUN_TRUE:
8936 // client isn't retrieving buffers fast enough
8937 if (!activeTrack->setOverflow()) {
8938 nsecs_t now = systemTime();
8939 // FIXME should lastWarning per track?
8940 if ((now - lastWarning) > kWarningThrottleNs) {
8941 ALOGW("RecordThread: buffer overflow");
8942 lastWarning = now;
8943 }
8944 }
8945 break;
8946 case OVERRUN_FALSE:
8947 activeTrack->clearOverflow();
8948 break;
8949 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008950 break;
8951 }
8952
Andy Hung3f0c9022016-01-15 17:49:46 -08008953 // update frame information and push timestamp out
8954 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008955 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008956 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8957 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008958 }
8959
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008960unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008961 // enable changes in effect chain
8962 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008963 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008964 if (audio_has_proportional_frames(mFormat)
8965 && loopCount == lastLoopCountRead + 1) {
8966 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8967 const double jitterMs =
8968 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8969 {framesRead, readPeriodNs},
8970 {0, 0} /* lastTimestamp */, mSampleRate);
8971 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8972
Andy Hung972bec12023-08-31 16:13:39 -07008973 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008974 mIoJitterMs.add(jitterMs);
8975 mProcessTimeMs.add(processMs);
8976 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008977 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008978 // update timing info.
8979 mLastIoBeginNs = lastIoBeginNs;
8980 mLastIoEndNs = lastIoEndNs;
8981 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008982 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008983 mThreadloopExecutor.process(); // process any remaining deferred actions.
8984 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008985
Glenn Kasten93e471f2013-08-19 08:40:07 -07008986 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008987
8988 {
Andy Hung972bec12023-08-31 16:13:39 -07008989 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008990 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008991 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008992 track->invalidate();
8993 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008994 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008995 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008996 }
8997
8998 releaseWakeLock();
8999
9000 ALOGV("RecordThread %p exiting", this);
9001 return false;
9002}
9003
Andy Hungee58e4a2023-07-07 13:47:37 -07009004void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08009005{
9006 if (!mStandby) {
9007 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07009008 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07009009 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08009010 mStandby = true;
9011 }
9012}
9013
Andy Hungee58e4a2023-07-07 13:47:37 -07009014void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08009015{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009016 // Idle the fast capture if it's currently running
9017 if (mFastCapture != 0) {
9018 FastCaptureStateQueue *sq = mFastCapture->sq();
9019 FastCaptureState *state = sq->begin();
9020 if (!(state->mCommand & FastCaptureState::IDLE)) {
9021 state->mCommand = FastCaptureState::COLD_IDLE;
9022 state->mColdFutexAddr = &mFastCaptureFutex;
9023 state->mColdGen++;
9024 mFastCaptureFutex = 0;
9025 sq->end();
9026 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
Andy Hung82f39d62024-09-30 17:19:14 -07009027 {
9028 audio_utils::mutex::scoped_queue_wait_check queueWaitCheck(mFastCapture->getTid());
9029 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
9030 }
9031
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009032#if 0
9033 if (kUseFastCapture == FastCapture_Dynamic) {
9034 // FIXME
9035 }
9036#endif
9037#ifdef AUDIO_WATCHDOG
9038 // FIXME
9039#endif
9040 } else {
9041 sq->end(false /*didModify*/);
9042 }
9043 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07009044 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009045 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07009046
9047 // If going into standby, flush the pipe source.
9048 if (mPipeSource.get() != nullptr) {
9049 const ssize_t flushed = mPipeSource->flush();
9050 if (flushed > 0) {
9051 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
9052 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
9053 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
9054 }
9055 }
Eric Laurent81784c32012-11-19 14:55:58 -08009056}
9057
Andy Hungc5007f82023-08-29 14:26:09 -07009058// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009059sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07009060 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009061 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009062 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08009063 audio_format_t format,
9064 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08009065 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08009066 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08009067 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009068 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00009069 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07009070 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08009071 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08009072 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02009073 audio_port_handle_t portId,
9074 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08009075{
Glenn Kasten74935e42013-12-19 08:56:45 -08009076 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009077 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07009078 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08009079 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07009080 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009081 audio_input_flags_t requestedFlags = *flags;
9082 uint32_t sampleRate;
9083
9084 lStatus = initCheck();
9085 if (lStatus != NO_ERROR) {
9086 ALOGE("createRecordTrack_l() audio driver not initialized");
9087 goto Exit;
9088 }
9089
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009090 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
9091 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
9092 lStatus = BAD_VALUE;
9093 goto Exit;
9094 }
9095
Eric Laurentec376dc2021-04-08 20:41:22 +02009096 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01009097 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009098 lStatus = PERMISSION_DENIED;
9099 goto Exit;
9100 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009101 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07009102 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009103 lStatus = BAD_VALUE;
9104 goto Exit;
9105 }
9106 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08009107 if (*pSampleRate == 0) {
9108 *pSampleRate = mSampleRate;
9109 }
9110 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07009111
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009112 // special case for FAST flag considered OK if fast capture is present and access to
9113 // audio history is not required
9114 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07009115 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
9116 }
9117
Eric Laurentf14db3c2017-12-08 14:20:36 -08009118 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07009119 if ((*flags & inputFlags) != *flags) {
9120 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
9121 " input flags (%08x)",
9122 *flags, inputFlags);
9123 *flags = (audio_input_flags_t)(*flags & inputFlags);
9124 }
Eric Laurent81784c32012-11-19 14:55:58 -08009125
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009126 // client expresses a preference for FAST and no access to audio history,
9127 // but we get the final say
9128 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009129 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009130 // we formerly checked for a callback handler (non-0 tid),
9131 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00009132 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07009133 //
Phil Burk7ed66a12019-04-18 13:20:30 -07009134 // Frame count is not specified (0), or is less than or equal the pipe depth.
9135 // It is OK to provide a higher capacity than requested.
9136 // We will force it to mPipeFramesP2 below.
9137 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009138 // PCM data
9139 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009140 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009141 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08009142 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07009143 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07009144 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009145 hasFastCapture() &&
9146 // there are sufficient fast track slots available
9147 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07009148 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07009149 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07009150 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07009151 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07009152 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07009153 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07009154 audio_input_flags_t old = *flags;
9155 chain->checkInputFlagCompatibility(flags);
9156 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009157 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9158 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009159 }
9160 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009161 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009162 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9163 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009164 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009165 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9166 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009167 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009168 this, frameCount, mFrameCount, mPipeFramesP2,
9169 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009170 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009171 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009172 }
9173 }
9174
Eric Laurentf14db3c2017-12-08 14:20:36 -08009175 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9176 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9177 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9178 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9179 lStatus = BAD_TYPE;
9180 goto Exit;
9181 }
9182
Glenn Kasten74105912014-07-03 12:28:53 -07009183 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009184 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009185 // fast track: frame count is exactly the pipe depth
9186 frameCount = mPipeFramesP2;
9187 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009188 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009189 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009190 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9191 // or 20 ms if there is a fast capture
9192 // TODO This could be a roundupRatio inline, and const
9193 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9194 * sampleRate + mSampleRate - 1) / mSampleRate;
9195 // minimum number of notification periods is at least kMinNotifications,
9196 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9197 static const size_t kMinNotifications = 3;
9198 static const uint32_t kMinMs = 30;
9199 // TODO This could be a roundupRatio inline
9200 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9201 // TODO This could be a roundupRatio inline
9202 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9203 maxNotificationFrames;
9204 const size_t minFrameCount = maxNotificationFrames *
9205 max(kMinNotifications, minNotificationsByMs);
9206 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009207 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9208 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009209 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009210 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009211 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009212 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009213
Andy Hungc5007f82023-08-29 14:26:09 -07009214 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009215 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009216 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009217 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009218 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009219 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009220 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009221 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009222 }
Eric Laurent81784c32012-11-19 14:55:58 -08009223
Andy Hung8d31fd22023-06-26 19:20:57 -07009224 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009225 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009226 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009227 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009228 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009229
Glenn Kasten03003332013-08-06 15:40:54 -07009230 lStatus = track->initCheck();
9231 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009232 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009233 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009234 goto Exit;
9235 }
9236 mTracks.add(track);
9237
Eric Laurent05067782016-06-01 18:27:28 -07009238 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009239 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9240 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9241 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009242 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009243 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009244
9245 if (maxSharedAudioHistoryMs != 0) {
9246 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9247 }
Eric Laurent81784c32012-11-19 14:55:58 -08009248 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009249
Eric Laurent81784c32012-11-19 14:55:58 -08009250 lStatus = NO_ERROR;
9251
9252Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009253 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009254 return track;
9255}
9256
Andy Hungee58e4a2023-07-07 13:47:37 -07009257status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009258 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009259 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009260{
9261 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9262 sp<ThreadBase> strongMe = this;
9263 status_t status = NO_ERROR;
9264
9265 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009266 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009267 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009268 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009269 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009270 event, triggerSession,
9271 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009272 }
9273
9274 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009275 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009276 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009277 if (recordTrack->isInvalid()) {
9278 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009279 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9280 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009281 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009282 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009283 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009284 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9285 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009286 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009287 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009288 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009289 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009290 }
9291 return status;
9292 }
9293
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009294 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9295 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9296 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009297 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009298 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009299 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009300 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009301 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009302 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009303 if (recordTrack->isInvalid()) {
9304 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009305 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9306 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009307 // STARTING_2 forces destroy to call stopInput.
9308 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009309 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9310 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009311 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009312 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009313 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009314 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009315 // Someone else has changed state, let them take over,
9316 // leave mState in the new state.
9317 recordTrack->clearSyncStartEvent();
9318 return INVALID_OPERATION;
9319 }
9320 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009321 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009322 ALOGW("%s(%d): startInput failed, status %d",
9323 __func__, recordTrack->id(), status);
9324 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9325 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009326 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009327 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009328 return status;
9329 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009330 sendIoConfigEvent_l(
9331 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009332 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009333
9334 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9335
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009336 // Catch up with current buffer indices if thread is already running.
9337 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9338 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9339 // see previously buffered data before it called start(), but with greater risk of overrun.
9340
Andy Hung8d31fd22023-06-26 19:20:57 -07009341 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009342 if (!recordTrack->isDirect()) {
9343 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009344 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009345 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009346 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009347 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009348 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009349 return status;
9350 }
Eric Laurent81784c32012-11-19 14:55:58 -08009351}
9352
Andy Hungee58e4a2023-07-07 13:47:37 -07009353void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009354{
Andy Hungee58e4a2023-07-07 13:47:37 -07009355 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009356
9357 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009358 sp<IAfTrackBase> ptr =
9359 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9360 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009361 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009362 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009363 }
Eric Laurent81784c32012-11-19 14:55:58 -08009364 }
9365}
9366
Andy Hungee58e4a2023-07-07 13:47:37 -07009367bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009368 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009369 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009370 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009371 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009372 return false;
9373 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009374 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009375 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009376
Andy Hungabfab202019-03-07 19:45:54 -08009377 // NOTE: Waiting here is important to keep stop synchronous.
9378 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009379 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009380 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009381 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009382 }
Andy Hungce685402018-10-05 17:23:27 -07009383
Andy Hung8d31fd22023-06-26 19:20:57 -07009384 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009385 ALOGV("Record stopped OK");
9386 return true;
9387 }
Andy Hungce685402018-10-05 17:23:27 -07009388
9389 // don't handle anything - we've been invalidated or restarted and in a different state
9390 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009391 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009392 return false;
9393}
9394
Andy Hungee58e4a2023-07-07 13:47:37 -07009395bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009396{
9397 return false;
9398}
9399
Andy Hungee58e4a2023-07-07 13:47:37 -07009400status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009401{
9402#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9403 if (!isValidSyncEvent(event)) {
9404 return BAD_VALUE;
9405 }
9406
Glenn Kastend848eb42016-03-08 13:42:11 -08009407 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009408 status_t ret = NAME_NOT_FOUND;
9409
Andy Hung972bec12023-08-31 16:13:39 -07009410 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009411
9412 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009413 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009414 if (eventSession == track->sessionId()) {
9415 (void) track->setSyncEvent(event);
9416 ret = NO_ERROR;
9417 }
9418 }
9419 return ret;
9420#else
9421 return BAD_VALUE;
9422#endif
9423}
9424
Andy Hungee58e4a2023-07-07 13:47:37 -07009425status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009426 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009427{
9428 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009429 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009430 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009431 return NO_INIT;
9432 }
jiabin9ff780e2018-03-19 18:19:52 -07009433 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9434 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009435}
9436
Andy Hungee58e4a2023-07-07 13:47:37 -07009437status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009438 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009439{
Paul McLean12340082019-03-19 09:35:05 -06009440 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009441 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009442 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009443 return NO_INIT;
9444 }
Paul McLean12340082019-03-19 09:35:05 -06009445 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009446}
9447
Andy Hungee58e4a2023-07-07 13:47:37 -07009448status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009449{
Paul McLean12340082019-03-19 09:35:05 -06009450 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009451 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009452 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009453 return NO_INIT;
9454 }
Paul McLean12340082019-03-19 09:35:05 -06009455 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009456}
9457
Andy Hungee58e4a2023-07-07 13:47:37 -07009458status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009459 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9460 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009461 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009462 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9463}
9464
Andy Hungee58e4a2023-07-07 13:47:37 -07009465status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009466 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9467 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009468
Eric Laurentec376dc2021-04-08 20:41:22 +02009469 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9470 return BAD_VALUE;
9471 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009472
9473 if (sharedAudioStartMs < 0
9474 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009475 return BAD_VALUE;
9476 }
9477
Eric Laurent2407ce32021-04-26 14:56:03 +02009478 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9479 // As we cannot detect more than one wraparound, only accept values up current write position
9480 // after one wraparound
9481 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9482 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009483 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009484 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9485 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009486 // Bring the start frame position within the input buffer to match the documented
9487 // "best effort" behavior of the API.
9488 if (sharedOffset < 0) {
9489 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009490 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009491 sharedAudioStartFrames =
9492 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009493 }
9494
Eric Laurentec376dc2021-04-08 20:41:22 +02009495 mSharedAudioPackageName = sharedAudioPackageName;
9496 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009497 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009498 } else {
9499 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009500 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009501 }
9502 return NO_ERROR;
9503}
9504
Andy Hungee58e4a2023-07-07 13:47:37 -07009505void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009506 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9507 mSharedAudioStartFrames = -1;
9508 mSharedAudioPackageName = "";
9509}
9510
Andy Hungee58e4a2023-07-07 13:47:37 -07009511ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009512{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009513 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009514 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009515 }
9516 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009517 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009518 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009519 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009520 }
9521 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009522 MetadataUpdate change;
9523 change.recordMetadataUpdate = metadata.tracks;
9524 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009525}
9526
Andy Hungc5007f82023-08-29 14:26:09 -07009527// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009528void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009529{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009530 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009531 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009532
Eric Laurent81784c32012-11-19 14:55:58 -08009533 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009534 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009535 removeTrack_l(track);
9536 }
9537}
9538
Andy Hungee58e4a2023-07-07 13:47:37 -07009539void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009540{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009541 String8 result;
9542 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009543 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009544
Eric Laurent81784c32012-11-19 14:55:58 -08009545 mTracks.remove(track);
9546 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009547 if (track->isFastTrack()) {
9548 ALOG_ASSERT(!mFastTrackAvail);
9549 mFastTrackAvail = true;
9550 }
Eric Laurent81784c32012-11-19 14:55:58 -08009551}
9552
Andy Hungee58e4a2023-07-07 13:47:37 -07009553void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009554{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009555 AudioStreamIn *input = mInput;
9556 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9557 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009558 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009559 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009560 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009561 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009562 }
Andy Hungbfa64962017-06-12 14:43:19 -07009563
9564 if (input != nullptr) {
9565 dprintf(fd, " Hal stream dump:\n");
9566 (void)input->stream->dump(fd);
9567 }
9568
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009569 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009570 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009571
Glenn Kasten2f90c512015-12-02 11:40:09 -08009572 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9573 // while we are dumping it. It may be inconsistent, but it won't mutate!
9574 // This is a large object so we place it on the heap.
9575 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009576 const std::unique_ptr<FastCaptureDumpState> copy =
9577 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009578 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009579}
9580
Andy Hungee58e4a2023-07-07 13:47:37 -07009581void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009582{
Eric Laurent81784c32012-11-19 14:55:58 -08009583 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009584 size_t numtracks = mTracks.size();
9585 size_t numactive = mActiveTracks.size();
9586 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009587 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009588 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009589 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009590 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009591 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009592 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009593 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009594 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009595 if (track != 0) {
9596 bool active = mActiveTracks.indexOf(track) >= 0;
9597 if (active) {
9598 numactiveseen++;
9599 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009600 result.append(prefix);
9601 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009602 }
Eric Laurent81784c32012-11-19 14:55:58 -08009603 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009604 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009605 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009606 }
9607
Marco Nelissenb2208842014-02-07 14:00:50 -08009608 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009609 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009610 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009611 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009612 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009613 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009614 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009615 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009616 result.append(prefix);
9617 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009618 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009619 }
Eric Laurent81784c32012-11-19 14:55:58 -08009620
9621 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009622 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009623}
9624
Andy Hungee58e4a2023-07-07 13:47:37 -07009625void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009626{
Andy Hung972bec12023-08-31 16:13:39 -07009627 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009628 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009629 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009630 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009631 track->setSilenced(silenced);
9632 }
9633 }
9634}
Andy Hung73c02e42015-03-29 01:13:58 -07009635
Andy Hung8d31fd22023-06-26 19:20:57 -07009636void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009637{
Andy Hung87c693c2023-07-06 20:56:16 -07009638 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009639 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009640 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009641 const int32_t rear = recordThread->mRsmpInRear;
9642 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009643 if (mRecordTrack->startFrames() >= 0) {
9644 int32_t startFrames = mRecordTrack->startFrames();
9645 // Accept a recent wraparound of mRsmpInRear
9646 if (startFrames <= rear) {
9647 deltaFrames = rear - startFrames;
9648 } else {
9649 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009650 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009651 // start frame cannot be further in the past than start of resampling buffer
9652 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9653 deltaFrames = recordThread->mRsmpInFrames;
9654 }
9655 }
9656 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009657}
9658
Andy Hung8d31fd22023-06-26 19:20:57 -07009659void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009660 size_t *framesAvailable, bool *hasOverrun)
9661{
Andy Hung87c693c2023-07-06 20:56:16 -07009662 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009663 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009664 const int32_t rear = recordThread->mRsmpInRear;
9665 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009666 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009667
9668 size_t framesIn;
9669 bool overrun = false;
9670 if (filled < 0) {
9671 // should not happen, but treat like a massive overrun and re-sync
9672 framesIn = 0;
9673 mRsmpInFront = rear;
9674 overrun = true;
9675 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9676 framesIn = (size_t) filled;
9677 } else {
9678 // client is not keeping up with server, but give it latest data
9679 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009680 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9681 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009682 overrun = true;
9683 }
9684 if (framesAvailable != NULL) {
9685 *framesAvailable = framesIn;
9686 }
9687 if (hasOverrun != NULL) {
9688 *hasOverrun = overrun;
9689 }
9690}
9691
Eric Laurent81784c32012-11-19 14:55:58 -08009692// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009693status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009694 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009695{
Andy Hung87c693c2023-07-06 20:56:16 -07009696 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009697 if (threadBase == 0) {
9698 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009699 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009700 return NOT_ENOUGH_DATA;
9701 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009702 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009703 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009704 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009705 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009706 // FIXME should not be P2 (don't want to increase latency)
9707 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009708 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009709 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009710
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009711 front &= recordThread->mRsmpInFramesP2 - 1;
9712 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009713 if (part1 > (size_t) filled) {
9714 part1 = filled;
9715 }
9716 size_t ask = buffer->frameCount;
9717 ALOG_ASSERT(ask > 0);
9718 if (part1 > ask) {
9719 part1 = ask;
9720 }
9721 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009722 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009723 buffer->raw = NULL;
9724 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009725 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009726 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009727 }
9728
Andy Hung57446612015-04-19 23:56:46 -07009729 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009730 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009731 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009732 return NO_ERROR;
9733}
9734
9735// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009736void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009737 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009738{
Hongwei Wang95e37682019-04-12 11:13:36 -07009739 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009740 if (stepCount == 0) {
9741 return;
9742 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009743 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009744 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009745 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009746 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009747 buffer->frameCount = 0;
9748}
9749
Andy Hungee58e4a2023-07-07 13:47:37 -07009750void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009751{
Andy Hung972bec12023-08-31 16:13:39 -07009752 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009753 checkBtNrec_l();
9754}
9755
Andy Hungee58e4a2023-07-07 13:47:37 -07009756void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009757{
9758 // disable AEC and NS if the device is a BT SCO headset supporting those
9759 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009760 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009761 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009762 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9763 for (size_t i = 0; i < mEffectChains.size(); i++) {
9764 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9765 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9766 }
9767 }
9768}
9769
Andy Hung97a893e2015-03-29 01:03:07 -07009770
Andy Hungee58e4a2023-07-07 13:47:37 -07009771bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009772 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009773{
9774 bool reconfig = false;
9775
Eric Laurent10351942014-05-08 18:49:52 -07009776 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009777
Eric Laurent10351942014-05-08 18:49:52 -07009778 audio_format_t reqFormat = mFormat;
9779 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009780 // 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 +08009781 [[maybe_unused]] audio_channel_mask_t channelMask =
9782 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009783
9784 AudioParameter param = AudioParameter(keyValuePair);
9785 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009786
9787 // scope for AutoPark extends to end of method
9788 AutoPark<FastCapture> park(mFastCapture);
9789
Eric Laurent10351942014-05-08 18:49:52 -07009790 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9791 // channel count change can be requested. Do we mandate the first client defines the
9792 // HAL sampling rate and channel count or do we allow changes on the fly?
9793 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9794 samplingRate = value;
9795 reconfig = true;
9796 }
9797 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009798 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009799 status = BAD_VALUE;
9800 } else {
9801 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009802 reconfig = true;
9803 }
Eric Laurent10351942014-05-08 18:49:52 -07009804 }
9805 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9806 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009807 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009808 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009809 status = BAD_VALUE;
9810 } else {
9811 channelMask = mask;
9812 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009813 }
Eric Laurent10351942014-05-08 18:49:52 -07009814 }
9815 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9816 // do not accept frame count changes if tracks are open as the track buffer
9817 // size depends on frame count and correct behavior would not be guaranteed
9818 // if frame count is changed after track creation
9819 if (mActiveTracks.size() > 0) {
9820 status = INVALID_OPERATION;
9821 } else {
9822 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009823 }
Eric Laurent10351942014-05-08 18:49:52 -07009824 }
9825 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009826 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009827 }
9828 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9829 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009830 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009831 }
Glenn Kastene198c362013-08-13 09:13:36 -07009832
Eric Laurent10351942014-05-08 18:49:52 -07009833 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009834 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009835 if (status == INVALID_OPERATION) {
9836 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009837 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009838 }
9839 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009840 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009841 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9842 if (mInput->stream->getAudioProperties(&config) == OK &&
9843 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9844 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009845 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009846 status = NO_ERROR;
9847 }
Eric Laurent81784c32012-11-19 14:55:58 -08009848 }
Eric Laurent10351942014-05-08 18:49:52 -07009849 if (status == NO_ERROR) {
9850 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009851 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009852 }
9853 }
Eric Laurent81784c32012-11-19 14:55:58 -08009854 }
Eric Laurent10351942014-05-08 18:49:52 -07009855
Eric Laurent81784c32012-11-19 14:55:58 -08009856 return reconfig;
9857}
9858
Andy Hungee58e4a2023-07-07 13:47:37 -07009859String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009860{
Andy Hung972bec12023-08-31 16:13:39 -07009861 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009862 if (initCheck() == NO_ERROR) {
9863 String8 out_s8;
9864 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9865 return out_s8;
9866 }
Eric Laurent81784c32012-11-19 14:55:58 -08009867 }
Andy Hung920f6572022-10-06 12:09:49 -07009868 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009869}
9870
Andy Hungab65b182023-09-06 19:41:47 -07009871void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009872 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009873 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009874 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009875 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009876 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009877 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009878 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9879 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009880 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009881 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009882 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009883 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009884 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009885 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009886 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009887 break;
9888 }
Andy Hungab65b182023-09-06 19:41:47 -07009889 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009890}
9891
Andy Hungee58e4a2023-07-07 13:47:37 -07009892void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009893{
Dean Wheatley6c009512023-10-23 09:34:14 +11009894 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9895 mSampleRate = audioConfig.sample_rate;
9896 mChannelMask = audioConfig.channel_mask;
9897 if (!audio_is_input_channel(mChannelMask)) {
9898 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9899 }
9900
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009901 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009902
9903 // Get actual HAL format.
9904 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9905 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9906 // Get format from the shim, which will be different than the HAL format
9907 // if recording compressed audio from IEC61937 wrapped sources.
9908 mFormat = audioConfig.format;
9909 if (!audio_is_valid_format(mFormat)) {
9910 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9911 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009912 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009913 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9914 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009915 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009916 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009917 ALOGI("HAL format %#x is not linear pcm", mFormat);
9918 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009919 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009920 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9921 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009922 result = mInput->stream->getBufferSize(&mBufferSize);
9923 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009924 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009925 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9926 "mBufferSize=%zu, mFrameCount=%zu",
9927 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009928
Eric Laurentec376dc2021-04-08 20:41:22 +02009929 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9930 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009931 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009932
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009933 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9934 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009935
9936 audio_input_flags_t flags = mInput->flags;
9937 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9938 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009939 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009940 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9941 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9942 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9943 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9944 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9945 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009946}
9947
Andy Hungee58e4a2023-07-07 13:47:37 -07009948uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009949{
Andy Hung972bec12023-08-31 16:13:39 -07009950 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009951 uint32_t result;
9952 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9953 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009954 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009955 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009956}
9957
Andy Hungee58e4a2023-07-07 13:47:37 -07009958KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009959{
Glenn Kastend848eb42016-03-08 13:42:11 -08009960 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009961 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009962 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009963 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009964 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009965 if (ids.indexOfKey(sessionId) < 0) {
9966 ids.add(sessionId, true);
9967 }
9968 }
9969 return ids;
9970}
9971
Andy Hungee58e4a2023-07-07 13:47:37 -07009972AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009973{
Andy Hung972bec12023-08-31 16:13:39 -07009974 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009975 AudioStreamIn *input = mInput;
9976 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009977 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009978 return input;
9979}
9980
Andy Hungc5007f82023-08-29 14:26:09 -07009981// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009982sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009983{
9984 if (mInput == NULL) {
9985 return NULL;
9986 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009987 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009988}
9989
Andy Hungee58e4a2023-07-07 13:47:37 -07009990status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009991{
Eric Laurent81784c32012-11-19 14:55:58 -08009992 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009993 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009994 chain->setInBuffer(NULL);
9995 chain->setOutBuffer(NULL);
9996
9997 checkSuspendOnAddEffectChain_l(chain);
9998
Eric Laurent1b928682014-10-02 19:41:47 -07009999 // make sure enabled pre processing effects state is communicated to the HAL as we
10000 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +000010001 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -070010002
Eric Laurent81784c32012-11-19 14:55:58 -080010003 mEffectChains.add(chain);
10004
10005 return NO_ERROR;
10006}
10007
Andy Hungee58e4a2023-07-07 13:47:37 -070010008size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -080010009{
10010 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -070010011
10012 for (size_t i = 0; i < mEffectChains.size(); i++) {
10013 if (chain == mEffectChains[i]) {
10014 mEffectChains.removeAt(i);
10015 break;
10016 }
Eric Laurent81784c32012-11-19 14:55:58 -080010017 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -070010018 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -080010019}
10020
Andy Hungee58e4a2023-07-07 13:47:37 -070010021status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -070010022 audio_patch_handle_t *handle)
10023{
10024 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010025
10026 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -070010027 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010028 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +020010029 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -070010030 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010031 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -070010032 }
10033
Eric Laurentd8365c52017-07-16 15:27:05 -070010034 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -070010035
10036 // store new source and send to effects
10037 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10038 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -070010039 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -070010040 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -070010041 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010042 }
Eric Laurent1c333e22014-05-20 10:48:17 -070010043
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010044 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010045 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10046 status = hwDevice->createAudioPatch(patch->num_sources,
10047 patch->sources,
10048 patch->num_sinks,
10049 patch->sinks,
10050 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010051 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010052 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
10053 patch->sinks[0].ext.mix.usecase.source,
10054 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -070010055 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -070010056 }
Eric Laurent054d9d32015-04-24 08:48:48 -070010057
jiabinc52b1ff2019-10-31 17:20:42 -070010058 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -070010059 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -070010060 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -070010061 }
Eric Laurent296fb132015-05-01 11:38:42 -070010062
Andy Hungc2b11cb2020-04-22 09:04:01 -070010063 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -070010064 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -070010065 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -070010066 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -070010067 // also dispatch to active AudioRecords
10068 for (const auto &track : mActiveTracks) {
10069 track->logEndInterval();
10070 track->logBeginInterval(pathSourcesAsString);
10071 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010072 // Force meteadata update after a route change
10073 mActiveTracks.setHasChanged();
10074
Eric Laurent1c333e22014-05-20 10:48:17 -070010075 return status;
10076}
10077
Andy Hungee58e4a2023-07-07 13:47:37 -070010078status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -070010079{
10080 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -070010081
jiabinc52b1ff2019-10-31 17:20:42 -070010082 mPatch = audio_patch{};
10083 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -070010084
Mikhail Naganov9ee05402016-10-13 15:58:17 -070010085 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -070010086 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
10087 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -070010088 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010089 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -070010090 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010091 // Force meteadata update after a route change
10092 mActiveTracks.setHasChanged();
10093
Eric Laurent1c333e22014-05-20 10:48:17 -070010094 return status;
10095}
10096
Andy Hungee58e4a2023-07-07 13:47:37 -070010097void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -070010098{
Andy Hung972bec12023-08-31 16:13:39 -070010099 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -070010100 mOutDevices = outDevices;
10101 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
10102 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010103 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -070010104 }
10105}
10106
Andy Hungee58e4a2023-07-07 13:47:37 -070010107int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +020010108{
10109 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010110 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +020010111 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010112 int32_t oldestFront = mRsmpInRear;
10113 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +020010114 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010115 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +020010116 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +020010117 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +020010118 if (filled > maxFilled) {
10119 oldestFront = front;
10120 maxFilled = filled;
10121 }
Eric Laurentec376dc2021-04-08 20:41:22 +020010122 }
Andy Hung920f6572022-10-06 12:09:49 -070010123 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +020010124 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
10125 }
Eric Laurent2407ce32021-04-26 14:56:03 +020010126 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +020010127}
10128
Andy Hungee58e4a2023-07-07 13:47:37 -070010129void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +020010130{
10131 if (offset == 0) {
10132 return;
10133 }
10134 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010135 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +020010136 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -070010137 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +020010138 }
10139}
10140
Andy Hungee58e4a2023-07-07 13:47:37 -070010141void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +020010142{
10143 // This is the formula for calculating the temporary buffer size.
10144 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
10145 // 1 full output buffer, regardless of the alignment of the available input.
10146 // The value is somewhat arbitrary, and could probably be even larger.
10147 // A larger value should allow more old data to be read after a track calls start(),
10148 // without increasing latency.
10149 //
10150 // Note this is independent of the maximum downsampling ratio permitted for capture.
10151 size_t minRsmpInFrames = mFrameCount * 7;
10152
10153 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
10154 // capture history available to another client using the same session ID:
10155 // dimension the resampler input buffer accordingly.
10156
10157 // Get oldest client read position: getOldestFront_l() must be called before altering
10158 // mRsmpInRear, or mRsmpInFrames
10159 int32_t previousFront = getOldestFront_l();
10160 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10161 int32_t previousRear = mRsmpInRear;
10162 mRsmpInRear = 0;
10163
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010164 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010165 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010166 "resizeInputBuffer_l() called with invalid max shared history %d",
10167 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010168 if (maxSharedAudioHistoryMs != 0) {
10169 // resizeInputBuffer_l should never be called with a non zero shared history if the
10170 // buffer was not already allocated
10171 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10172 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10173 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10174 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010175 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010176 return;
10177 }
10178 mRsmpInFrames = rsmpInFrames;
10179 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010180 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010181 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10182 // initialized
10183 if (mRsmpInFrames < minRsmpInFrames) {
10184 mRsmpInFrames = minRsmpInFrames;
10185 }
10186 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10187
10188 // TODO optimize audio capture buffer sizes ...
10189 // Here we calculate the size of the sliding buffer used as a source
10190 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10191 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10192 // be better to have it derived from the pipe depth in the long term.
10193 // The current value is higher than necessary. However it should not add to latency.
10194
10195 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10196 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10197
10198 void *rsmpInBuffer;
10199 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10200 // if posix_memalign fails, will segv here.
10201 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10202
10203 // Copy audio history if any from old buffer before freeing it
10204 if (previousRear != 0) {
10205 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10206 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10207
10208 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10209 previousFront &= previousRsmpInFramesP2 - 1;
10210 size_t part1 = previousRsmpInFramesP2 - previousFront;
10211 if (part1 > (size_t) unread) {
10212 part1 = unread;
10213 }
10214 if (part1 != 0) {
10215 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10216 part1 * mFrameSize);
10217 mRsmpInRear = part1;
10218 part1 = unread - part1;
10219 if (part1 != 0) {
10220 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10221 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10222 mRsmpInRear += part1;
10223 }
10224 }
10225 // Update front for all clients according to new rear
10226 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10227 } else {
10228 mRsmpInRear = 0;
10229 }
10230 free(mRsmpInBuffer);
10231 mRsmpInBuffer = rsmpInBuffer;
10232}
10233
Andy Hungee58e4a2023-07-07 13:47:37 -070010234void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010235{
Andy Hung972bec12023-08-31 16:13:39 -070010236 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010237 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010238 if (record->getSource()) {
10239 mSource = record->getSource();
10240 }
Eric Laurent83b88082014-06-20 18:31:16 -070010241}
10242
Andy Hungee58e4a2023-07-07 13:47:37 -070010243void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010244{
Andy Hung972bec12023-08-31 16:13:39 -070010245 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010246 if (mSource == record->getSource()) {
10247 mSource = mInput;
10248 }
Eric Laurent83b88082014-06-20 18:31:16 -070010249 destroyTrack_l(record);
10250}
10251
Andy Hungee58e4a2023-07-07 13:47:37 -070010252void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010253{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010254 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010255 config->role = AUDIO_PORT_ROLE_SINK;
10256 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10257 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010258 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10259 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10260 config->flags.input = mInput->flags;
10261 }
Eric Laurent83b88082014-06-20 18:31:16 -070010262}
Eric Laurent1c333e22014-05-20 10:48:17 -070010263
Atneya Nairaa3afcb2024-10-08 16:36:19 -070010264std::string RecordThread::getLocalLogHeader() const {
10265 using namespace std::literals;
10266 static constexpr auto indent = " "
10267 " "sv;
10268 return std::string{indent}.append(IAfRecordTrack::getLogHeader());
10269}
10270
Eric Laurent6acd1d42017-01-04 14:23:29 -080010271// ----------------------------------------------------------------------------
10272// Mmap
10273// ----------------------------------------------------------------------------
10274
Andy Hung7aa7d102023-07-07 15:58:48 -070010275// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10276// MmapPlaybackThread or MmapCaptureThread instance.
10277class MmapThreadHandle : public MmapStreamInterface {
10278public:
10279 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10280 ~MmapThreadHandle() override;
10281
10282 // MmapStreamInterface virtuals
10283 status_t createMmapBuffer(int32_t minSizeFrames,
10284 struct audio_mmap_buffer_info* info) final;
10285 status_t getMmapPosition(struct audio_mmap_position* position) final;
10286 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10287 status_t start(const AudioClient& client,
10288 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10289 status_t stop(audio_port_handle_t handle) final;
10290 status_t standby() final;
10291 status_t reportData(const void* buffer, size_t frameCount) final;
10292private:
10293 const sp<IAfMmapThread> mThread;
10294};
10295
10296/* static */
10297sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10298 const sp<IAfMmapThread>& mmapThread) {
10299 return sp<MmapThreadHandle>::make(mmapThread);
10300}
10301
10302MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010303 : mThread(thread)
10304{
Phil Burk9fabbf82017-08-03 12:02:00 -070010305 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010306}
10307
Andy Hung7aa7d102023-07-07 15:58:48 -070010308// MmapStreamInterface could be directly implemented by MmapThread excepting this
10309// special handling on adapter dtor.
10310MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010311{
Phil Burk9fabbf82017-08-03 12:02:00 -070010312 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010313}
10314
Andy Hung7aa7d102023-07-07 15:58:48 -070010315status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010316 struct audio_mmap_buffer_info *info)
10317{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010318 return mThread->createMmapBuffer(minSizeFrames, info);
10319}
10320
Andy Hung7aa7d102023-07-07 15:58:48 -070010321status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010323 return mThread->getMmapPosition(position);
10324}
10325
Andy Hung7aa7d102023-07-07 15:58:48 -070010326status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010327 int64_t *timeNanos) {
10328 return mThread->getExternalPosition(position, timeNanos);
10329}
10330
Andy Hung7aa7d102023-07-07 15:58:48 -070010331status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010332 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010333{
jiabind1f1cb62020-03-24 11:57:57 -070010334 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010335}
10336
Andy Hung7aa7d102023-07-07 15:58:48 -070010337status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010339 return mThread->stop(handle);
10340}
10341
Andy Hung7aa7d102023-07-07 15:58:48 -070010342status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010343{
Eric Laurent18b57012017-02-13 16:23:52 -080010344 return mThread->standby();
10345}
10346
Andy Hung7aa7d102023-07-07 15:58:48 -070010347status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10348{
jiabinfc791ee2023-02-15 19:43:40 +000010349 return mThread->reportData(buffer, frameCount);
10350}
10351
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352
Andy Hungee58e4a2023-07-07 13:47:37 -070010353MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010354 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010355 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010356 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010357 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010358 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010359 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010360 mActiveTracks(&this->mLocalLog),
10361 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10362 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010363{
Eric Laurent18b57012017-02-13 16:23:52 -080010364 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010365 readHalParameters_l();
10366}
10367
Andy Hungee58e4a2023-07-07 13:47:37 -070010368void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010369{
10370 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10371}
10372
Andy Hungee58e4a2023-07-07 13:47:37 -070010373void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010374{
Andy Hung8d31fd22023-06-26 19:20:57 -070010375 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010376 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010377 {
Andy Hung972bec12023-08-31 16:13:39 -070010378 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010379 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010380 activeTracks.add(t);
10381 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010382 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010383 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010384 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010385 stop(t->portId());
10386 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010387 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010388 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010389 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010390 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010391 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010392 }
10393}
10394
10395
Andy Hung8d672e02023-09-15 18:19:28 -070010396void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 audio_stream_type_t streamType __unused,
10398 audio_session_t sessionId,
10399 const sp<MmapStreamCallback>& callback,
Robert Wuaeb1d002024-10-30 23:19:44 +000010400 const DeviceIdVector& deviceIds,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401 audio_port_handle_t portId)
10402{
10403 mAttr = *attr;
10404 mSessionId = sessionId;
10405 mCallback = callback;
Robert Wuaeb1d002024-10-30 23:19:44 +000010406 mDeviceIds = deviceIds;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010407 mPortId = portId;
10408}
10409
Andy Hungee58e4a2023-07-07 13:47:37 -070010410status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010411 struct audio_mmap_buffer_info *info)
10412{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010413 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414 if (mHalStream == 0) {
10415 return NO_INIT;
10416 }
Eric Laurent18b57012017-02-13 16:23:52 -080010417 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010418 return mHalStream->createMmapBuffer(minSizeFrames, info);
10419}
10420
Andy Hungee58e4a2023-07-07 13:47:37 -070010421status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010422{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010423 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010424 if (mHalStream == 0) {
10425 return NO_INIT;
10426 }
10427 return mHalStream->getMmapPosition(position);
10428}
10429
Andy Hungee58e4a2023-07-07 13:47:37 -070010430status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010431{
Eric Laurentdda206a2022-07-08 17:28:35 +020010432 // The HAL must receive track metadata before starting the stream
10433 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010434 status_t ret = mHalStream->start();
10435 if (ret != NO_ERROR) {
10436 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10437 return ret;
10438 }
Andy Hungcf10d742020-04-28 15:38:24 -070010439 if (mStandby) {
10440 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010441 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010442 mStandby = false;
10443 }
Eric Laurent331679c2018-04-16 17:03:16 -070010444 return NO_ERROR;
10445}
10446
Andy Hungee58e4a2023-07-07 13:47:37 -070010447status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010448 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010449 audio_port_handle_t *handle)
10450{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010451 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010452 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010453 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 if (mHalStream == 0) {
10455 return NO_INIT;
10456 }
10457
10458 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459
Eric Laurentdda206a2022-07-08 17:28:35 +020010460 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010461 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010462 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010463 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010464 }
10465
10466 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10467
10468 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010469 AttributionSourceState adjAttributionSource;
10470 if (!com::android::media::audio::audioserver_permissions()) {
10471 adjAttributionSource = afutils::checkAttributionSourcePackage(
10472 client.attributionSource);
10473 } else {
10474 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10475 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10476 client.attributionSource,
10477 mAfThreadCallback->getPermissionProvider()
10478 );
10479 if (!validatedRes.has_value()) {
10480 ALOGE("MMAP client package validation fail: %s",
10481 validatedRes.error().toString8().c_str());
10482 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10483 }
10484 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10485 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010486
Andy Hung3f49ebb2023-09-19 14:48:41 -070010487 const auto localSessionId = mSessionId;
10488 auto localAttr = mAttr;
Andy Hung6b137d12024-08-27 22:35:17 +000010489 float volume = 0.0f;
Vlad Popa1e865e62024-08-15 19:11:42 -070010490 bool muted = false;
Eric Laurenta54f1282017-07-01 19:39:32 -070010491 if (isOutput()) {
10492 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10493 config.sample_rate = mSampleRate;
10494 config.channel_mask = mChannelMask;
10495 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010496 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010497 audio_output_flags_t flags =
10498 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Robert Wuaeb1d002024-10-30 23:19:44 +000010499 DeviceIdVector deviceIds = mDeviceIds;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010500 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010501 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010502 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010503 mutex().unlock();
10504 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10505 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010506 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010507 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010508 &config,
10509 flags,
Robert Wufb971192024-10-30 21:54:35 +000010510 &deviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010511 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010512 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010513 &isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +000010514 &isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -070010515 &volume,
10516 &muted);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010517 mutex().lock();
10518 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010519 ALOGD_IF(!secondaryOutputs.empty(),
10520 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010521 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010522 audio_config_base_t config;
10523 config.sample_rate = mSampleRate;
10524 config.channel_mask = mChannelMask;
10525 config.format = mFormat;
Robert Wuaeb1d002024-10-30 23:19:44 +000010526 audio_port_handle_t deviceId = getFirstDeviceId(mDeviceIds);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010527 mutex().unlock();
10528 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010529 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010530 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010531 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010532 &config,
10533 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10534 &deviceId,
10535 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010536 mutex().lock();
10537 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010538 }
10539 // APM should not chose a different input or output stream for the same set of attributes
10540 // and audo configuration
10541 if (ret != NO_ERROR || io != mId) {
10542 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10543 __FUNCTION__, ret, io, mId);
10544 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 }
10546
10547 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010548 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010549 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010550 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551 } else {
jiabin09609032022-06-15 19:26:01 +000010552 {
10553 // Add the track record before starting input so that the silent status for the
10554 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010555 setClientSilencedState_l(portId, false /*silenced*/);
10556 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010557 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010558 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010559 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 }
10561
10562 // abort if start is rejected by audio policy manager
10563 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010564 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010565 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010566 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010568 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010569 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010570 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010571 }
Andy Hungc5007f82023-08-29 14:26:09 -070010572 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010573 } else {
10574 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010575 }
jiabin09609032022-06-15 19:26:01 +000010576 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577 return PERMISSION_DENIED;
10578 }
10579
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010580 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010581 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10582 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010583 mChannelMask, mSessionId, isOutput(),
10584 client.attributionSource,
Andy Hung6b137d12024-08-27 22:35:17 +000010585 IPCThreadState::self()->getCallingPid(), portId,
Vlad Popa1e865e62024-08-15 19:11:42 -070010586 volume, muted);
jiabin09609032022-06-15 19:26:01 +000010587 if (!isOutput()) {
10588 track->setSilenced_l(isClientSilenced_l(portId));
10589 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010590
Eric Laurent4eb58f12018-12-07 16:41:02 -080010591 if (isOutput()) {
10592 // force volume update when a new track is added
10593 mHalVolFloat = -1.0f;
10594 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010595 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010596 if (t->isSilenced_l()
10597 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010598 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010599 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010600 }
10601 }
10602
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010604 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010605 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010606 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 chain->incTrackCnt();
10608 chain->incActiveTrackCnt();
10609 }
10610
Andy Hungc2b11cb2020-04-22 09:04:01 -070010611 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010612 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010613
10614 if (mActiveTracks.size() == 1) {
10615 ret = exitStandby_l();
10616 }
10617
Eric Laurent6acd1d42017-01-04 14:23:29 -080010618 broadcast_l();
10619
Eric Laurentdda206a2022-07-08 17:28:35 +020010620 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010621
Eric Laurentdda206a2022-07-08 17:28:35 +020010622 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623}
10624
Andy Hungee58e4a2023-07-07 13:47:37 -070010625status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010626{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010627 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010628 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010629
10630 if (mHalStream == 0) {
10631 return NO_INIT;
10632 }
10633
Eric Laurenta54f1282017-07-01 19:39:32 -070010634 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010635 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010636 return NO_ERROR;
10637 }
10638
Andy Hung8d31fd22023-06-26 19:20:57 -070010639 sp<IAfMmapTrack> track;
10640 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010641 if (handle == t->portId()) {
10642 track = t;
10643 break;
10644 }
10645 }
10646 if (track == 0) {
10647 return BAD_VALUE;
10648 }
10649
10650 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010651 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652
Andy Hungc5007f82023-08-29 14:26:09 -070010653 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010655 AudioSystem::stopOutput(track->portId());
10656 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010657 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010658 AudioSystem::stopInput(track->portId());
10659 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010660 }
Andy Hungc5007f82023-08-29 14:26:09 -070010661 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010662
Andy Hung116bc262023-06-20 18:56:17 -070010663 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010664 if (chain != 0) {
10665 chain->decActiveTrackCnt();
10666 chain->decTrackCnt();
10667 }
10668
Eric Laurentdda206a2022-07-08 17:28:35 +020010669 if (mActiveTracks.isEmpty()) {
10670 mHalStream->stop();
10671 }
10672
Eric Laurent6acd1d42017-01-04 14:23:29 -080010673 broadcast_l();
10674
Eric Laurent6acd1d42017-01-04 14:23:29 -080010675 return NO_ERROR;
10676}
10677
Andy Hungee58e4a2023-07-07 13:47:37 -070010678status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010679NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010680{
10681 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010682 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010683
10684 if (mHalStream == 0) {
10685 return NO_INIT;
10686 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010687 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010688 return INVALID_OPERATION;
10689 }
10690 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010691 if (!mStandby) {
10692 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010693 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010694 mStandby = true;
10695 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010696 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010697 return NO_ERROR;
10698}
10699
Andy Hungee58e4a2023-07-07 13:47:37 -070010700status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010701 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10702 return INVALID_OPERATION;
10703}
10704
Andy Hungee58e4a2023-07-07 13:47:37 -070010705void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706{
10707 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10708 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10709 mFormat = mHALFormat;
10710 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10711 result = mHalStream->getFrameSize(&mFrameSize);
10712 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010713 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10714 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010715 result = mHalStream->getBufferSize(&mBufferSize);
10716 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10717 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010718
Andy Hungcf10d742020-04-28 15:38:24 -070010719 // TODO: make a readHalParameters call?
10720 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010721 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010722 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010723 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10724 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10725 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10726 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10727 /*
10728 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10729 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10730 (int32_t)mHapticChannelMask)
10731 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10732 (int32_t)mHapticChannelCount)
10733 */
10734 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010735 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010736 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10737 (int32_t)mFrameCount) // sic - added HAL
10738 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010739}
10740
Andy Hungee58e4a2023-07-07 13:47:37 -070010741bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010742{
Andy Hungab65b182023-09-06 19:41:47 -070010743 {
10744 audio_utils::unique_lock _l(mutex());
10745 checkSilentMode_l();
10746 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010747
10748 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10749
10750 while (!exitPending())
10751 {
Andy Hung116bc262023-06-20 18:56:17 -070010752 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010753
Andy Hung13850be2019-03-14 11:33:09 -070010754 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010755 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010756
Eric Laurent6acd1d42017-01-04 14:23:29 -080010757 if (mSignalPending) {
10758 // A signal was raised while we were unlocked
10759 mSignalPending = false;
10760 } else {
10761 if (mConfigEvents.isEmpty()) {
10762 // we're about to wait, flush the binder command buffer
10763 IPCThreadState::self()->flushCommands();
10764
10765 if (exitPending()) {
10766 break;
10767 }
10768
Eric Laurent6acd1d42017-01-04 14:23:29 -080010769 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010770 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010771 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010772 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010773
10774 checkSilentMode_l();
10775
10776 continue;
10777 }
10778 }
10779
10780 processConfigEvents_l();
10781
10782 processVolume_l();
10783
10784 checkInvalidTracks_l();
10785
Andy Hungab65b182023-09-06 19:41:47 -070010786 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787
Kevin Rocard069c2712018-03-29 19:09:14 -070010788 updateMetadata_l();
10789
Eric Laurent6acd1d42017-01-04 14:23:29 -080010790 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010791 } // release Thread lock
10792
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010794 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795 }
Andy Hung13850be2019-03-14 11:33:09 -070010796
10797 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010798 unlockEffectChains(effectChains);
10799 // Effect chains will be actually deleted here if they were removed from
10800 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010801 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010802 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010803 mThreadloopExecutor.process(); // process any remaining deferred actions.
10804 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010805
10806 threadLoop_exit();
10807
10808 if (!mStandby) {
10809 threadLoop_standby();
10810 mStandby = true;
10811 }
10812
Eric Laurent6acd1d42017-01-04 14:23:29 -080010813 ALOGV("Thread %p type %d exiting", this, mType);
10814 return false;
10815}
10816
Andy Hungc5007f82023-08-29 14:26:09 -070010817// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010818bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010819 status_t& status)
10820{
10821 AudioParameter param = AudioParameter(keyValuePair);
10822 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010823 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010824 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010825 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010826 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010827 if (sendToHal) {
10828 status = mHalStream->setParameters(keyValuePair);
10829 } else {
10830 status = NO_ERROR;
10831 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010832
10833 return false;
10834}
10835
Andy Hungee58e4a2023-07-07 13:47:37 -070010836String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837{
Andy Hung972bec12023-08-31 16:13:39 -070010838 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010839 String8 out_s8;
10840 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10841 return out_s8;
10842 }
Andy Hung920f6572022-10-06 12:09:49 -070010843 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844}
10845
Andy Hungab65b182023-09-06 19:41:47 -070010846void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010847 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010848 sp<AudioIoDescriptor> desc;
10849 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010850 switch (event) {
10851 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010852 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010853 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010854 isInput = true;
10855 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010857 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010859 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10860 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010862 case AUDIO_INPUT_CLOSED:
10863 case AUDIO_OUTPUT_CLOSED:
10864 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010865 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010866 break;
10867 }
Andy Hungab65b182023-09-06 19:41:47 -070010868 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010869}
10870
Andy Hungee58e4a2023-07-07 13:47:37 -070010871status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010872 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010873NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010874{
10875 status_t status = NO_ERROR;
10876
10877 // store new device and send to effects
10878 audio_devices_t type = AUDIO_DEVICE_NONE;
Robert Wuaeb1d002024-10-30 23:19:44 +000010879 DeviceIdVector deviceIds;
jiabinc52b1ff2019-10-31 17:20:42 -070010880 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10881 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10882 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010883 if (isOutput()) {
10884 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010885 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10886 && !mAudioHwDev->supportsAudioPatches(),
10887 "Enumerated device type(%#x) must not be used "
10888 "as it does not support audio patches",
10889 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010890 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010891 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10892 patch->sinks[i].ext.device.address);
Robert Wuaeb1d002024-10-30 23:19:44 +000010893 deviceIds.push_back(patch->sinks[i].id);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010894 }
jiabinc52b1ff2019-10-31 17:20:42 -070010895 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896 } else {
10897 type = patch->sources[0].ext.device.type;
Robert Wuaeb1d002024-10-30 23:19:44 +000010898 deviceIds.push_back(patch->sources[0].id);
jiabinc52b1ff2019-10-31 17:20:42 -070010899 numDevices = mPatch.num_sources;
10900 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010901 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010902 }
10903
10904 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010905 if (isOutput()) {
10906 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10907 } else {
10908 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10909 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010910 }
10911
jiabinc52b1ff2019-10-31 17:20:42 -070010912 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010913 // store new source and send to effects
10914 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10915 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10916 for (size_t i = 0; i < mEffectChains.size(); i++) {
10917 mEffectChains[i]->setAudioSource_l(mAudioSource);
10918 }
10919 }
10920 }
10921
jiabin78b86f22024-02-22 00:39:29 +000010922 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10923 // okay to notify the client earlier before the new patch creation.
Robert Wuaeb1d002024-10-30 23:19:44 +000010924 if (mDeviceIds != deviceIds) {
jiabin78b86f22024-02-22 00:39:29 +000010925 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10926 // The aaudioservice handle the routing changed event asynchronously. In that case,
10927 // it is safe to hold the lock here.
Robert Wuaeb1d002024-10-30 23:19:44 +000010928 callback->onRoutingChanged(deviceIds);
jiabin78b86f22024-02-22 00:39:29 +000010929 }
10930 }
10931
Eric Laurent6acd1d42017-01-04 14:23:29 -080010932 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010933 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10934 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010935 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010936 audio_port_config port;
10937 std::optional<audio_source_t> source;
10938 if (isOutput()) {
10939 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010940 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010941 port = patch->sources[0];
10942 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010943 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010944 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010945 *handle = AUDIO_PATCH_HANDLE_NONE;
10946 }
10947
Robert Wuaeb1d002024-10-30 23:19:44 +000010948 if (numDevices == 0 || mDeviceIds != deviceIds) {
jiabinc52b1ff2019-10-31 17:20:42 -070010949 if (isOutput()) {
10950 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10951 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010952 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010953 } else {
10954 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10955 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10956 }
jiabinc52b1ff2019-10-31 17:20:42 -070010957 mPatch = *patch;
Robert Wuaeb1d002024-10-30 23:19:44 +000010958 mDeviceIds = deviceIds;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010960 // Force meteadata update after a route change
10961 mActiveTracks.setHasChanged();
10962
Eric Laurent6acd1d42017-01-04 14:23:29 -080010963 return status;
10964}
10965
Andy Hungee58e4a2023-07-07 13:47:37 -070010966status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010967{
10968 status_t status = NO_ERROR;
10969
jiabinc52b1ff2019-10-31 17:20:42 -070010970 mPatch = audio_patch{};
10971 mOutDeviceTypeAddrs.clear();
10972 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010973
10974 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10975 supportsAudioPatches : false;
10976
10977 if (supportsAudioPatches) {
10978 status = mHalDevice->releaseAudioPatch(handle);
10979 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010980 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010981 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010982 // Force meteadata update after a route change
10983 mActiveTracks.setHasChanged();
10984
Eric Laurent6acd1d42017-01-04 14:23:29 -080010985 return status;
10986}
10987
Andy Hungee58e4a2023-07-07 13:47:37 -070010988void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010989NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010990{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010991 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010992 if (isOutput()) {
10993 config->role = AUDIO_PORT_ROLE_SOURCE;
10994 config->ext.mix.hw_module = mAudioHwDev->handle();
10995 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10996 } else {
10997 config->role = AUDIO_PORT_ROLE_SINK;
10998 config->ext.mix.hw_module = mAudioHwDev->handle();
10999 config->ext.mix.usecase.source = mAudioSource;
11000 }
11001}
11002
Andy Hungee58e4a2023-07-07 13:47:37 -070011003status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011004{
11005 audio_session_t session = chain->sessionId();
11006
11007 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
11008 // Attach all tracks with same session ID to this chain.
11009 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070011010 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011011 if (session == track->sessionId()) {
11012 chain->incTrackCnt();
11013 chain->incActiveTrackCnt();
11014 }
11015 }
11016
11017 chain->setThread(this);
11018 chain->setInBuffer(nullptr);
11019 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000011020 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011021
11022 mEffectChains.add(chain);
11023 checkSuspendOnAddEffectChain_l(chain);
11024 return NO_ERROR;
11025}
11026
Andy Hungee58e4a2023-07-07 13:47:37 -070011027size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011028{
11029 audio_session_t session = chain->sessionId();
11030
11031 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
11032
11033 for (size_t i = 0; i < mEffectChains.size(); i++) {
11034 if (chain == mEffectChains[i]) {
11035 mEffectChains.removeAt(i);
11036 // detach all active tracks from the chain
11037 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070011038 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011039 if (session == track->sessionId()) {
11040 chain->decActiveTrackCnt();
11041 chain->decTrackCnt();
11042 }
11043 }
11044 break;
11045 }
11046 }
11047 return mEffectChains.size();
11048}
11049
Andy Hungee58e4a2023-07-07 13:47:37 -070011050void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011051{
11052 mHalStream->standby();
11053}
11054
Andy Hungee58e4a2023-07-07 13:47:37 -070011055void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011056{
Phil Burk7dce7282017-09-27 13:51:41 -070011057 // Do not call callback->onTearDown() because it is redundant for thread exit
11058 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059}
11060
Andy Hungee58e4a2023-07-07 13:47:37 -070011061status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011062{
11063 return BAD_VALUE;
11064}
11065
Andy Hungee58e4a2023-07-07 13:47:37 -070011066bool MmapThread::isValidSyncEvent(
11067 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011068{
11069 return false;
11070}
11071
Andy Hungee58e4a2023-07-07 13:47:37 -070011072status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080011073 const effect_descriptor_t *desc, audio_session_t sessionId)
11074{
11075 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080011076 if (audio_is_global_session(sessionId)) {
11077 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080011078 desc->name, mThreadName);
11079 return BAD_VALUE;
11080 }
11081
11082 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
11083 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
11084 desc->name);
11085 return BAD_VALUE;
11086 }
11087 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080011088 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
11089 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011090 return BAD_VALUE;
11091 }
11092
11093 // Only allow effects without processing load or latency
11094 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
11095 return BAD_VALUE;
11096 }
11097
Andy Hung116bc262023-06-20 18:56:17 -070011098 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070011099 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
11100 return BAD_VALUE;
11101 }
11102
Eric Laurent6acd1d42017-01-04 14:23:29 -080011103 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011104}
11105
Andy Hungee58e4a2023-07-07 13:47:37 -070011106void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011107{
Andy Hung8d31fd22023-06-26 19:20:57 -070011108 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011109 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000011110 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
11111 // The aaudioservice handle the routing changed event asynchronously. In that case,
11112 // it is safe to hold the lock here.
Robert Wuaeb1d002024-10-30 23:19:44 +000011113 DeviceIdVector emptyDeviceIdVector;
11114 callback->onRoutingChanged(emptyDeviceIdVector);
jiabin78b86f22024-02-22 00:39:29 +000011115 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020011116 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
11117 mNoCallbackWarningCount++;
11118 }
11119 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011120 }
11121 }
11122}
11123
Andy Hungee58e4a2023-07-07 13:47:37 -070011124void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011125{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011126 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
11127 mAttr.content_type, mAttr.usage, mAttr.source);
11128 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070011129 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011130 dprintf(fd, " No active clients\n");
11131 }
11132}
11133
Andy Hungee58e4a2023-07-07 13:47:37 -070011134void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011135{
Eric Laurent6acd1d42017-01-04 14:23:29 -080011136 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011137 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011138 dprintf(fd, " %zu Tracks\n", numtracks);
11139 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080011140 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011141 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070011142 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011143 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011144 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070011145 result.append(prefix);
11146 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011147 }
11148 } else {
11149 dprintf(fd, "\n");
11150 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000011151 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011152}
11153
Atneya Nairaa3afcb2024-10-08 16:36:19 -070011154std::string MmapThread::getLocalLogHeader() const {
11155 using namespace std::literals;
11156 static constexpr auto indent = " "
11157 " "sv;
11158 return std::string{indent}.append(IAfMmapTrack::getLogHeader());
11159}
11160
Andy Hungee58e4a2023-07-07 13:47:37 -070011161/* static */
11162sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011163 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011164 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011165 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011166}
11167
11168MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070011169 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011170 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011171 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011172 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070011173 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011174{
11175 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
11176 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070011177 mMasterVolume = afThreadCallback->masterVolume_l();
11178 mMasterMute = afThreadCallback->masterMute_l();
Andy Hung6b137d12024-08-27 22:35:17 +000011179 if (!audioserver_flags::portid_volume_management()) {
11180 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11181 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11182 mStreamTypes[stream].volume = 0.0f;
11183 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
11184 }
11185 // Audio patch and call assistant volume are always max
11186 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11187 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11188 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11189 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011190 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011191 if (mAudioHwDev) {
11192 if (mAudioHwDev->canSetMasterVolume()) {
11193 mMasterVolume = 1.0;
11194 }
11195
11196 if (mAudioHwDev->canSetMasterMute()) {
11197 mMasterMute = false;
11198 }
11199 }
11200}
11201
Andy Hungee58e4a2023-07-07 13:47:37 -070011202void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011203 audio_stream_type_t streamType,
11204 audio_session_t sessionId,
11205 const sp<MmapStreamCallback>& callback,
Robert Wuaeb1d002024-10-30 23:19:44 +000011206 const DeviceIdVector& deviceIds,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011207 audio_port_handle_t portId)
11208{
Andy Hung8d672e02023-09-15 18:19:28 -070011209 audio_utils::lock_guard l(mutex());
Robert Wuaeb1d002024-10-30 23:19:44 +000011210 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceIds, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011211 mStreamType = streamType;
11212}
11213
Andy Hungee58e4a2023-07-07 13:47:37 -070011214AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011215{
Andy Hung972bec12023-08-31 16:13:39 -070011216 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011217 AudioStreamOut *output = mOutput;
11218 mOutput = NULL;
11219 return output;
11220}
11221
Andy Hungee58e4a2023-07-07 13:47:37 -070011222void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011223{
Andy Hung972bec12023-08-31 16:13:39 -070011224 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011225 // Don't apply master volume in SW if our HAL can do it for us.
11226 if (mAudioHwDev &&
11227 mAudioHwDev->canSetMasterVolume()) {
11228 mMasterVolume = 1.0;
11229 } else {
11230 mMasterVolume = value;
11231 }
11232}
11233
Andy Hungee58e4a2023-07-07 13:47:37 -070011234void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011235{
Andy Hung972bec12023-08-31 16:13:39 -070011236 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011237 // Don't apply master mute in SW if our HAL can do it for us.
11238 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11239 mMasterMute = false;
11240 } else {
11241 mMasterMute = muted;
11242 }
11243}
11244
Vlad Popa1e865e62024-08-15 19:11:42 -070011245void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011246{
Vlad Popa1e865e62024-08-15 19:11:42 -070011247 ALOGV("%s: stream %d value %f muted %d", __func__, stream, value, muted);
Andy Hung972bec12023-08-31 16:13:39 -070011248 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011249 mStreamTypes[stream].volume = value;
Vlad Popa1e865e62024-08-15 19:11:42 -070011250 if (com_android_media_audio_ring_my_car()) {
11251 mStreamTypes[stream].mute = muted;
11252 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011253 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011254 broadcast_l();
11255 }
11256}
11257
Andy Hungee58e4a2023-07-07 13:47:37 -070011258float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011259{
Andy Hung972bec12023-08-31 16:13:39 -070011260 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011261 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011262}
11263
Andy Hungee58e4a2023-07-07 13:47:37 -070011264void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011265{
Andy Hung972bec12023-08-31 16:13:39 -070011266 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011267 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011268 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011269 broadcast_l();
11270 }
11271}
11272
Andy Hung6b137d12024-08-27 22:35:17 +000011273status_t MmapPlaybackThread::setPortsVolume(
Vlad Popa1e865e62024-08-15 19:11:42 -070011274 const std::vector<audio_port_handle_t>& portIds, float volume, bool muted) {
Andy Hung6b137d12024-08-27 22:35:17 +000011275 audio_utils::lock_guard _l(mutex());
11276 for (const auto& portId : portIds) {
11277 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
11278 if (portId == track->portId()) {
11279 track->setPortVolume(volume);
Vlad Popa1e865e62024-08-15 19:11:42 -070011280 track->setPortMute(muted);
Andy Hung6b137d12024-08-27 22:35:17 +000011281 break;
11282 }
11283 }
11284 }
11285 broadcast_l();
11286 return NO_ERROR;
11287}
11288
Andy Hungee58e4a2023-07-07 13:47:37 -070011289void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011290{
Andy Hung972bec12023-08-31 16:13:39 -070011291 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011292 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011293 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011294 track->invalidate();
11295 }
11296 broadcast_l();
11297 }
11298}
11299
Andy Hungee58e4a2023-07-07 13:47:37 -070011300void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011301{
Andy Hung972bec12023-08-31 16:13:39 -070011302 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011303 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011304 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011305 if (portIds.find(track->portId()) != portIds.end()) {
11306 track->invalidate();
11307 trackMatch = true;
11308 portIds.erase(track->portId());
11309 }
11310 if (portIds.empty()) {
11311 break;
11312 }
11313 }
11314 if (trackMatch) {
11315 broadcast_l();
11316 }
11317}
11318
Andy Hungee58e4a2023-07-07 13:47:37 -070011319void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011320NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011321{
Andy Hung6b137d12024-08-27 22:35:17 +000011322 float volume = 0;
11323 if (!audioserver_flags::portid_volume_management()) {
11324 if (mMasterMute || streamMuted_l()) {
11325 volume = 0;
11326 } else {
11327 volume = mMasterVolume * streamVolume_l();
11328 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011329 } else {
Andy Hung6b137d12024-08-27 22:35:17 +000011330 if (mMasterMute) {
11331 volume = 0;
11332 } else {
11333 // All mmap tracks are declared with the same audio attributes to the audio policy
11334 // manager. Hence, they follow the same routing / volume group. Any change of volume
11335 // will be broadcasted to all tracks. Thus, take arbitrarily first track volume.
11336 size_t numtracks = mActiveTracks.size();
11337 if (numtracks) {
Vlad Popa1e865e62024-08-15 19:11:42 -070011338 if (mActiveTracks[0]->getPortMute()) {
11339 volume = 0;
11340 } else {
11341 volume = mMasterVolume * mActiveTracks[0]->getPortVolume();
11342 }
Andy Hung6b137d12024-08-27 22:35:17 +000011343 }
11344 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011345 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011346 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011347 // Convert volumes from float to 8.24
11348 uint32_t vol = (uint32_t)(volume * (1 << 24));
11349
11350 // Delegate volume control to effect in track effect chain if needed
11351 // only one effect chain can be present on DirectOutputThread, so if
11352 // there is one, the track is connected to it
11353 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011354 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011355 volume = (float)vol / (1 << 24);
11356 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011357 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011358 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11359 mHalVolFloat = volume; // HW volume control worked, so update value.
11360 mNoCallbackWarningCount = 0;
11361 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011362 sp<MmapStreamCallback> callback = mCallback.promote();
11363 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011364 mHalVolFloat = volume; // SW volume control worked, so update value.
11365 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011366 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011367 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011368 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011369 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011370 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11371 ALOGW("Could not set MMAP stream volume: no volume callback!");
11372 mNoCallbackWarningCount++;
11373 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011374 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011375 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011376 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011377 track->setMetadataHasChanged();
Andy Hung6b137d12024-08-27 22:35:17 +000011378 if (!audioserver_flags::portid_volume_management()) {
11379 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11380 /*muteState=*/{mMasterMute,
11381 streamVolume_l() == 0.f,
11382 streamMuted_l(),
11383 // TODO(b/241533526): adjust logic to include mute from AppOps
11384 false /*muteFromPlaybackRestricted*/,
11385 false /*muteFromClientVolume*/,
Vlad Popa1e865e62024-08-15 19:11:42 -070011386 false /*muteFromVolumeShaper*/,
11387 false /*muteFromPortVolume*/});
Andy Hung6b137d12024-08-27 22:35:17 +000011388 } else {
11389 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
11390 /*muteState=*/{mMasterMute,
11391 track->getPortVolume() == 0.f,
11392 /* muteFromStreamMuted= */ false,
11393 // TODO(b/241533526): adjust logic to include mute from AppOps
11394 false /*muteFromPlaybackRestricted*/,
11395 false /*muteFromClientVolume*/,
Vlad Popa1e865e62024-08-15 19:11:42 -070011396 false /*muteFromVolumeShaper*/,
11397 track->getPortMute()});
Andy Hung6b137d12024-08-27 22:35:17 +000011398 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011399 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011400 }
11401}
11402
Andy Hungee58e4a2023-07-07 13:47:37 -070011403ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011404{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011405 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011406 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011407 }
11408 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011409 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011410 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011411 playback_track_metadata_v7_t trackMetadata;
11412 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011413 .usage = track->attributes().usage,
11414 .content_type = track->attributes().content_type,
11415 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011416 };
11417 trackMetadata.channel_mask = track->channelMask(),
11418 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11419 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011420 }
11421 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011422
11423 MetadataUpdate change;
11424 change.playbackMetadataUpdate = metadata.tracks;
11425 return change;
11426};
Kevin Rocard069c2712018-03-29 19:09:14 -070011427
Andy Hungee58e4a2023-07-07 13:47:37 -070011428void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011429{
Atneya Nair967c85f2024-10-27 16:09:50 -070011430 if (property_get_bool("ro.audio.silent", false)) {
11431 ALOGW("ro.audio.silent is now ignored");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011432 }
11433}
11434
Andy Hungee58e4a2023-07-07 13:47:37 -070011435void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011436{
11437 MmapThread::toAudioPortConfig(config);
11438 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11439 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11440 config->flags.output = mOutput->flags;
11441 }
11442}
11443
Andy Hungee58e4a2023-07-07 13:47:37 -070011444status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011445 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011446{
11447 if (mOutput == nullptr) {
11448 return NO_INIT;
11449 }
11450 struct timespec timestamp;
11451 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11452 if (status == NO_ERROR) {
11453 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11454 }
11455 return status;
11456}
11457
Andy Hungee58e4a2023-07-07 13:47:37 -070011458status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011459 // Send to MelProcessor for sound dose measurement.
11460 auto processor = mMelProcessor.load();
11461 if (processor) {
11462 processor->process(buffer, frameCount * mFrameSize);
11463 }
11464
jiabinfc791ee2023-02-15 19:43:40 +000011465 return NO_ERROR;
11466}
11467
Andy Hungc5007f82023-08-29 14:26:09 -070011468// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011469void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011470 const sp<audio_utils::MelProcessor>& processor)
11471{
11472 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011473 mMelProcessor.store(processor);
11474 if (processor) {
11475 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011476 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011477
11478 // no need to update output format for MMapPlaybackThread since it is
11479 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011480}
11481
Andy Hungc5007f82023-08-29 14:26:09 -070011482// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011483void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011484{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011485 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11486 auto melProcessor = mMelProcessor.load();
11487 if (melProcessor != nullptr) {
11488 melProcessor->pause();
11489 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011490}
11491
Andy Hungee58e4a2023-07-07 13:47:37 -070011492void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011493{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011494 MmapThread::dumpInternals_l(fd, args);
Andy Hung6b137d12024-08-27 22:35:17 +000011495 if (!audioserver_flags::portid_volume_management()) {
11496 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d",
11497 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
11498 } else {
11499 dprintf(fd, " HAL volume: %f", mHalVolFloat);
11500 }
11501 dprintf(fd, "\n");
Eric Laurent6acd1d42017-01-04 14:23:29 -080011502 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11503}
11504
Andy Hungee58e4a2023-07-07 13:47:37 -070011505/* static */
11506sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011507 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011508 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011509 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011510}
11511
11512MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011513 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011514 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011515 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011516 mInput(input)
11517{
11518 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11519 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11520}
11521
Andy Hungee58e4a2023-07-07 13:47:37 -070011522status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011523{
Phil Burkf054fc32018-12-06 09:45:59 -080011524 {
11525 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011526 if (mInput != nullptr && mInput->stream != nullptr) {
11527 mInput->stream->setGain(1.0f);
11528 }
11529 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011530 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011531}
11532
Andy Hungee58e4a2023-07-07 13:47:37 -070011533AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011534{
Andy Hung972bec12023-08-31 16:13:39 -070011535 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011536 AudioStreamIn *input = mInput;
11537 mInput = NULL;
11538 return input;
11539}
Kevin Rocard069c2712018-03-29 19:09:14 -070011540
Andy Hungee58e4a2023-07-07 13:47:37 -070011541void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011542{
11543 bool changed = false;
11544 bool silenced = false;
11545
11546 sp<MmapStreamCallback> callback = mCallback.promote();
11547 if (callback == 0) {
11548 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11549 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11550 mNoCallbackWarningCount++;
11551 }
11552 }
11553
11554 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11555 // track is silenced and unmute otherwise
11556 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11557 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11558 changed = true;
11559 silenced = mActiveTracks[i]->isSilenced_l();
11560 }
11561 }
11562
11563 if (changed) {
11564 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11565 }
11566}
11567
Andy Hungee58e4a2023-07-07 13:47:37 -070011568ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011569{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011570 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011571 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011572 }
11573 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011574 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011575 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011576 record_track_metadata_v7_t trackMetadata;
11577 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011578 .source = track->attributes().source,
11579 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011580 };
11581 trackMetadata.channel_mask = track->channelMask(),
11582 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11583 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011584 }
11585 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011586 MetadataUpdate change;
11587 change.recordMetadataUpdate = metadata.tracks;
11588 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011589}
11590
Andy Hungee58e4a2023-07-07 13:47:37 -070011591void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011592{
Andy Hung972bec12023-08-31 16:13:39 -070011593 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011594 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011595 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011596 mActiveTracks[i]->setSilenced_l(silenced);
11597 broadcast_l();
11598 }
11599 }
jiabin09609032022-06-15 19:26:01 +000011600 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011601}
11602
Andy Hungee58e4a2023-07-07 13:47:37 -070011603void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011604{
11605 MmapThread::toAudioPortConfig(config);
11606 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11607 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11608 config->flags.input = mInput->flags;
11609 }
11610}
11611
Andy Hungee58e4a2023-07-07 13:47:37 -070011612status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011613 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011614{
11615 if (mInput == nullptr) {
11616 return NO_INIT;
11617 }
11618 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11619}
11620
jiabinc658e452022-10-21 20:52:21 +000011621// ----------------------------------------------------------------------------
11622
Andy Hungee58e4a2023-07-07 13:47:37 -070011623/* static */
11624sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011625 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011626 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011627 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011628}
11629
Andy Hung583043b2023-07-17 17:05:00 -070011630BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011631 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011632 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011633
Andy Hungee58e4a2023-07-07 13:47:37 -070011634PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011635 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011636 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11637 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011638 float volumeLeft = 1.0f;
11639 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011640 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11641 bitPerfectTrack != nullptr) {
11642 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011643 mAudioMixer->setParameter(
11644 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11645 mAudioMixer->setParameter(
11646 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11647 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011648 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011649 mIsBitPerfect = true;
11650 } else {
11651 mIsBitPerfect = false;
11652 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11653 // active.
11654 for (const auto& track : mActiveTracks) {
11655 const int trackId = track->id();
11656 mAudioMixer->setParameter(
11657 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11658 }
11659 }
jiabin76d94692022-12-15 21:51:21 +000011660 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11661 mVolumeLeft = volumeLeft;
11662 mVolumeRight = volumeRight;
11663 setVolumeForOutput_l(volumeLeft, volumeRight);
11664 }
jiabinc658e452022-10-21 20:52:21 +000011665 return result;
11666}
11667
Andy Hungee58e4a2023-07-07 13:47:37 -070011668void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011669 MixerThread::threadLoop_mix();
11670 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11671}
11672
jiabin220eea12024-05-17 17:55:20 +000011673void BitPerfectThread::setTracksInternalMute(
11674 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
jiabin783a1eb2024-09-18 22:36:19 +000011675 audio_utils::lock_guard _l(mutex());
jiabin220eea12024-05-17 17:55:20 +000011676 for (auto& track : mTracks) {
11677 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11678 track->setInternalMute(it->second);
11679 tracksInternalMute->erase(it);
11680 }
11681 }
11682}
11683
11684sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11685 if (com::android::media::audioserver::
11686 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11687 sp<IAfTrack> bitPerfectTrack = nullptr;
11688 bool allOtherTracksMuted = true;
11689 // Return the bit perfect track if all other tracks are muted
11690 for (const auto& track : mActiveTracks) {
11691 if (track->isBitPerfect()) {
jiabin783a1eb2024-09-18 22:36:19 +000011692 if (track->getInternalMute()) {
11693 // There can only be one bit-perfect client active. If it is mute internally,
11694 // there is no need to stream bit-perfectly.
11695 break;
11696 }
jiabin220eea12024-05-17 17:55:20 +000011697 bitPerfectTrack = track;
11698 } else if (track->getFinalVolume() != 0.f) {
11699 allOtherTracksMuted = false;
11700 if (bitPerfectTrack != nullptr) {
11701 break;
11702 }
11703 }
11704 }
11705 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11706 } else {
11707 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11708 return mActiveTracks[0];
11709 }
11710 }
11711 return nullptr;
11712}
11713
Glenn Kasten63238ef2015-03-02 15:50:29 -080011714} // namespace android