blob: 228eaf6a56325e85ef595b1f79bfc55d0d7606a9 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
Vlad Popab042ee62022-10-20 18:05:00 +020020// #define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Andy Hung25a80ac2023-07-19 12:47:35 -070023#include "Threads.h"
24
25#include "Client.h"
26#include "IAfEffect.h"
27#include "MelReporter.h"
28#include "ResamplerBufferProvider.h"
29
30#include <afutils/DumpTryLock.h>
31#include <afutils/Permission.h>
32#include <afutils/TypedLogger.h>
33#include <afutils/Vibrator.h>
34#include <audio_utils/MelProcessor.h>
35#include <audio_utils/Metadata.h>
jiabin220eea12024-05-17 17:55:20 +000036#include <com_android_media_audioserver.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070037#ifdef DEBUG_CPU_USAGE
38#include <audio_utils/Statistics.h>
39#include <cpustats/ThreadCpuUsage.h>
40#endif
41#include <audio_utils/channels.h>
42#include <audio_utils/format.h>
43#include <audio_utils/minifloat.h>
44#include <audio_utils/mono_blend.h>
45#include <audio_utils/primitives.h>
46#include <audio_utils/safe_math.h>
47#include <audiomanager/AudioManager.h>
48#include <binder/IPCThreadState.h>
49#include <binder/IServiceManager.h>
50#include <binder/PersistableBundle.h>
Eric Laurent4eb45d02023-12-20 12:07:17 +010051#include <com_android_media_audio.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070052#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070054#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070055#include <media/AudioContainers.h>
56#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070057#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070058#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070059#ifdef ADD_BATTERY_DATA
60#include <media/IMediaPlayerService.h>
61#include <media/IMediaDeathNotifier.h>
62#endif
63#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080064#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070065#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070066#include <media/audiohal/EffectsFactoryHalInterface.h>
67#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070068#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080069#include <media/nbaio/AudioStreamOutSink.h>
70#include <media/nbaio/MonoPipe.h>
71#include <media/nbaio/MonoPipeReader.h>
72#include <media/nbaio/Pipe.h>
73#include <media/nbaio/PipeReader.h>
74#include <media/nbaio/SourceAudioBufferProvider.h>
Atneya Nair5997a652024-06-14 17:24:45 -070075#include <media/ValidatedAttributionSourceState.h>
Wei Jia3f273d12015-11-24 09:06:49 -080076#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070077#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070078#include <mediautils/SchedulingPolicyService.h>
79#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070080#include <powermanager/PowerManager.h>
81#include <private/android_filesystem_config.h>
82#include <private/media/AudioTrackShared.h>
83#include <system/audio_effects/effect_aec.h>
84#include <system/audio_effects/effect_downmix.h>
85#include <system/audio_effects/effect_ns.h>
86#include <system/audio_effects/effect_spatializer.h>
87#include <utils/Log.h>
88#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080089
Andy Hung25a80ac2023-07-19 12:47:35 -070090#include <fcntl.h>
91#include <linux/futex.h>
92#include <math.h>
93#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080094#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070095#include <sstream>
96#include <string>
97#include <sys/stat.h>
98#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080099
Eric Laurent81784c32012-11-19 14:55:58 -0800100// ----------------------------------------------------------------------------
101
102// Note: the following macro is used for extremely verbose logging message. In
103// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
104// 0; but one side effect of this is to turn all LOGV's as well. Some messages
105// are so verbose that we want to suppress them even when we have ALOG_ASSERT
106// turned on. Do not uncomment the #def below unless you really know what you
107// are doing and want to see all of the extremely verbose messages.
108//#define VERY_VERY_VERBOSE_LOGGING
109#ifdef VERY_VERY_VERBOSE_LOGGING
110#define ALOGVV ALOGV
111#else
112#define ALOGVV(a...) do { } while(0)
113#endif
114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700116#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700117
Andy Hung6770c6f2015-04-07 13:43:36 -0700118template <typename T>
119static inline T min(const T& a, const T& b)
120{
121 return a < b ? a : b;
122}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700123
Atneya Nair5997a652024-06-14 17:24:45 -0700124using com::android::media::permission::ValidatedAttributionSourceState;
125
Eric Laurent81784c32012-11-19 14:55:58 -0800126namespace android {
127
Andy Hungee58e4a2023-07-07 13:47:37 -0700128using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700129using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000130using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700131
Andy Hung25a80ac2023-07-19 12:47:35 -0700132// Keep in sync with java definition in media/java/android/media/AudioRecord.java
133static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// retry counts for buffer fill timeout
136// 50 * ~20msecs = 1 second
137static const int8_t kMaxTrackRetries = 50;
138static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700139
Eric Laurent81784c32012-11-19 14:55:58 -0800140// allow less retry attempts on direct output thread.
141// direct outputs can be a scarce resource in audio hardware and should
142// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700143// Notes:
144// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
145// in case the data write is bursty for the AudioTrack. The application
146// should endeavor to write at least once every kMaxTrackRetriesDirectMs
147// to prevent an underrun situation. If the data is bursty, then
148// the application can also throttle the data sent to be even.
149// 2) For compressed audio data, any data present in the AudioTrack buffer
150// will be sent and reset the retry count. This delivers data as
151// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
152// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
153// of data to be available, then any remaining data is delivered.
154// This is required to ensure the last bit of data is delivered before underrun.
155//
156// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
157// or the size of the HAL period for proportional / linear PCM tracks.
158static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800159
160// don't warn about blocked writes or record buffer overflows more often than this
161static const nsecs_t kWarningThrottleNs = seconds(5);
162
163// RecordThread loop sleep time upon application overrun or audio HAL read error
164static const int kRecordThreadSleepUs = 5000;
165
Eric Laurent10351942014-05-08 18:49:52 -0700166// maximum time to wait in sendConfigEvent_l() for a status to be received
167static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800168
169// minimum sleep time for the mixer thread loop when tracks are active but in underrun
170static const uint32_t kMinThreadSleepTimeUs = 5000;
171// maximum divider applied to the active sleep time in the mixer thread loop
172static const uint32_t kMaxThreadSleepTimeShift = 2;
173
Andy Hung09a50072014-02-27 14:30:47 -0800174// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700175// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800176static const uint32_t kMinNormalSinkBufferSizeMs = 20;
177// maximum normal sink buffer size
178static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800179
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700180// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
181// FIXME This should be based on experimentally observed scheduling jitter
182static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
183
Eric Laurent972a1732013-09-04 09:42:59 -0700184// Offloaded output thread standby delay: allows track transition without going to standby
185static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
186
Eric Laurent51716182016-02-29 18:00:56 -0800187// Direct output thread minimum sleep time in idle or active(underrun) state
188static const nsecs_t kDirectMinSleepTimeUs = 10000;
189
Brian Lindahl65e90012022-07-27 18:01:07 +0200190// Minimum amount of time between checking to see if the timestamp is advancing
191// for underrun detection. If we check too frequently, we may not detect a
192// timestamp update and will falsely detect underrun.
Andy Hung0ff14292023-12-20 15:55:16 -0800193static constexpr nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1'000'000;
Brian Lindahl65e90012022-07-27 18:01:07 +0200194
Glenn Kasten1b291842016-07-18 14:55:21 -0700195// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
196// balance between power consumption and latency, and allows threads to be scheduled reliably
197// by the CFS scheduler.
198// FIXME Express other hardcoded references to 20ms with references to this constant and move
199// it appropriately.
200#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800201
Eric Laurent81784c32012-11-19 14:55:58 -0800202// Whether to use fast mixer
203static const enum {
204 FastMixer_Never, // never initialize or use: for debugging only
205 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
206 // normal mixer multiplier is 1
207 FastMixer_Static, // initialize if needed, then use all the time if initialized,
208 // multiplier is calculated based on min & max normal mixer buffer size
209 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
210 // multiplier is calculated based on min & max normal mixer buffer size
211 // FIXME for FastMixer_Dynamic:
212 // Supporting this option will require fixing HALs that can't handle large writes.
213 // For example, one HAL implementation returns an error from a large write,
214 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
215 // We could either fix the HAL implementations, or provide a wrapper that breaks
216 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
217} kUseFastMixer = FastMixer_Static;
218
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700219// Whether to use fast capture
220static const enum {
221 FastCapture_Never, // never initialize or use: for debugging only
222 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
223 FastCapture_Static, // initialize if needed, then use all the time if initialized
224} kUseFastCapture = FastCapture_Static;
225
Eric Laurent81784c32012-11-19 14:55:58 -0800226// Priorities for requestPriority
227static const int kPriorityAudioApp = 2;
228static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700229static const int kPriorityFastCapture = 3;
Pattara Teerapong9a332c52024-01-26 08:18:05 +0000230// Request real-time priority for PlaybackThread in ARC
231static const int kPriorityPlaybackThreadArc = 1;
Eric Laurent81784c32012-11-19 14:55:58 -0800232
Glenn Kastenea38ee72016-04-18 11:08:01 -0700233// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
234// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
235// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700236
237// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800238static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800239
Glenn Kasten03490092014-05-27 12:30:54 -0700240// The minimum and maximum allowed values
241static const int kFastTrackMultiplierMin = 1;
242static const int kFastTrackMultiplierMax = 2;
243
244// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
245static int sFastTrackMultiplier = kFastTrackMultiplier;
246
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700247// See Thread::readOnlyHeap().
248// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
249// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
250// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700251static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700252
Andy Hung25a80ac2023-07-19 12:47:35 -0700253static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700254
255static nsecs_t getStandbyTimeInNanos() {
256 static nsecs_t standbyTimeInNanos = []() {
257 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
258 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
259 ALOGI("%s: Using %d ms as standby time", __func__, ms);
260 return milliseconds(ms);
261 }();
262 return standbyTimeInNanos;
263}
264
Andy Hung81994d62023-07-20 21:44:14 -0700265// Set kEnableExtendedChannels to true to enable greater than stereo output
266// for the MixerThread and device sink. Number of channels allowed is
267// FCC_2 <= channels <= FCC_LIMIT.
268constexpr bool kEnableExtendedChannels = true;
269
270// Returns true if channel mask is permitted for the PCM sink in the MixerThread
271/* static */
272bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
273 switch (audio_channel_mask_get_representation(channelMask)) {
274 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
275 // Haptic channel mask is only applicable for channel position mask.
276 const uint32_t channelCount = audio_channel_count_from_out_mask(
277 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
278 const uint32_t maxChannelCount = kEnableExtendedChannels
279 ? FCC_LIMIT : FCC_2;
280 if (channelCount < FCC_2 // mono is not supported at this time
281 || channelCount > maxChannelCount) {
282 return false;
283 }
284 // check that channelMask is the "canonical" one we expect for the channelCount.
285 return audio_channel_position_mask_is_out_canonical(channelMask);
286 }
287 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
288 if (kEnableExtendedChannels) {
289 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
290 if (channelCount >= FCC_2 // mono is not supported at this time
291 && channelCount <= FCC_LIMIT) {
292 return true;
293 }
294 }
295 return false;
296 default:
297 return false;
298 }
299}
300
301// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
302constexpr bool kEnableExtendedPrecision = true;
303
304// Returns true if format is permitted for the PCM sink in the MixerThread
305/* static */
306bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
307 switch (format) {
308 case AUDIO_FORMAT_PCM_16_BIT:
309 return true;
310 case AUDIO_FORMAT_PCM_FLOAT:
311 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
312 case AUDIO_FORMAT_PCM_32_BIT:
313 case AUDIO_FORMAT_PCM_8_24_BIT:
314 return kEnableExtendedPrecision;
315 default:
316 return false;
317 }
318}
319
Eric Laurent81784c32012-11-19 14:55:58 -0800320// ----------------------------------------------------------------------------
321
Andy Hung25a80ac2023-07-19 12:47:35 -0700322// formatToString() needs to be exact for MediaMetrics purposes.
323// Do not use media/TypeConverter.h toString().
324/* static */
325std::string IAfThreadBase::formatToString(audio_format_t format) {
326 std::string result;
327 FormatConverter::toString(format, result);
328 return result;
329}
330
Andy Hungb68f5eb2019-12-03 16:49:17 -0800331// TODO: move all toString helpers to audio.h
332// under #ifdef __cplusplus #endif
333static std::string patchSinksToString(const struct audio_patch *patch)
334{
335 std::stringstream ss;
336 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700337 if (i > 0) {
338 ss << "|";
339 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800340 ss << "(" << toString(patch->sinks[i].ext.device.type)
341 << ", " << patch->sinks[i].ext.device.address << ")";
342 }
343 return ss.str();
344}
345
346static std::string patchSourcesToString(const struct audio_patch *patch)
347{
348 std::stringstream ss;
349 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700350 if (i > 0) {
351 ss << "|";
352 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800353 ss << "(" << toString(patch->sources[i].ext.device.type)
354 << ", " << patch->sources[i].ext.device.address << ")";
355 }
356 return ss.str();
357}
358
Andy Hung4bd53e72022-11-17 17:21:45 -0800359static std::string toString(audio_latency_mode_t mode) {
360 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000361 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
362 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800363}
364
365// Could be made a template, but other toString overloads for std::vector are confused.
366static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
367 std::string s("{ ");
368 for (const auto& e : elements) {
369 s.append(toString(e));
370 s.append(" ");
371 }
372 s.append("}");
373 return s;
374}
375
Glenn Kasten03490092014-05-27 12:30:54 -0700376static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
377
378static void sFastTrackMultiplierInit()
379{
380 char value[PROPERTY_VALUE_MAX];
381 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
382 char *endptr;
383 unsigned long ul = strtoul(value, &endptr, 0);
384 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
385 sFastTrackMultiplier = (int) ul;
386 }
387 }
388}
389
390// ----------------------------------------------------------------------------
391
Eric Laurent81784c32012-11-19 14:55:58 -0800392#ifdef ADD_BATTERY_DATA
393// To collect the amplifier usage
394static void addBatteryData(uint32_t params) {
395 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
396 if (service == NULL) {
397 // it already logged
398 return;
399 }
400
401 service->addBatteryData(params);
402}
403#endif
404
Andy Hung3f0c9022016-01-15 17:49:46 -0800405// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
406struct {
407 // call when you acquire a partial wakelock
408 void acquire(const sp<IBinder> &wakeLockToken) {
409 pthread_mutex_lock(&mLock);
410 if (wakeLockToken.get() == nullptr) {
411 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
412 } else {
413 if (mCount == 0) {
414 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
415 }
416 ++mCount;
417 }
418 pthread_mutex_unlock(&mLock);
419 }
420
421 // call when you release a partial wakelock.
422 void release(const sp<IBinder> &wakeLockToken) {
423 if (wakeLockToken.get() == nullptr) {
424 return;
425 }
426 pthread_mutex_lock(&mLock);
427 if (--mCount < 0) {
428 ALOGE("negative wakelock count");
429 mCount = 0;
430 }
431 pthread_mutex_unlock(&mLock);
432 }
433
434 // retrieves the boottime timebase offset from monotonic.
435 int64_t getBoottimeOffset() {
436 pthread_mutex_lock(&mLock);
437 int64_t boottimeOffset = mBoottimeOffset;
438 pthread_mutex_unlock(&mLock);
439 return boottimeOffset;
440 }
441
442 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
443 // and the selected timebase.
444 // Currently only TIMEBASE_BOOTTIME is allowed.
445 //
446 // This only needs to be called upon acquiring the first partial wakelock
447 // after all other partial wakelocks are released.
448 //
449 // We do an empirical measurement of the offset rather than parsing
450 // /proc/timer_list since the latter is not a formal kernel ABI.
451 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
452 int clockbase;
453 switch (timebase) {
454 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
455 clockbase = SYSTEM_TIME_BOOTTIME;
456 break;
457 default:
458 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
459 break;
460 }
461 // try three times to get the clock offset, choose the one
462 // with the minimum gap in measurements.
463 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700464 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800465 for (int i = 0; i < tries; ++i) {
466 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
467 const nsecs_t tbase = systemTime(clockbase);
468 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
469 const nsecs_t gap = tmono2 - tmono;
470 if (i == 0 || gap < bestGap) {
471 bestGap = gap;
472 measured = tbase - ((tmono + tmono2) >> 1);
473 }
474 }
475
476 // to avoid micro-adjusting, we don't change the timebase
477 // unless it is significantly different.
478 //
479 // Assumption: It probably takes more than toleranceNs to
480 // suspend and resume the device.
481 static int64_t toleranceNs = 10000; // 10 us
482 if (llabs(*offset - measured) > toleranceNs) {
483 ALOGV("Adjusting timebase offset old: %lld new: %lld",
484 (long long)*offset, (long long)measured);
485 *offset = measured;
486 }
487 }
488
489 pthread_mutex_t mLock;
490 int32_t mCount;
491 int64_t mBoottimeOffset;
492} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800493
494// ----------------------------------------------------------------------------
495// CPU Stats
496// ----------------------------------------------------------------------------
497
498class CpuStats {
499public:
500 CpuStats();
501 void sample(const String8 &title);
502#ifdef DEBUG_CPU_USAGE
503private:
504 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700505 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800506
Andy Hung16698b82018-08-01 10:48:38 -0700507 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800508
509 int mCpuNum; // thread's current CPU number
510 int mCpukHz; // frequency of thread's current CPU in kHz
511#endif
512};
513
514CpuStats::CpuStats()
515#ifdef DEBUG_CPU_USAGE
516 : mCpuNum(-1), mCpukHz(-1)
517#endif
518{
519}
520
Glenn Kasten0f11b512014-01-31 16:18:54 -0800521void CpuStats::sample(const String8 &title
522#ifndef DEBUG_CPU_USAGE
523 __unused
524#endif
525 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800526#ifdef DEBUG_CPU_USAGE
527 // get current thread's delta CPU time in wall clock ns
528 double wcNs;
529 bool valid = mCpuUsage.sampleAndEnable(wcNs);
530
531 // record sample for wall clock statistics
532 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700533 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800534 }
535
536 // get the current CPU number
537 int cpuNum = sched_getcpu();
538
539 // get the current CPU frequency in kHz
540 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
541
542 // check if either CPU number or frequency changed
543 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
544 mCpuNum = cpuNum;
545 mCpukHz = cpukHz;
546 // ignore sample for purposes of cycles
547 valid = false;
548 }
549
550 // if no change in CPU number or frequency, then record sample for cycle statistics
551 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const double cycles = wcNs * cpukHz * 0.000001;
553 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800554 }
555
Eric Tan5b13ff82018-07-27 11:20:17 -0700556 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800557 // mCpuUsage.elapsed() is expensive, so don't call it every loop
558 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700559 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800560 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700561 const double perLoop = elapsed / (double) n;
562 const double perLoop100 = perLoop * 0.01;
563 const double perLoop1k = perLoop * 0.001;
564 const double mean = mWcStats.getMean();
565 const double stddev = mWcStats.getStdDev();
566 const double minimum = mWcStats.getMin();
567 const double maximum = mWcStats.getMax();
568 const double meanCycles = mHzStats.getMean();
569 const double stddevCycles = mHzStats.getStdDev();
570 const double minCycles = mHzStats.getMin();
571 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800572 mCpuUsage.resetElapsed();
573 mWcStats.reset();
574 mHzStats.reset();
575 ALOGD("CPU usage for %s over past %.1f secs\n"
576 " (%u mixer loops at %.1f mean ms per loop):\n"
577 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
578 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
579 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000580 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800581 elapsed * .000000001, n, perLoop * .000001,
582 mean * .001,
583 stddev * .001,
584 minimum * .001,
585 maximum * .001,
586 mean / perLoop100,
587 stddev / perLoop100,
588 minimum / perLoop100,
589 maximum / perLoop100,
590 meanCycles / perLoop1k,
591 stddevCycles / perLoop1k,
592 minCycles / perLoop1k,
593 maxCycles / perLoop1k);
594
595 }
596 }
597#endif
598};
599
600// ----------------------------------------------------------------------------
601// ThreadBase
602// ----------------------------------------------------------------------------
603
Glenn Kasten97b7b752014-09-28 13:04:24 -0700604// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700605const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700606{
607 switch (type) {
608 case MIXER:
609 return "MIXER";
610 case DIRECT:
611 return "DIRECT";
612 case DUPLICATING:
613 return "DUPLICATING";
614 case RECORD:
615 return "RECORD";
616 case OFFLOAD:
617 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700618 case MMAP_PLAYBACK:
619 return "MMAP_PLAYBACK";
620 case MMAP_CAPTURE:
621 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200622 case SPATIALIZER:
623 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000624 case BIT_PERFECT:
625 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700626 default:
627 return "unknown";
628 }
629}
630
Andy Hung583043b2023-07-17 17:05:00 -0700631ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700632 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800633 : Thread(false /*canCallJava*/),
634 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700635 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700636 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
637 isOut),
638 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700639 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800640 // are set by PlaybackThread::readOutputParameters_l() or
641 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700642 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700643 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700644 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800645 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700646 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800647 mSystemReady(systemReady),
648 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800649{
Andy Hungcf10d742020-04-28 15:38:24 -0700650 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700651 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Andy Hungee58e4a2023-07-07 13:47:37 -0700654ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800655{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700656 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700657 mConfigEvents.clear();
658
Eric Laurent81784c32012-11-19 14:55:58 -0800659 // do not lock the mutex in destructor
660 releaseWakeLock_l();
661 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800662 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800663 binder->unlinkToDeath(mDeathRecipient);
664 }
Andy Hungd0979812019-02-21 15:51:44 -0800665
666 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800667}
668
Andy Hungee58e4a2023-07-07 13:47:37 -0700669status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700670{
671 status_t status = initCheck();
672 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800673 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700674 } else {
675 ALOGE("No working audio driver found.");
676 }
677 return status;
678}
679
Andy Hungee58e4a2023-07-07 13:47:37 -0700680void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800681{
682 ALOGV("ThreadBase::exit");
683 // do any cleanup required for exit to succeed
684 preExit();
685 {
686 // This lock prevents the following race in thread (uniprocessor for illustration):
687 // if (!exitPending()) {
688 // // context switch from here to exit()
689 // // exit() calls requestExit(), what exitPending() observes
690 // // exit() calls signal(), which is dropped since no waiters
691 // // context switch back from exit() to here
692 // mWaitWorkCV.wait(...);
693 // // now thread is hung
694 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700695 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800696 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700697 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800698 }
699 // When Thread::requestExitAndWait is made virtual and this method is renamed to
700 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
Andy Hung51e73d32024-03-21 19:43:05 -0700701
702 // For TimeCheck: track waiting on the thread join of getTid().
703 audio_utils::mutex::scoped_join_wait_check sjw(getTid());
704
Eric Laurent81784c32012-11-19 14:55:58 -0800705 requestExitAndWait();
706}
707
Andy Hungee58e4a2023-07-07 13:47:37 -0700708status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800709{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000710 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700711 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800712
Eric Laurent10351942014-05-08 18:49:52 -0700713 return sendSetParameterConfigEvent_l(keyValuePairs);
714}
715
716// sendConfigEvent_l() must be called with ThreadBase::mLock held
717// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700718status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700719NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700720{
721 status_t status = NO_ERROR;
722
Eric Laurent72e3f392015-05-20 14:43:50 -0700723 if (event->mRequiresSystemReady && !mSystemReady) {
724 event->mWaitStatus = false;
725 mPendingConfigEvents.add(event);
726 return status;
727 }
Eric Laurent10351942014-05-08 18:49:52 -0700728 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700729 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700730 mWaitWorkCV.notify_one();
731 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700732 {
Andy Hungc5007f82023-08-29 14:26:09 -0700733 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700734 while (event->mWaitStatus) {
Andy Hung02ea2a02024-01-25 17:02:30 -0800735 if (event->mCondition.wait_for(
736 _l, std::chrono::nanoseconds(kConfigEventTimeoutNs), getTid())
737 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700738 event->mStatus = TIMED_OUT;
739 event->mWaitStatus = false;
740 }
741 }
742 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800743 }
Andy Hungc5007f82023-08-29 14:26:09 -0700744 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800745 return status;
746}
747
Andy Hungee58e4a2023-07-07 13:47:37 -0700748void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700749 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800750{
Andy Hung972bec12023-08-31 16:13:39 -0700751 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700752 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800753}
754
Andy Hungc5007f82023-08-29 14:26:09 -0700755// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700756void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700757 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800758{
Andy Hungd0979812019-02-21 15:51:44 -0800759 // The audio statistics history is exponentially weighted to forget events
760 // about five or more seconds in the past. In order to have
761 // crisper statistics for mediametrics, we reset the statistics on
762 // an IoConfigEvent, to reflect different properties for a new device.
763 mIoJitterMs.reset();
764 mLatencyMs.reset();
765 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000766 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100767 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800768
Eric Laurent09f1ed22019-04-24 17:45:17 -0700769 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700770 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800771}
772
Andy Hungee58e4a2023-07-07 13:47:37 -0700773void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700774{
Andy Hung972bec12023-08-31 16:13:39 -0700775 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800776 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700777}
778
Andy Hungc5007f82023-08-29 14:26:09 -0700779// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700780void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800781 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800782{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800783 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700784 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800785}
786
Andy Hungc5007f82023-08-29 14:26:09 -0700787// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700788status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800789{
Andy Hung2ddee192015-12-18 17:34:44 -0800790 sp<ConfigEvent> configEvent;
791 AudioParameter param(keyValuePair);
792 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700793 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800794 setMasterMono_l(value != 0);
795 if (param.size() == 1) {
796 return NO_ERROR; // should be a solo parameter - we don't pass down
797 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700798 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800799 configEvent = new SetParameterConfigEvent(param.toString());
800 } else {
801 configEvent = new SetParameterConfigEvent(keyValuePair);
802 }
Eric Laurent10351942014-05-08 18:49:52 -0700803 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700804}
805
Andy Hungee58e4a2023-07-07 13:47:37 -0700806status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700807 const struct audio_patch *patch,
808 audio_patch_handle_t *handle)
809{
Andy Hung972bec12023-08-31 16:13:39 -0700810 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700811 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
812 status_t status = sendConfigEvent_l(configEvent);
813 if (status == NO_ERROR) {
814 CreateAudioPatchConfigEventData *data =
815 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
816 *handle = data->mHandle;
817 }
818 return status;
819}
820
Andy Hungee58e4a2023-07-07 13:47:37 -0700821status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700822 const audio_patch_handle_t handle)
823{
Andy Hung972bec12023-08-31 16:13:39 -0700824 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700825 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
826 return sendConfigEvent_l(configEvent);
827}
828
Andy Hungee58e4a2023-07-07 13:47:37 -0700829status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700830 const DeviceDescriptorBaseVector& outDevices)
831{
832 if (type() != RECORD) {
833 // The update out device operation is only for record thread.
834 return INVALID_OPERATION;
835 }
Andy Hung972bec12023-08-31 16:13:39 -0700836 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700837 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
838 return sendConfigEvent_l(configEvent);
839}
840
Andy Hungee58e4a2023-07-07 13:47:37 -0700841void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200842{
843 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
844 sp<ConfigEvent> configEvent =
845 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
846 sendConfigEvent_l(configEvent);
847}
Eric Laurent1c333e22014-05-20 10:48:17 -0700848
Andy Hungee58e4a2023-07-07 13:47:37 -0700849void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200850{
Andy Hung972bec12023-08-31 16:13:39 -0700851 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200852 sendCheckOutputStageEffectsEvent_l();
853}
854
Andy Hungee58e4a2023-07-07 13:47:37 -0700855void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200856{
857 sp<ConfigEvent> configEvent =
858 (ConfigEvent *)new CheckOutputStageEffectsEvent();
859 sendConfigEvent_l(configEvent);
860}
861
Andy Hungee58e4a2023-07-07 13:47:37 -0700862void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200863{
864 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
865 sendConfigEvent_l(configEvent);
866}
867
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700868// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700869void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700870{
Eric Laurent10351942014-05-08 18:49:52 -0700871 bool configChanged = false;
872
Eric Laurent81784c32012-11-19 14:55:58 -0800873 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700874 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700875 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800876 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700877 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700878 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700879 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
880 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800881 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700882 true /*asynchronous*/);
883 if (err != 0) {
884 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700885 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700886 }
887 } break;
888 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700889 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Andy Hungab65b182023-09-06 19:41:47 -0700890 ioConfigChanged_l(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700891 } break;
892 case CFG_EVENT_SET_PARAMETER: {
893 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
894 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
895 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700896 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000897 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700898 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700899 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700900 case CFG_EVENT_CREATE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700901 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700902 CreateAudioPatchConfigEventData *data =
903 (CreateAudioPatchConfigEventData *)event->mData.get();
904 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700905 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200906 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700907 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
908 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
909 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700910 } break;
911 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
Andy Hungab65b182023-09-06 19:41:47 -0700912 const DeviceTypeSet oldDevices = getDeviceTypes_l();
Eric Laurent1c333e22014-05-20 10:48:17 -0700913 ReleaseAudioPatchConfigEventData *data =
914 (ReleaseAudioPatchConfigEventData *)event->mData.get();
915 event->mStatus = releaseAudioPatch_l(data->mHandle);
Andy Hungab65b182023-09-06 19:41:47 -0700916 const DeviceTypeSet newDevices = getDeviceTypes_l();
Eric Laurent52568142022-10-28 11:23:28 +0200917 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700918 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
919 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
920 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
921 } break;
922 case CFG_EVENT_UPDATE_OUT_DEVICE: {
923 UpdateOutDevicesConfigEventData *data =
924 (UpdateOutDevicesConfigEventData *)event->mData.get();
925 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700926 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200927 case CFG_EVENT_RESIZE_BUFFER: {
928 ResizeBufferConfigEventData *data =
929 (ResizeBufferConfigEventData *)event->mData.get();
930 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
931 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200932
933 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
934 setCheckOutputStageEffects();
935 } break;
936
Eric Laurent68a40a82022-05-03 18:15:04 +0200937 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
938 onHalLatencyModesChanged_l();
939 } break;
940
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700941 default:
Eric Laurent10351942014-05-08 18:49:52 -0700942 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700943 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800944 }
Eric Laurent10351942014-05-08 18:49:52 -0700945 {
Andy Hung972bec12023-08-31 16:13:39 -0700946 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700947 if (event->mWaitStatus) {
948 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700949 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700950 }
951 }
952 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
953 }
954
955 if (configChanged) {
956 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800957 }
Eric Laurent81784c32012-11-19 14:55:58 -0800958}
959
Marco Nelissenb2208842014-02-07 14:00:50 -0800960String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
961 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700962 const audio_channel_representation_t representation =
963 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700964
965 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800966 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700967 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
968 if (output) {
969 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
971 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700972 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700973 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
974 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
975 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
976 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
977 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
978 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
979 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
980 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
981 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
982 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
983 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
984 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700985 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
986 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
987 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
988 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
989 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
990 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
991 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700992 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700993 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
994 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700995 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
996 } else {
997 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
998 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
999 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
1000 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
1001 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
1002 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
1003 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
1004 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
1005 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
1006 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
1007 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
1008 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -07001009 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
1010 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
1011 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001012 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001013 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1014 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001015 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1016 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1017 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1018 }
1019 const int len = s.length();
1020 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001021 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001022 s.unlockBuffer(len - 2); // remove trailing ", "
1023 }
1024 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001025 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001026 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1027 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1028 return s;
1029 default:
1030 s.appendFormat("unknown mask, representation:%d bits:%#x",
1031 representation, audio_channel_mask_get_bits(mask));
1032 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001033 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001034}
1035
Andy Hungee58e4a2023-07-07 13:47:37 -07001036void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001037NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001038{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001039 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1040 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1041
Andy Hungc5007f82023-08-29 14:26:09 -07001042 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001043 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001044 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001045 }
1046
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001047 dumpBase_l(fd, args);
1048 dumpInternals_l(fd, args);
1049 dumpTracks_l(fd, args);
1050 dumpEffectChains_l(fd, args);
1051
1052 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001053 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001054 }
1055
1056 dprintf(fd, " Local log:\n");
1057 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001058
1059 // --all does the statistics
1060 bool dumpAll = false;
1061 for (const auto &arg : args) {
1062 if (arg == String16("--all")) {
1063 dumpAll = true;
1064 }
1065 }
1066 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001067 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001068 if (!sched.empty()) {
1069 (void)write(fd, sched.c_str(), sched.size());
1070 }
1071 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001072}
1073
Andy Hungee58e4a2023-07-07 13:47:37 -07001074void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001075{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001076 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001077 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001078 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001079 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001080 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1081 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001082 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001083 dprintf(fd, " Channel count: %u\n", mChannelCount);
1084 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001085 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001086 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1087 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001088 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001089 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001090 size_t numConfig = mConfigEvents.size();
1091 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001092 const size_t SIZE = 256;
1093 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001094 for (size_t i = 0; i < numConfig; i++) {
1095 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001096 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001097 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001098 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001099 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001100 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001101 }
Andy Hung293558a2017-03-21 12:19:20 -07001102 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001103 dprintf(fd, " Output devices: %s (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001104 dumpDeviceTypes(outDeviceTypes_l()).c_str(), toString(outDeviceTypes_l()).c_str());
jiabinc52b1ff2019-10-31 17:20:42 -07001105 dprintf(fd, " Input device: %#x (%s)\n",
Andy Hungab65b182023-09-06 19:41:47 -07001106 inDeviceType_l(), toString(inDeviceType_l()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001107 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001108
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001109 // Dump timestamp statistics for the Thread types that support it.
1110 if (mType == RECORD
1111 || mType == MIXER
1112 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001113 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001114 || mType == OFFLOAD
1115 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001116 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungab65b182023-09-06 19:41:47 -07001117 dprintf(fd, " Timestamp corrected: %s\n",
1118 isTimestampCorrectionEnabled_l() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001119 }
1120
Andy Hung446f4df2019-02-21 12:26:41 -08001121 if (mLastIoBeginNs > 0) { // MMAP may not set this
1122 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1123 isOutput() ? "write" : "read",
1124 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1125 }
1126
1127 if (mProcessTimeMs.getN() > 0) {
1128 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1129 }
1130
1131 if (mIoJitterMs.getN() > 0) {
1132 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1133 isOutput() ? "write" : "read",
1134 mIoJitterMs.toString().c_str());
1135 }
1136
Andy Hunge6c37112019-02-26 17:38:10 -08001137 if (mLatencyMs.getN() > 0) {
1138 dprintf(fd, " Threadloop %s latency stats: %s\n",
1139 isOutput() ? "write" : "read",
1140 mLatencyMs.toString().c_str());
1141 }
Robert Wu06db0a32021-08-10 19:05:34 +00001142
1143 if (mMonopipePipeDepthStats.getN() > 0) {
1144 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1145 isOutput() ? "write" : "read",
1146 mMonopipePipeDepthStats.toString().c_str());
1147 }
Eric Laurent81784c32012-11-19 14:55:58 -08001148}
1149
Andy Hungee58e4a2023-07-07 13:47:37 -07001150void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001151{
1152 const size_t SIZE = 256;
1153 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001154
Marco Nelissenb2208842014-02-07 14:00:50 -08001155 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001156 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001157 write(fd, buffer, strlen(buffer));
1158
Marco Nelissenb2208842014-02-07 14:00:50 -08001159 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001160 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001161 if (chain != 0) {
1162 chain->dump(fd, args);
1163 }
1164 }
1165}
1166
Andy Hungee58e4a2023-07-07 13:47:37 -07001167void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001168{
Andy Hung972bec12023-08-31 16:13:39 -07001169 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001170 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001171}
1172
Andy Hungee58e4a2023-07-07 13:47:37 -07001173String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001174{
1175 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001176 case MIXER:
1177 return String16("AudioMix");
1178 case DIRECT:
1179 return String16("AudioDirectOut");
1180 case DUPLICATING:
1181 return String16("AudioDup");
1182 case RECORD:
1183 return String16("AudioIn");
1184 case OFFLOAD:
1185 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001186 case MMAP_PLAYBACK:
1187 return String16("MmapPlayback");
1188 case MMAP_CAPTURE:
1189 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001190 case SPATIALIZER:
1191 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001192 default:
1193 ALOG_ASSERT(false);
1194 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001195 }
1196}
1197
Andy Hungee58e4a2023-07-07 13:47:37 -07001198void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001200 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001201 if (mPowerManager != 0) {
1202 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001203 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001204 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1205 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001206 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001207 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001208 {} /* workSource */,
1209 {} /* historyTag */);
1210 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001211 mWakeLockToken = binder;
1212 }
Chris Ye6597d732020-02-28 22:38:25 -08001213 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001214 }
Wei Jia3f273d12015-11-24 09:06:49 -08001215
Andy Hung3f0c9022016-01-15 17:49:46 -08001216 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001217 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1218 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001219}
1220
Andy Hungee58e4a2023-07-07 13:47:37 -07001221void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001222{
Andy Hung972bec12023-08-31 16:13:39 -07001223 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001224 releaseWakeLock_l();
1225}
1226
Andy Hungee58e4a2023-07-07 13:47:37 -07001227void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001228{
Andy Hung3f0c9022016-01-15 17:49:46 -08001229 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001230 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001231 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001232 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001233 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001234 }
1235 mWakeLockToken.clear();
1236 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001237}
1238
Andy Hungee58e4a2023-07-07 13:47:37 -07001239void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001240 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001241 // use checkService() to avoid blocking if power service is not up yet
1242 sp<IBinder> binder =
1243 defaultServiceManager()->checkService(String16("power"));
1244 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001245 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001246 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001247 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001248 binder->linkToDeath(mDeathRecipient);
1249 }
1250 }
1251}
1252
Andy Hungee58e4a2023-07-07 13:47:37 -07001253void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001254 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001255
1256#if !LOG_NDEBUG
1257 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001258 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001259 s << uid << " ";
1260 }
1261 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1262#endif
1263
Andy Hung438e7572015-12-14 15:51:17 -08001264 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1265 if (mSystemReady) {
1266 ALOGE("no wake lock to update, but system ready!");
1267 } else {
1268 ALOGW("no wake lock to update, system not ready yet");
1269 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001270 return;
1271 }
1272 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001273 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001274 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1275 mWakeLockToken, uidsAsInt);
1276 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001277 }
1278}
1279
Andy Hungee58e4a2023-07-07 13:47:37 -07001280void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001281{
Andy Hung972bec12023-08-31 16:13:39 -07001282 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001283 releaseWakeLock_l();
1284 mPowerManager.clear();
1285}
1286
Andy Hungee58e4a2023-07-07 13:47:37 -07001287void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001288 const DeviceDescriptorBaseVector& outDevices __unused)
1289{
1290 ALOGE("%s should only be called in RecordThread", __func__);
1291}
1292
Andy Hungee58e4a2023-07-07 13:47:37 -07001293void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001294{
1295 ALOGE("%s should only be called in RecordThread", __func__);
1296}
1297
Andy Hungee58e4a2023-07-07 13:47:37 -07001298void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001299{
1300 sp<ThreadBase> thread = mThread.promote();
1301 if (thread != 0) {
1302 thread->clearPowerManager();
1303 }
1304 ALOGW("power manager service died !!!");
1305}
1306
Andy Hungee58e4a2023-07-07 13:47:37 -07001307void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001308 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001309{
Andy Hung116bc262023-06-20 18:56:17 -07001310 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001311 if (chain != 0) {
1312 if (type != NULL) {
1313 chain->setEffectSuspended_l(type, suspend);
1314 } else {
1315 chain->setEffectSuspendedAll_l(suspend);
1316 }
1317 }
1318
1319 updateSuspendedSessions_l(type, suspend, sessionId);
1320}
1321
Andy Hungee58e4a2023-07-07 13:47:37 -07001322void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001323{
1324 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1325 if (index < 0) {
1326 return;
1327 }
1328
1329 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1330 mSuspendedSessions.valueAt(index);
1331
1332 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001333 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001334 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001335 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001336 chain->setEffectSuspendedAll_l(true);
1337 } else {
1338 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1339 desc->mType.timeLow);
1340 chain->setEffectSuspended_l(&desc->mType, true);
1341 }
1342 }
1343 }
1344}
1345
Andy Hungee58e4a2023-07-07 13:47:37 -07001346void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001347 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001348 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001349{
1350 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1351
1352 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1353
1354 if (suspend) {
1355 if (index >= 0) {
1356 sessionEffects = mSuspendedSessions.valueAt(index);
1357 } else {
1358 mSuspendedSessions.add(sessionId, sessionEffects);
1359 }
1360 } else {
1361 if (index < 0) {
1362 return;
1363 }
1364 sessionEffects = mSuspendedSessions.valueAt(index);
1365 }
1366
1367
Andy Hung116bc262023-06-20 18:56:17 -07001368 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001369 if (type != NULL) {
1370 key = type->timeLow;
1371 }
1372 index = sessionEffects.indexOfKey(key);
1373
1374 sp<SuspendedSessionDesc> desc;
1375 if (suspend) {
1376 if (index >= 0) {
1377 desc = sessionEffects.valueAt(index);
1378 } else {
1379 desc = new SuspendedSessionDesc();
1380 if (type != NULL) {
1381 desc->mType = *type;
1382 }
1383 sessionEffects.add(key, desc);
1384 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1385 }
1386 desc->mRefCount++;
1387 } else {
1388 if (index < 0) {
1389 return;
1390 }
1391 desc = sessionEffects.valueAt(index);
1392 if (--desc->mRefCount == 0) {
1393 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1394 sessionEffects.removeItemsAt(index);
1395 if (sessionEffects.isEmpty()) {
1396 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1397 sessionId);
1398 mSuspendedSessions.removeItem(sessionId);
1399 }
1400 }
1401 }
1402 if (!sessionEffects.isEmpty()) {
1403 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1404 }
1405}
1406
Andy Hungee58e4a2023-07-07 13:47:37 -07001407void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001408 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001409 bool threadLocked)
1410NO_THREAD_SAFETY_ANALYSIS // manual locking
1411{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001412 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001413 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001414 }
Eric Laurent81784c32012-11-19 14:55:58 -08001415
Eric Laurent81784c32012-11-19 14:55:58 -08001416 if (mType != RECORD) {
1417 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1418 // another session. This gives the priority to well behaved effect control panels
1419 // and applications not using global effects.
1420 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1421 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001422 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001423 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1424 }
1425 }
1426
Eric Laurent6b446ce2019-12-13 10:56:31 -08001427 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001428 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001429 }
1430}
1431
Andy Hungc5007f82023-08-29 14:26:09 -07001432// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001433status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001434 const effect_descriptor_t *desc, audio_session_t sessionId)
1435{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001436 // No global output effect sessions on record threads
1437 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1438 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001439 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1440 desc->name, mThreadName);
1441 return BAD_VALUE;
1442 }
1443 // only pre processing effects on record thread
1444 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1445 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1446 desc->name, mThreadName);
1447 return BAD_VALUE;
1448 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001449
1450 // always allow effects without processing load or latency
1451 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1452 return NO_ERROR;
1453 }
1454
Eric Laurent4c415062016-06-17 16:14:16 -07001455 audio_input_flags_t flags = mInput->flags;
1456 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1457 if (flags & AUDIO_INPUT_FLAG_RAW) {
1458 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1459 desc->name, mThreadName);
1460 return BAD_VALUE;
1461 }
1462 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1463 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1464 desc->name, mThreadName);
1465 return BAD_VALUE;
1466 }
1467 }
jiabineb3bda02020-06-30 14:07:03 -07001468
Andy Hung116bc262023-06-20 18:56:17 -07001469 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001470 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1471 return BAD_VALUE;
1472 }
Eric Laurent4c415062016-06-17 16:14:16 -07001473 return NO_ERROR;
1474}
1475
Andy Hungc5007f82023-08-29 14:26:09 -07001476// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001477status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001478 const effect_descriptor_t *desc, audio_session_t sessionId)
1479{
1480 // no preprocessing on playback threads
1481 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001482 ALOGW("%s: pre processing effect %s created on playback"
1483 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001484 return BAD_VALUE;
1485 }
1486
Eric Laurent3e4de772017-07-16 16:55:08 -07001487 // always allow effects without processing load or latency
1488 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1489 return NO_ERROR;
1490 }
1491
Andy Hung116bc262023-06-20 18:56:17 -07001492 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
Shunkai Yao4c3af932024-04-26 04:12:21 +00001493 ALOGW("%s: thread (%s) doesn't support haptic playback while the effect is HapticGenerator",
1494 __func__, threadTypeToString(mType));
jiabineb3bda02020-06-30 14:07:03 -07001495 return BAD_VALUE;
1496 }
1497
Eric Laurent4eb45d02023-12-20 12:07:17 +01001498 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentf690c462021-09-17 14:47:03 +02001499 && mType != SPATIALIZER) {
1500 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1501 __func__, mType);
1502 return BAD_VALUE;
1503 }
1504
Eric Laurent4c415062016-06-17 16:14:16 -07001505 switch (mType) {
1506 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001507 audio_output_flags_t flags = mOutput->flags;
1508 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1509 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1510 // global effects are applied only to non fast tracks if they are SW
1511 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1512 break;
1513 }
1514 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1515 // only post processing on output stage session
1516 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001517 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1518 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001519 return BAD_VALUE;
1520 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001521 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1522 // only post processing on output stage session
1523 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001524 ALOGW("%s: non post processing effect %s not allowed on device session",
1525 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001526 return BAD_VALUE;
1527 }
Eric Laurent4c415062016-06-17 16:14:16 -07001528 } else {
1529 // no restriction on effects applied on non fast tracks
1530 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1531 break;
1532 }
1533 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001534
Eric Laurent4c415062016-06-17 16:14:16 -07001535 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001536 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001537 return BAD_VALUE;
1538 }
1539 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001540 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1541 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001542 return BAD_VALUE;
1543 }
1544 }
1545 } break;
1546 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001547 // nothing actionable on offload threads, if the effect:
1548 // - is offloadable: the effect can be created
1549 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1550 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001551 break;
1552 case DIRECT:
1553 // Reject any effect on Direct output threads for now, since the format of
1554 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001555 ALOGW("%s: effect %s on DIRECT output thread %s",
1556 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001557 return BAD_VALUE;
1558 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001559 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001560 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1561 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001562 return BAD_VALUE;
1563 }
1564 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001565 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1566 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001567 return BAD_VALUE;
1568 }
1569 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001570 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1571 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001572 return BAD_VALUE;
1573 }
1574 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001575 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001576 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1577 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1578 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1579 // are supported and added after the spatializer.
1580 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1581 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1582 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001583 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001584 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1585 // only post processing , downmixer or spatializer effects on output stage session
Eric Laurent4eb45d02023-12-20 12:07:17 +01001586 if (IAfEffectModule::isSpatializer(&desc->type)
Eric Laurentb62d0362021-10-26 17:40:18 +02001587 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1588 break;
1589 }
1590 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1591 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1592 __func__, desc->name);
1593 return BAD_VALUE;
1594 }
1595 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1596 // only post processing on output stage session
1597 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1598 ALOGW("%s: non post processing effect %s not allowed on device session",
1599 __func__, desc->name);
1600 return BAD_VALUE;
1601 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001602 }
1603 break;
jiabinc658e452022-10-21 20:52:21 +00001604 case BIT_PERFECT:
1605 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1606 // Allow HW accelerated effects of tunnel type
1607 break;
1608 }
1609 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1610 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1611 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1612 // 3) there is any bit-perfect track with the given session id.
1613 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1614 sessionId == AUDIO_SESSION_DEVICE) {
1615 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1616 __func__, desc->name, mThreadName);
1617 return BAD_VALUE;
1618 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1619 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1620 __func__, desc->name, sessionId);
1621 return BAD_VALUE;
1622 }
1623 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001624 default:
1625 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1626 }
1627
1628 return NO_ERROR;
1629}
1630
Andy Hungc5007f82023-08-29 14:26:09 -07001631// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001632sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001633 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001634 const sp<IEffectClient>& effectClient,
1635 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001636 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001637 effect_descriptor_t *desc,
1638 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001639 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001640 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001641 bool probe,
1642 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001643{
Andy Hung116bc262023-06-20 18:56:17 -07001644 sp<IAfEffectModule> effect;
1645 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001646 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001647 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001648 bool chainCreated = false;
1649 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001650 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001651
1652 lStatus = initCheck();
1653 if (lStatus != NO_ERROR) {
1654 ALOGW("createEffect_l() Audio driver not initialized.");
1655 goto Exit;
1656 }
1657
Eric Laurent81784c32012-11-19 14:55:58 -08001658 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1659
Andy Hungc5007f82023-08-29 14:26:09 -07001660 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001661 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001662
Eric Laurent4c415062016-06-17 16:14:16 -07001663 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001664 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001665 goto Exit;
1666 }
1667
Eric Laurent81784c32012-11-19 14:55:58 -08001668 // check for existing effect chain with the requested audio session
1669 chain = getEffectChain_l(sessionId);
1670 if (chain == 0) {
1671 // create a new chain for this session
1672 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001673 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 addEffectChain_l(chain);
1675 chain->setStrategy(getStrategyForSession_l(sessionId));
1676 chainCreated = true;
1677 } else {
Shunkai Yao29d10572024-03-19 04:31:47 +00001678 effect = chain->getEffectFromDesc(desc);
Eric Laurent81784c32012-11-19 14:55:58 -08001679 }
1680
1681 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1682
1683 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001684 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001685 // create a new effect module if none present in the chain
Shunkai Yao29d10572024-03-19 04:31:47 +00001686 lStatus = chain->createEffect(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001687 if (lStatus != NO_ERROR) {
1688 goto Exit;
1689 }
1690 effectCreated = true;
1691
jiabinc52b1ff2019-10-31 17:20:42 -07001692 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001693 effect->setDevices(outDeviceTypeAddrs());
1694 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001695 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001696 effect->setAudioSource(mAudioSource);
1697 }
jiabin1319f5a2021-03-30 22:21:24 +00001698 if (effect->isHapticGenerator()) {
1699 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1700 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001701 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001702 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001703 if (defaultVibratorInfo) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001704 audio_utils::lock_guard _cl(chain->mutex());
jiabin1319f5a2021-03-30 22:21:24 +00001705 // Only set the vibrator info when it is a valid one.
Shunkai Yaod125e402024-01-20 03:19:06 +00001706 effect->setVibratorInfo_l(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001707 }
1708 }
Eric Laurent81784c32012-11-19 14:55:58 -08001709 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001710 handle = IAfEffectHandle::create(
1711 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001712 lStatus = handle->initCheck();
1713 if (lStatus == OK) {
1714 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001715 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001716 }
Eric Laurent81784c32012-11-19 14:55:58 -08001717 if (enabled != NULL) {
1718 *enabled = (int)effect->isEnabled();
1719 }
1720 }
1721
1722Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001723 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001724 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001725 if (effectCreated) {
Shunkai Yao29d10572024-03-19 04:31:47 +00001726 chain->removeEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001727 }
Eric Laurent81784c32012-11-19 14:55:58 -08001728 if (chainCreated) {
1729 removeEffectChain_l(chain);
1730 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001731 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001732 }
1733
Glenn Kasten9156ef32013-08-06 15:39:08 -07001734 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001735 return handle;
1736}
1737
Andy Hungee58e4a2023-07-07 13:47:37 -07001738void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001739 bool unpinIfLast)
1740{
1741 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001742 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001743 {
Andy Hung972bec12023-08-31 16:13:39 -07001744 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001745 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001746 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001747 return;
1748 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001749 effect = effectBase->asEffectModule();
1750 if (effect == nullptr) {
1751 return;
1752 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001753 // restore suspended effects if the disconnected handle was enabled and the last one.
1754 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1755 if (remove) {
1756 removeEffect_l(effect, true);
1757 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001758 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001759 }
1760 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001761 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001762 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001763 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001764 }
1765 }
1766}
1767
Andy Hungee58e4a2023-07-07 13:47:37 -07001768void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001769 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001770 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001771 broadcast_l();
1772 }
1773 if (!effect->isOffloadable()) {
1774 if (mType == ThreadBase::OFFLOAD) {
1775 PlaybackThread *t = (PlaybackThread *)this;
1776 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1777 }
1778 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001779 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001780 }
1781 }
1782}
1783
Andy Hungee58e4a2023-07-07 13:47:37 -07001784void ThreadBase::onEffectDisable() {
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}
1790
Andy Hungee58e4a2023-07-07 13:47:37 -07001791sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001792 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001793{
Andy Hung972bec12023-08-31 16:13:39 -07001794 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001795 return getEffect_l(sessionId, effectId);
1796}
1797
Andy Hungee58e4a2023-07-07 13:47:37 -07001798sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001799 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001800{
Andy Hung116bc262023-06-20 18:56:17 -07001801 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001802 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1803}
1804
Andy Hungee58e4a2023-07-07 13:47:37 -07001805std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001806{
Andy Hung116bc262023-06-20 18:56:17 -07001807 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Shunkai Yaod125e402024-01-20 03:19:06 +00001808 return chain != nullptr ? chain->getEffectIds_l() : std::vector<int>{};
Eric Laurent6c796322019-04-09 14:13:17 -07001809}
1810
Andy Hung972bec12023-08-31 16:13:39 -07001811// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1812// ThreadBase::mutex() held
1813status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001814{
1815 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001816 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001817 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001818 bool chainCreated = false;
1819
Eric Laurent5baf2af2013-09-12 17:37:00 -07001820 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001821 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1822 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001823
Eric Laurent81784c32012-11-19 14:55:58 -08001824 if (chain == 0) {
1825 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001826 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Shunkai Yao29d10572024-03-19 04:31:47 +00001827 chain = IAfEffectChain::create(this, sessionId, mAfThreadCallback);
Eric Laurent81784c32012-11-19 14:55:58 -08001828 addEffectChain_l(chain);
1829 chain->setStrategy(getStrategyForSession_l(sessionId));
1830 chainCreated = true;
1831 }
Andy Hung972bec12023-08-31 16:13:39 -07001832 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001833
1834 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001835 ALOGW("%s: %p effect %s already present in chain %p",
1836 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001837 return BAD_VALUE;
1838 }
1839
Shunkai Yaod125e402024-01-20 03:19:06 +00001840 effect->setOffloaded_l(mType == OFFLOAD, mId);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001841
Shunkai Yao29d10572024-03-19 04:31:47 +00001842 status_t status = chain->addEffect(effect);
Eric Laurent81784c32012-11-19 14:55:58 -08001843 if (status != NO_ERROR) {
1844 if (chainCreated) {
1845 removeEffectChain_l(chain);
1846 }
1847 return status;
1848 }
1849
jiabin8f278ee2019-11-11 12:16:27 -08001850 effect->setDevices(outDeviceTypeAddrs());
1851 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001852 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001853 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001854
Eric Laurent81784c32012-11-19 14:55:58 -08001855 return NO_ERROR;
1856}
1857
Andy Hungee58e4a2023-07-07 13:47:37 -07001858void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001859
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001860 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001861 effect_descriptor_t desc = effect->desc();
1862 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1863 detachAuxEffect_l(effect->id());
1864 }
1865
Andy Hung116bc262023-06-20 18:56:17 -07001866 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001867 if (chain != 0) {
1868 // remove effect chain if removing last effect
Shunkai Yao29d10572024-03-19 04:31:47 +00001869 if (chain->removeEffect(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001870 removeEffectChain_l(chain);
1871 }
1872 } else {
1873 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1874 }
1875}
1876
Shunkai Yaof4847652024-01-12 00:25:20 +00001877void ThreadBase::lockEffectChains_l(Vector<sp<IAfEffectChain>>& effectChains)
1878 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001879{
1880 effectChains = mEffectChains;
Shunkai Yaof4847652024-01-12 00:25:20 +00001881 for (const auto& effectChain : effectChains) {
1882 effectChain->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001883 }
1884}
1885
Shunkai Yaof4847652024-01-12 00:25:20 +00001886void ThreadBase::unlockEffectChains(const Vector<sp<IAfEffectChain>>& effectChains)
1887 NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001888{
Shunkai Yaof4847652024-01-12 00:25:20 +00001889 for (const auto& effectChain : effectChains) {
1890 effectChain->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001891 }
1892}
1893
Andy Hungee58e4a2023-07-07 13:47:37 -07001894sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001895{
Andy Hung972bec12023-08-31 16:13:39 -07001896 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001897 return getEffectChain_l(sessionId);
1898}
1899
Andy Hungee58e4a2023-07-07 13:47:37 -07001900sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001901 const
Eric Laurent81784c32012-11-19 14:55:58 -08001902{
1903 size_t size = mEffectChains.size();
1904 for (size_t i = 0; i < size; i++) {
1905 if (mEffectChains[i]->sessionId() == sessionId) {
1906 return mEffectChains[i];
1907 }
1908 }
1909 return 0;
1910}
1911
Andy Hungee58e4a2023-07-07 13:47:37 -07001912void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001913{
Andy Hung972bec12023-08-31 16:13:39 -07001914 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001915 size_t size = mEffectChains.size();
1916 for (size_t i = 0; i < size; i++) {
1917 mEffectChains[i]->setMode_l(mode);
1918 }
1919}
1920
Andy Hungee58e4a2023-07-07 13:47:37 -07001921void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001922{
1923 config->type = AUDIO_PORT_TYPE_MIX;
1924 config->ext.mix.handle = mId;
1925 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001926 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001927 config->channel_mask = mChannelMask;
1928 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1929 AUDIO_PORT_CONFIG_FORMAT;
1930}
1931
Andy Hungee58e4a2023-07-07 13:47:37 -07001932void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001933{
Andy Hung972bec12023-08-31 16:13:39 -07001934 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001935 if (mSystemReady) {
1936 return;
1937 }
1938 mSystemReady = true;
1939
1940 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1941 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1942 }
1943 mPendingConfigEvents.clear();
1944}
1945
Andy Hungdae27702016-10-31 14:01:16 -07001946template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001947ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001948 ssize_t index = mActiveTracks.indexOf(track);
1949 if (index >= 0) {
1950 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1951 return index;
1952 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001953 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001954 mActiveTracksGeneration++;
1955 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001956 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001957 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001958 return mActiveTracks.add(track);
1959}
1960
1961template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001962ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001963 ssize_t index = mActiveTracks.remove(track);
1964 if (index < 0) {
1965 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1966 return index;
1967 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001968 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001969 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001970 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001971 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001972 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001973#ifdef TEE_SINK
1974 track->dumpTee(-1 /* fd */, "_REMOVE");
1975#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001976 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001977 return index;
1978}
1979
1980template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001981void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001982 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001983 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001984 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001985 }
1986 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001987 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001988 mActiveTracks.clear();
1989 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001990}
1991
1992template <typename T>
Andy Hungab65b182023-09-06 19:41:47 -07001993void ThreadBase::ActiveTracks<T>::updatePowerState_l(
Andy Hung920f6572022-10-06 12:09:49 -07001994 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001995 // Updates ActiveTracks client uids to the thread wakelock.
1996 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1997 thread->updateWakeLockUids_l(getWakeLockUids());
1998 mLastActiveTracksGeneration = mActiveTracksGeneration;
1999 }
Andy Hungdae27702016-10-31 14:01:16 -07002000}
Eric Laurent83b88082014-06-20 18:31:16 -07002001
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002002template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002003bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002004 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002005 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002006
2007 for (const sp<T> &track : mActiveTracks) {
2008 // Do not short-circuit as all hasChanged states must be reset
2009 // as all the metadata are going to be sent
2010 hasChanged |= track->readAndClearHasChanged();
2011 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002012 return hasChanged;
2013}
2014
2015template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002016void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002017 const char *funcName, const sp<T> &track) const {
2018 if (mLocalLog != nullptr) {
2019 String8 result;
2020 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002021 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002022 }
2023}
2024
Andy Hungee58e4a2023-07-07 13:47:37 -07002025void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002026{
2027 // Thread could be blocked waiting for async
2028 // so signal it to handle state changes immediately
2029 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2030 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2031 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002032 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002033}
2034
Andy Hungd0979812019-02-21 15:51:44 -08002035// Call only from threadLoop() or when it is idle.
2036// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002037void ThreadBase::sendStatistics(bool force)
Andy Hungab65b182023-09-06 19:41:47 -07002038NO_THREAD_SAFETY_ANALYSIS
Andy Hungd0979812019-02-21 15:51:44 -08002039{
2040 // Do not log if we have no stats.
2041 // We choose the timestamp verifier because it is the most likely item to be present.
2042 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2043 if (nstats == 0) {
2044 return;
2045 }
2046
2047 // Don't log more frequently than once per 12 hours.
2048 // We use BOOTTIME to include suspend time.
2049 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2050 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2051 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2052 return;
2053 }
2054
2055 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2056 mLastRecordedTimeNs = timeNs;
2057
Ray Essickf27e9872019-12-07 06:28:46 -08002058 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002059
2060#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2061
2062 // thread configuration
2063 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2064 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2065 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2066 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2067 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2068 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2069 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
Andy Hungab65b182023-09-06 19:41:47 -07002070 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes_l()).c_str());
2071 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType_l()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002072
2073 // thread statistics
2074 if (mIoJitterMs.getN() > 0) {
2075 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2076 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2077 }
2078 if (mProcessTimeMs.getN() > 0) {
2079 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2080 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2081 }
2082 const auto tsjitter = mTimestampVerifier.getJitterMs();
2083 if (tsjitter.getN() > 0) {
2084 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2085 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2086 }
2087 if (mLatencyMs.getN() > 0) {
2088 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2089 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2090 }
Robert Wu06db0a32021-08-10 19:05:34 +00002091 if (mMonopipePipeDepthStats.getN() > 0) {
2092 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2093 mMonopipePipeDepthStats.getMean());
2094 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2095 mMonopipePipeDepthStats.getStdDev());
2096 }
Andy Hungd0979812019-02-21 15:51:44 -08002097
2098 item->selfrecord();
2099}
2100
Andy Hungee58e4a2023-07-07 13:47:37 -07002101product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002102{
Andy Hung583043b2023-07-17 17:05:00 -07002103 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002104 return PRODUCT_STRATEGY_NONE;
2105 }
2106 return AudioSystem::getStrategyForStream(stream);
2107}
2108
Andy Hungc5007f82023-08-29 14:26:09 -07002109// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002110void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002111 const sp<audio_utils::MelProcessor>& /*processor*/)
2112{
2113 // Do nothing
2114 ALOGW("%s: ThreadBase does not support CSD", __func__);
2115}
2116
Andy Hungc5007f82023-08-29 14:26:09 -07002117// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002118void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002119{
2120 // Do nothing
2121 ALOGW("%s: ThreadBase does not support CSD", __func__);
2122}
2123
Eric Laurent81784c32012-11-19 14:55:58 -08002124// ----------------------------------------------------------------------------
2125// Playback
2126// ----------------------------------------------------------------------------
2127
Andy Hung583043b2023-07-17 17:05:00 -07002128PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002129 AudioStreamOut* output,
2130 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002131 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002132 bool systemReady,
2133 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002134 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002135 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002136 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002137 mMixerBuffer(NULL),
2138 mMixerBufferSize(0),
2139 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2140 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002141 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002142 mEffectBuffer(NULL),
2143 mEffectBufferSize(0),
2144 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2145 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002146 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002147 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002148 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002149 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002150 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002151 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002152 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002153 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002154 mMixerStatus(MIXER_IDLE),
2155 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002156 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002157 mBytesRemaining(0),
2158 mCurrentWriteLength(0),
2159 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002160 mWriteAckSequence(0),
2161 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002162 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002163 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002164 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002165 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002166 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002167 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002168 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002169{
Glenn Kastend7dca052015-03-05 16:05:54 -08002170 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002171 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002172
Andy Hungc5007f82023-08-29 14:26:09 -07002173 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002174 // it would be safer to explicitly pass initial masterVolume/masterMute as
2175 // parameter.
2176 //
2177 // If the HAL we are using has support for master volume or master mute,
2178 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2179 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002180 mMasterVolume = afThreadCallback->masterVolume_l();
2181 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002182 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002183 if (mOutput->audioHwDev->canSetMasterVolume()) {
2184 mMasterVolume = 1.0;
2185 }
2186
2187 if (mOutput->audioHwDev->canSetMasterMute()) {
2188 mMasterMute = false;
2189 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002190 mIsMsdDevice = strcmp(
2191 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002192 }
2193
Eric Laurentf1f22e72021-07-13 14:04:14 +02002194 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2195 mMixerChannelMask = mixerConfig->channel_mask;
2196 }
2197
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002198 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002199
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002200 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002201 && mMixerChannelMask != mChannelMask) {
2202 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2203 mChannelMask, mMixerChannelMask);
2204 }
2205
Andy Hungc8fddf32018-08-08 18:32:37 -07002206 // TODO: We may also match on address as well as device type for
2207 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002208 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002209 // TODO: This property should be ensure that only contains one single device type.
2210 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2211 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002212 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2213 : AUDIO_DEVICE_NONE));
2214 }
2215
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002216 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2217 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002218 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002219 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002220 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002221 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002222 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2223 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002224 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2225 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002226}
2227
Andy Hungee58e4a2023-07-07 13:47:37 -07002228PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002229{
Andy Hung583043b2023-07-17 17:05:00 -07002230 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002231 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002232 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002233 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002234 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002235}
2236
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002237// Thread virtuals
2238
Andy Hungee58e4a2023-07-07 13:47:37 -07002239void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002240{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002241 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002242 ALOGE("The stream is not open yet"); // This should not happen.
2243 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002244 // Callbacks take strong or weak pointers as a parameter.
2245 // Since PlaybackThread passes itself as a callback handler, it can only
2246 // be done outside of the constructor. Creating weak and especially strong
2247 // pointers to a refcounted object in its own constructor is strongly
2248 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2249 // Even if a function takes a weak pointer, it is possible that it will
2250 // need to convert it to a strong pointer down the line.
2251 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2252 mOutput->stream->setCallback(this) == OK) {
2253 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002254 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002255 }
2256
jiabinf6eb4c32020-02-25 14:06:25 -08002257 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002258 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002259 }
2260 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002261 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002262 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002263}
2264
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002265// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002266void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002267{
2268 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002269 status_t result = mOutput->stream->exit();
2270 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002271}
2272
Andy Hungee58e4a2023-07-07 13:47:37 -07002273void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002274{
Eric Laurent81784c32012-11-19 14:55:58 -08002275 String8 result;
2276
Marco Nelissenb2208842014-02-07 14:00:50 -08002277 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002278 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2279 const stream_type_t *st = &mStreamTypes[i];
2280 if (i > 0) {
2281 result.appendFormat(", ");
2282 }
2283 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2284 if (st->mute) {
2285 result.append("M");
2286 }
2287 }
2288 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002289 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002290 result.clear();
2291
Eric Laurent81784c32012-11-19 14:55:58 -08002292 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2293 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002294 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002295 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002296
2297 size_t numtracks = mTracks.size();
2298 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002299 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002300 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002301 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002302 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002303 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002304 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002305 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002306 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002307 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002308 if (track != 0) {
2309 bool active = mActiveTracks.indexOf(track) >= 0;
2310 if (active) {
2311 numactiveseen++;
2312 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002313 result.append(prefix);
2314 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002315 }
2316 }
2317 } else {
2318 result.append("\n");
2319 }
2320 if (numactiveseen != numactive) {
2321 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002322 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002323 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002324 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002325 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002326 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002327 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002328 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002329 result.append(prefix);
2330 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002331 }
2332 }
2333 }
2334
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002335 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002336}
2337
Andy Hungee58e4a2023-07-07 13:47:37 -07002338void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002339{
Andy Hung04cb8f72020-03-20 13:44:33 -07002340 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002341 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002342 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2343 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002344 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2345 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2346 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2347 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002348 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002349 dprintf(fd, " Total writes: %d\n", mNumWrites);
2350 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2351 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
Andy Hung8d672e02023-09-15 18:19:28 -07002352 dprintf(fd, " Suspend count: %d\n", (int32_t)mSuspended);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002353 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002354 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002355 AudioStreamOut *output = mOutput;
2356 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002357 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002358 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002359 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2360 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2361 if (mPipeSink.get() != nullptr) {
2362 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2363 }
2364 if (output != nullptr) {
2365 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002366 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002367 }
Eric Laurent81784c32012-11-19 14:55:58 -08002368}
2369
Andy Hungc5007f82023-08-29 14:26:09 -07002370// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002371sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002372 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002373 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002374 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002375 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002376 audio_format_t format,
2377 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002378 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002379 size_t *pNotificationFrameCount,
2380 uint32_t notificationsPerBuffer,
2381 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002382 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002383 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002384 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002385 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002386 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002387 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002388 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002389 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002390 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002391 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002392 bool isBitPerfect,
2393 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002394{
Glenn Kasten74935e42013-12-19 08:56:45 -08002395 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002396 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002397 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002398 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002399 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002400 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002401 uint32_t sampleRate;
2402
2403 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2404 lStatus = BAD_VALUE;
2405 goto Exit;
2406 }
Eric Laurent21da6472017-11-09 16:29:26 -08002407
2408 if (*pSampleRate == 0) {
2409 *pSampleRate = mSampleRate;
2410 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002411 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002412
2413 // special case for FAST flag considered OK if fast mixer is present
2414 if (hasFastMixer()) {
2415 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2416 }
2417
2418 // Check if requested flags are compatible with output stream flags
2419 if ((*flags & outputFlags) != *flags) {
2420 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2421 *flags, outputFlags);
2422 *flags = (audio_output_flags_t)(*flags & outputFlags);
2423 }
Eric Laurent81784c32012-11-19 14:55:58 -08002424
jiabinc658e452022-10-21 20:52:21 +00002425 if (isBitPerfect) {
Andy Hung8d672e02023-09-15 18:19:28 -07002426 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07002427 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002428 if (chain.get() != nullptr) {
2429 // Bit-perfect is required according to the configuration and preferred mixer
2430 // attributes, but it is not in the output flag from the client's request. Explicitly
2431 // adding bit-perfect flag to check the compatibility
2432 audio_output_flags_t flagsToCheck =
2433 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2434 chain->checkOutputFlagCompatibility(&flagsToCheck);
2435 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2436 ALOGE("%s cannot create track as there is data-processing effect attached to "
2437 "given session id(%d)", __func__, sessionId);
2438 lStatus = BAD_VALUE;
2439 goto Exit;
2440 }
2441 *flags = flagsToCheck;
2442 }
2443 }
2444
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002446 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002447 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002448 // PCM data
2449 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002450 // TODO: extract as a data library function that checks that a computationally
2451 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002452 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002453 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2454 (channelMask == AUDIO_CHANNEL_OUT_MONO
2455 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002456 // hardware sample rate
2457 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002458 // normal mixer has an associated fast mixer
2459 hasFastMixer() &&
2460 // there are sufficient fast track slots available
2461 (mFastTrackAvailMask != 0)
2462 // FIXME test that MixerThread for this fast track has a capable output HAL
2463 // FIXME add a permission test also?
2464 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002465 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2466 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002467 // read the fast track multiplier property the first time it is needed
2468 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2469 if (ok != 0) {
2470 ALOGE("%s pthread_once failed: %d", __func__, ok);
2471 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002472 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002473 }
Eric Laurent4c415062016-06-17 16:14:16 -07002474
2475 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002476 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002477 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002478 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002479 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002480 AUDIO_SESSION_OUTPUT_STAGE,
2481 AUDIO_SESSION_OUTPUT_MIX,
2482 sessionId,
2483 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002484 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002485 if (chain.get() != nullptr) {
2486 audio_output_flags_t old = *flags;
2487 chain->checkOutputFlagCompatibility(flags);
2488 if (old != *flags) {
2489 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2490 (int)session, (int)old, (int)*flags);
2491 }
Eric Laurent4c415062016-06-17 16:14:16 -07002492 }
2493 }
2494 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002495 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002496 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2497 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002498 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002499 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002500 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002501 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002502 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002503 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002504 audio_is_linear_pcm(format), channelMask, sampleRate,
2505 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002506 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002507 }
2508 }
Eric Laurent21da6472017-11-09 16:29:26 -08002509
2510 if (!audio_has_proportional_frames(format)) {
2511 if (sharedBuffer != 0) {
2512 // Same comment as below about ignoring frameCount parameter for set()
2513 frameCount = sharedBuffer->size();
2514 } else if (frameCount == 0) {
2515 frameCount = mNormalFrameCount;
2516 }
2517 if (notificationFrameCount != frameCount) {
2518 notificationFrameCount = frameCount;
2519 }
2520 } else if (sharedBuffer != 0) {
2521 // FIXME: Ensure client side memory buffers need
2522 // not have additional alignment beyond sample
2523 // (e.g. 16 bit stereo accessed as 32 bit frame).
2524 size_t alignment = audio_bytes_per_sample(format);
2525 if (alignment & 1) {
2526 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2527 alignment = 1;
2528 }
2529 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2530 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2531 if (channelCount > 1) {
2532 // More than 2 channels does not require stronger alignment than stereo
2533 alignment <<= 1;
2534 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002535 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002536 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002537 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002538 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002539 goto Exit;
2540 }
Eric Laurent21da6472017-11-09 16:29:26 -08002541
2542 // When initializing a shared buffer AudioTrack via constructors,
2543 // there's no frameCount parameter.
2544 // But when initializing a shared buffer AudioTrack via set(),
2545 // there _is_ a frameCount parameter. We silently ignore it.
2546 frameCount = sharedBuffer->size() / frameSize;
2547 } else {
2548 size_t minFrameCount = 0;
2549 // For fast tracks we try to respect the application's request for notifications per buffer.
2550 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2551 if (notificationsPerBuffer > 0) {
2552 // Avoid possible arithmetic overflow during multiplication.
2553 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2554 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2555 notificationsPerBuffer, mFrameCount);
2556 } else {
2557 minFrameCount = mFrameCount * notificationsPerBuffer;
2558 }
2559 }
2560 } else {
2561 // For normal PCM streaming tracks, update minimum frame count.
2562 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2563 // cover audio hardware latency.
2564 // This is probably too conservative, but legacy application code may depend on it.
2565 // If you change this calculation, also review the start threshold which is related.
2566 uint32_t latencyMs = latency_l();
2567 if (latencyMs == 0) {
2568 ALOGE("Error when retrieving output stream latency");
2569 lStatus = UNKNOWN_ERROR;
2570 goto Exit;
2571 }
2572
2573 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2574 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2575
Eric Laurent81784c32012-11-19 14:55:58 -08002576 }
Eric Laurent21da6472017-11-09 16:29:26 -08002577 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002578 frameCount = minFrameCount;
2579 }
Eric Laurent81784c32012-11-19 14:55:58 -08002580 }
Eric Laurent21da6472017-11-09 16:29:26 -08002581
2582 // Make sure that application is notified with sufficient margin before underrun.
2583 // The client can divide the AudioTrack buffer into sub-buffers,
2584 // and expresses its desire to server as the notification frame count.
2585 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2586 size_t maxNotificationFrames;
2587 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2588 // notify every HAL buffer, regardless of the size of the track buffer
2589 maxNotificationFrames = mFrameCount;
2590 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002591 // Triple buffer the notification period for a triple buffered mixer period;
2592 // otherwise, double buffering for the notification period is fine.
2593 //
2594 // TODO: This should be moved to AudioTrack to modify the notification period
2595 // on AudioTrack::setBufferSizeInFrames() changes.
2596 const int nBuffering =
2597 (uint64_t{frameCount} * mSampleRate)
2598 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2599
Eric Laurent21da6472017-11-09 16:29:26 -08002600 maxNotificationFrames = frameCount / nBuffering;
2601 // If client requested a fast track but this was denied, then use the smaller maximum.
2602 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2603 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2604 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2605 maxNotificationFrames = maxNotificationFramesFastDenied;
2606 }
2607 }
2608 }
2609 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2610 if (notificationFrameCount == 0) {
2611 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2612 maxNotificationFrames, frameCount);
2613 } else {
2614 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2615 notificationFrameCount, maxNotificationFrames, frameCount);
2616 }
2617 notificationFrameCount = maxNotificationFrames;
2618 }
2619 }
2620
Glenn Kasten74935e42013-12-19 08:56:45 -08002621 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002622 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002623
Glenn Kastenc3df8382014-03-13 15:05:25 -07002624 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002625 case BIT_PERFECT:
2626 if (isBitPerfect) {
2627 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2628 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2629 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2630 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2631 mChannelMask);
2632 lStatus = BAD_VALUE;
2633 goto Exit;
2634 }
2635 }
2636 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002637
2638 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002639 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002640 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002641 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2642 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002643 sampleRate, format, channelMask, mOutput, mFormat);
2644 lStatus = BAD_VALUE;
2645 goto Exit;
2646 }
2647 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002648 break;
2649
2650 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002651 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002652 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2653 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 sampleRate, format, channelMask, mOutput, mFormat);
2655 lStatus = BAD_VALUE;
2656 goto Exit;
2657 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002658 break;
2659
2660 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002661 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002662 ALOGE("createTrack_l() Bad parameter: format %#x \""
2663 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 format, mOutput, mFormat);
2665 lStatus = BAD_VALUE;
2666 goto Exit;
2667 }
Andy Hungcd044842014-08-07 11:04:34 -07002668 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002669 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2670 lStatus = BAD_VALUE;
2671 goto Exit;
2672 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002673 break;
2674
Eric Laurent81784c32012-11-19 14:55:58 -08002675 }
2676
2677 lStatus = initCheck();
2678 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002679 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002680 goto Exit;
2681 }
2682
Andy Hungc5007f82023-08-29 14:26:09 -07002683 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002684 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002685
2686 // all tracks in same audio session must share the same routing strategy otherwise
2687 // conflicts will happen when tracks are moved from one output to another by audio policy
2688 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002689 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002690 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002691 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002692 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002693 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002694 if (sessionId == t->sessionId() && strategy != actual) {
2695 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2696 strategy, actual);
2697 lStatus = BAD_VALUE;
2698 goto Exit;
2699 }
2700 }
2701 }
2702
Deeraj Soman2b515232024-05-14 12:58:24 +05302703 // Set DIRECT/OFFLOAD flag if current thread is DirectOutputThread/OffloadThread.
2704 // This can happen when the playback is rerouted to direct output/offload thread by
yucliuc9c49cd2020-07-13 16:25:21 -07002705 // dynamic audio policy.
2706 // Do NOT report the flag changes back to client, since the client
Deeraj Soman2b515232024-05-14 12:58:24 +05302707 // doesn't explicitly request a direct/offload flag.
yucliuc9c49cd2020-07-13 16:25:21 -07002708 audio_output_flags_t trackFlags = *flags;
2709 if (mType == DIRECT) {
2710 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
Deeraj Soman2b515232024-05-14 12:58:24 +05302711 } else if (mType == OFFLOAD) {
2712 trackFlags = static_cast<audio_output_flags_t>(trackFlags |
2713 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT);
yucliuc9c49cd2020-07-13 16:25:21 -07002714 }
jiabin94ed47c2023-07-27 23:34:20 +00002715 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002716
Andy Hung8d31fd22023-06-26 19:20:57 -07002717 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002718 channelMask, frameCount,
2719 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002720 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002721 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002722 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002723
Glenn Kasten03003332013-08-06 15:40:54 -07002724 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2725 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002726 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002727 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002728 goto Exit;
2729 }
2730 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002731 {
Andy Hung972bec12023-08-31 16:13:39 -07002732 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002733 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002734 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002735 }
2736 }
Eric Laurent81784c32012-11-19 14:55:58 -08002737
Andy Hung116bc262023-06-20 18:56:17 -07002738 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002739 if (chain != 0) {
2740 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2741 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002742 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002743 chain->incTrackCnt();
2744 }
2745
Eric Laurent05067782016-06-01 18:27:28 -07002746 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002747 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2748 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2749 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002750 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002751 }
2752 }
2753
2754 lStatus = NO_ERROR;
2755
2756Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002757 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002758 return track;
2759}
2760
Andy Hung1bc088a2018-02-09 15:57:31 -08002761template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002762ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002763{
Andy Hungc0691382018-09-12 18:01:57 -07002764 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002765 const ssize_t index = mTracks.remove(track);
2766 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002767 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002768 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002769 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002770 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002771 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002772 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002773 }
2774 return index;
2775}
2776
Andy Hungee58e4a2023-07-07 13:47:37 -07002777uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002778{
2779 return latency;
2780}
2781
Andy Hungee58e4a2023-07-07 13:47:37 -07002782uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002783{
Andy Hung972bec12023-08-31 16:13:39 -07002784 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002785 return latency_l();
2786}
Andy Hungee58e4a2023-07-07 13:47:37 -07002787uint32_t PlaybackThread::latency_l() const
Andy Hungab65b182023-09-06 19:41:47 -07002788NO_THREAD_SAFETY_ANALYSIS
2789// Fix later.
Eric Laurent81784c32012-11-19 14:55:58 -08002790{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002791 uint32_t latency;
2792 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2793 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002794 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002795 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002796}
2797
Andy Hungee58e4a2023-07-07 13:47:37 -07002798void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002799{
Andy Hung972bec12023-08-31 16:13:39 -07002800 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002801 // Don't apply master volume in SW if our HAL can do it for us.
2802 if (mOutput && mOutput->audioHwDev &&
2803 mOutput->audioHwDev->canSetMasterVolume()) {
2804 mMasterVolume = 1.0;
2805 } else {
2806 mMasterVolume = value;
2807 }
2808}
2809
Andy Hungee58e4a2023-07-07 13:47:37 -07002810void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002811{
2812 mMasterBalance.store(balance);
2813}
2814
Andy Hungee58e4a2023-07-07 13:47:37 -07002815void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002816{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002817 if (isDuplicating()) {
2818 return;
2819 }
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 mute in SW if our HAL can do it for us.
2822 if (mOutput && mOutput->audioHwDev &&
2823 mOutput->audioHwDev->canSetMasterMute()) {
2824 mMasterMute = false;
2825 } else {
2826 mMasterMute = muted;
2827 }
2828}
2829
Andy Hungee58e4a2023-07-07 13:47:37 -07002830void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002831{
Andy Hung972bec12023-08-31 16:13:39 -07002832 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002833 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002834 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002835}
2836
Andy Hungee58e4a2023-07-07 13:47:37 -07002837void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002838{
Andy Hung972bec12023-08-31 16:13:39 -07002839 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002840 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002841 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002842}
2843
Andy Hungee58e4a2023-07-07 13:47:37 -07002844float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002845{
Andy Hung972bec12023-08-31 16:13:39 -07002846 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002847 return mStreamTypes[stream].volume;
2848}
2849
Andy Hungee58e4a2023-07-07 13:47:37 -07002850void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002851{
2852 mOutput->stream->setVolume(left, right);
2853}
2854
Andy Hungc5007f82023-08-29 14:26:09 -07002855// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002856status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002857{
2858 status_t status = ALREADY_EXISTS;
2859
Eric Laurent81784c32012-11-19 14:55:58 -08002860 if (mActiveTracks.indexOf(track) < 0) {
2861 // the track is newly added, make sure it fills up all its
2862 // buffers before playing. This is to ensure the client will
2863 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002864 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002865 IAfTrackBase::track_state state = track->state();
Andy Hung6c498e92023-12-05 17:28:17 -08002866 // Because the track is not on the ActiveTracks,
2867 // at this point, only the TrackHandle will be adding the track.
Andy Hungc5007f82023-08-29 14:26:09 -07002868 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002869 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002870 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002872 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002873 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002874 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002875 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002876 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002877 }
2878 return INVALID_OPERATION;
2879 }
2880 // abort if start is rejected by audio policy manager
2881 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002882 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2883 // current playback thread is reopened, which may happen when clients set preferred
2884 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2885 // immediately.
2886 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002887 }
2888#ifdef ADD_BATTERY_DATA
2889 // to track the speaker usage
2890 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2891#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002892 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002893 }
2894
Eric Laurent51716182016-02-29 18:00:56 -08002895 // set retry count for buffer fill
2896 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002897 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002898 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002899 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002900 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002901 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002902 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002903 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002904 track->retryCount() = kMaxTrackStartupRetries;
2905 track->fillingStatus() =
2906 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002907 }
2908
Andy Hung116bc262023-06-20 18:56:17 -07002909 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002910 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2911 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00002912 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
jiabin57303cc2018-12-18 15:45:57 -08002913 // Unlock due to VibratorService will lock for this call and will
2914 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002915 mutex().unlock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002916 const os::HapticScale hapticScale = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002917 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002918 std::optional<media::AudioVibratorInfo> vibratorInfo;
2919 {
2920 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2921 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002922 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002923 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002924 }
Andy Hungc5007f82023-08-29 14:26:09 -07002925 mutex().lock();
Ahmad Khalil229466a2024-02-05 12:15:30 +00002926 track->setHapticScale(hapticScale);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002927 if (vibratorInfo) {
2928 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2929 }
2930
jiabin57303cc2018-12-18 15:45:57 -08002931 // Haptic playback should be enabled by vibrator service.
2932 if (track->getHapticPlaybackEnabled()) {
2933 // Disable haptic playback of all active track to ensure only
2934 // one track playing haptic if current track should play haptic.
2935 for (const auto &t : mActiveTracks) {
2936 t->setHapticPlaybackEnabled(false);
2937 }
jiabin245cdd92018-12-07 17:55:15 -08002938 }
jiabine70bc7f2020-06-30 22:07:55 -07002939
2940 // Set haptic intensity for effect
2941 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00002942 chain->setHapticScale_l(track->id(), hapticScale);
jiabine70bc7f2020-06-30 22:07:55 -07002943 }
jiabin245cdd92018-12-07 17:55:15 -08002944 }
2945
Andy Hung8d31fd22023-06-26 19:20:57 -07002946 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002947 track->resetPresentationComplete();
Andy Hung6c498e92023-12-05 17:28:17 -08002948
2949 // Do not release the ThreadBase mutex after the track is added to mActiveTracks unless
2950 // all key changes are complete. It is possible that the threadLoop will begin
2951 // processing the added track immediately after the ThreadBase mutex is released.
Eric Laurent81784c32012-11-19 14:55:58 -08002952 mActiveTracks.add(track);
Andy Hung6c498e92023-12-05 17:28:17 -08002953
Eric Laurentd0107bc2013-06-11 14:38:48 -07002954 if (chain != 0) {
2955 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2956 track->sessionId());
2957 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002958 }
2959
Andy Hungc2b11cb2020-04-22 09:04:01 -07002960 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002961 status = NO_ERROR;
2962 }
2963
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002964 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002965 return status;
2966}
2967
Andy Hungee58e4a2023-07-07 13:47:37 -07002968bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002969{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002971 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002972 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002973 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002974 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002975 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002976 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002977 if (track->isPausePending()) {
2978 track->pauseAck();
2979 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002980 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002981 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982
2983 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002984}
2985
Andy Hungee58e4a2023-07-07 13:47:37 -07002986void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002987{
2988 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002989
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002990 String8 result;
2991 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002992 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002993
Eric Laurent81784c32012-11-19 14:55:58 -08002994 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002995 {
Andy Hung972bec12023-08-31 16:13:39 -07002996 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002997 mAudioTrackCallbacks.erase(track);
2998 }
Eric Laurent81784c32012-11-19 14:55:58 -08002999 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003000 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07003001 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003002 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3003 mFastTrackAvailMask |= 1 << index;
3004 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07003005 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003006 }
Andy Hung116bc262023-06-20 18:56:17 -07003007 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003008 if (chain != 0) {
3009 chain->decTrackCnt();
3010 }
3011}
3012
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003013std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds_l()
3014{
3015 std::set<int32_t> result;
3016 for (const auto& t : mTracks) {
3017 if (t->isExternalTrack()) {
3018 result.insert(t->portId());
3019 }
3020 }
3021 return result;
3022}
3023
3024std::set<audio_port_handle_t> PlaybackThread::getTrackPortIds()
3025{
3026 audio_utils::lock_guard _l(mutex());
3027 return getTrackPortIds_l();
3028}
3029
Andy Hungee58e4a2023-07-07 13:47:37 -07003030String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003031{
Andy Hung972bec12023-08-31 16:13:39 -07003032 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003033 String8 out_s8;
3034 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3035 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003036 }
Andy Hung920f6572022-10-06 12:09:49 -07003037 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003038}
3039
Andy Hungee58e4a2023-07-07 13:47:37 -07003040status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003041 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003042 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003043 return NO_INIT;
3044 }
3045 return mOutput->stream->selectPresentation(presentationId, programId);
3046}
3047
Andy Hungab65b182023-09-06 19:41:47 -07003048void PlaybackThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003049 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003050 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003051 sp<AudioIoDescriptor> desc;
3052 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003053 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003054 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003055 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003056 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003057 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3058 mSampleRate, mFormat, mChannelMask,
3059 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3060 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003061 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003062 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003063 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003064 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003065 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003066 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003067 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003068 break;
3069 }
Andy Hungab65b182023-09-06 19:41:47 -07003070 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003071}
3072
Andy Hungee58e4a2023-07-07 13:47:37 -07003073void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003074{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003075 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003076}
3077
Andy Hungee58e4a2023-07-07 13:47:37 -07003078void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003079{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003080 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003081}
3082
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003083void PlaybackThread::onError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003084{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07003085 mCallbackThread->setAsyncError(isHardError);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003086}
3087
Andy Hungee58e4a2023-07-07 13:47:37 -07003088void PlaybackThread::onCodecFormatChanged(
Ryan Prichard78c5e452024-02-08 16:16:57 -08003089 const std::vector<uint8_t>& metadataBs)
jiabinf6eb4c32020-02-25 14:06:25 -08003090{
Andy Hungee58e4a2023-07-07 13:47:37 -07003091 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003092 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003093 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003094 if (playbackThread == nullptr) {
3095 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3096 return;
3097 }
3098
jiabinf6eb4c32020-02-25 14:06:25 -08003099 audio_utils::metadata::Data metadata =
3100 audio_utils::metadata::dataFromByteString(metadataBs);
3101 if (metadata.empty()) {
3102 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3103 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3104 (int)metadataBs.size());
3105 return;
3106 }
3107
3108 audio_utils::metadata::ByteString metaDataStr =
3109 audio_utils::metadata::byteStringFromData(metadata);
3110 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003111 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003112 for (const auto& callbackPair : mAudioTrackCallbacks) {
3113 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003114 }
3115 }).detach();
3116}
3117
Andy Hungee58e4a2023-07-07 13:47:37 -07003118void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003119{
Andy Hung972bec12023-08-31 16:13:39 -07003120 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003121 // reject out of sequence requests
3122 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3123 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003124 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003125 }
3126}
3127
Andy Hungee58e4a2023-07-07 13:47:37 -07003128void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003129{
Andy Hung972bec12023-08-31 16:13:39 -07003130 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003131 // reject out of sequence requests
3132 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003133 // Register discontinuity when HW drain is completed because that can cause
3134 // the timestamp frame position to reset to 0 for direct and offload threads.
3135 // (Out of sequence requests are ignored, since the discontinuity would be handled
3136 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003137 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003138 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003139 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003140 }
3141}
3142
Andy Hungee58e4a2023-07-07 13:47:37 -07003143void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003144NO_THREAD_SAFETY_ANALYSIS
3145// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003146{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003147 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003148 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3149 mSampleRate = audioConfig.sample_rate;
3150 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003151 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003152 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003153 }
Andy Hung81994d62023-07-20 21:44:14 -07003154 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003155 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3156 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003157 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003158
3159 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3160 mMixerChannelMask = mChannelMask;
3161 }
3162
Andy Hunge5412692014-05-16 11:25:07 -07003163 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003164 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003165
Eric Laurentf1f22e72021-07-13 14:04:14 +02003166 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3167
Phil Burkca5e6142015-07-14 09:42:29 -07003168 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003169 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003170 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003171 // Get format from the shim, which will be different than the HAL format
3172 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003173 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003174 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003175 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003176 }
Andy Hung81994d62023-07-20 21:44:14 -07003177 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003178 LOG_FATAL("HAL format %#x not supported for mixed output",
3179 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003180 }
Phil Burk062e67a2015-02-11 13:40:50 -08003181 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003182 result = mOutput->stream->getBufferSize(&mBufferSize);
3183 LOG_ALWAYS_FATAL_IF(result != OK,
3184 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003185 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003186 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003187 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003188 mFrameCount);
3189 }
3190
Eric Laurentd1f69b02014-12-15 14:33:13 -08003191 mHwSupportsPause = false;
3192 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003193 bool supportsPause = false, supportsResume = false;
3194 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3195 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003196 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003197 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003198 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003199 } else if (supportsResume) {
3200 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003201 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003202 }
3203 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003204 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3205 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3206 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003207
Andy Hungfbfc3952015-01-15 13:33:51 -08003208 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3209 // For best precision, we use float instead of the associated output
3210 // device format (typically PCM 16 bit).
3211
3212 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3213 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3214 mBufferSize = mFrameSize * mFrameCount;
3215
3216 // TODO: We currently use the associated output device channel mask and sample rate.
3217 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3218 // (if a valid mask) to avoid premature downmix.
3219 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3220 // instead of the output device sample rate to avoid loss of high frequency information.
3221 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3222 }
3223
Andy Hung09a50072014-02-27 14:30:47 -08003224 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003225 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003226 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003227 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3228 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003229 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3230 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003231
Eric Laurent81784c32012-11-19 14:55:58 -08003232 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3233 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3234 maxNormalFrameCount = maxNormalFrameCount & ~15;
3235 if (maxNormalFrameCount < minNormalFrameCount) {
3236 maxNormalFrameCount = minNormalFrameCount;
3237 }
3238 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3239 if (multiplier <= 1.0) {
3240 multiplier = 1.0;
3241 } else if (multiplier <= 2.0) {
3242 if (2 * mFrameCount <= maxNormalFrameCount) {
3243 multiplier = 2.0;
3244 } else {
3245 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3246 }
3247 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003248 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003249 }
3250 }
3251 mNormalFrameCount = multiplier * mFrameCount;
3252 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003253 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003254 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3255 }
Andy Hungab65b182023-09-06 19:41:47 -07003256 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames",
3257 (size_t)mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08003258
Andy Hung08fb1742015-05-31 23:22:10 -07003259 // Check if we want to throttle the processing to no more than 2x normal rate
3260 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003261 mThreadThrottleTimeMs = 0;
3262 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003263 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3264
Andy Hung010a1a12014-03-13 13:57:33 -07003265 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3266 // Originally this was int16_t[] array, need to remove legacy implications.
3267 free(mSinkBuffer);
3268 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003269
Andy Hung5b10a202014-03-13 13:59:29 -07003270 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3271 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3272 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003273 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003274
Andy Hung69aed5f2014-02-25 17:24:40 -08003275 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3276 // drives the output.
3277 free(mMixerBuffer);
3278 mMixerBuffer = NULL;
3279 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003280 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003281 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003282 * audio_bytes_per_sample(mMixerBufferFormat);
3283 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3284 }
Andy Hung98ef9782014-03-04 14:46:50 -08003285 free(mEffectBuffer);
3286 mEffectBuffer = NULL;
3287 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003288 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003289 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003290 * audio_bytes_per_sample(mEffectBufferFormat);
3291 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3292 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003293
Eric Laurentb62d0362021-10-26 17:40:18 +02003294 if (mType == SPATIALIZER) {
3295 free(mPostSpatializerBuffer);
3296 mPostSpatializerBuffer = nullptr;
3297 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3298 * audio_bytes_per_sample(mEffectBufferFormat);
3299 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3300 }
3301
Mikhail Naganov55773032020-10-01 15:08:13 -07003302 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3303 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003304 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3305 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003306 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003307
Eric Laurent81784c32012-11-19 14:55:58 -08003308 // force reconfiguration of effect chains and engines to take new buffer size and audio
3309 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003310 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003311 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3312 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003313 // create a copy of mEffectChains as calling moveEffectChain_ll()
3314 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003315 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003316 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003317 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003318 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003319 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003320
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003321 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003322 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003323 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003324 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003325 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3326 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3327 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3328 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3329 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3330 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3331 (int32_t)mHapticChannelMask)
3332 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3333 (int32_t)mHapticChannelCount)
3334 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003335 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003336 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3337 (int32_t)mFrameCount) // sic - added HAL
3338 ;
3339 uint32_t latencyMs;
3340 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3341 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3342 }
3343 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003344}
3345
Andy Hungee58e4a2023-07-07 13:47:37 -07003346ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003347{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003348 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003349 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003350 }
3351 StreamOutHalInterface::SourceMetadata metadata;
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08003352 static const bool stereo_spatialization_property =
3353 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
3354 const bool stereo_spatialization_enabled =
3355 stereo_spatialization_property && com_android_media_audio_stereo_spatialization();
3356 if (stereo_spatialization_enabled) {
Eric Laurent4eb45d02023-12-20 12:07:17 +01003357 std::map<audio_session_t, std::vector<playback_track_metadata_v7_t> >allSessionsMetadata;
3358 for (const sp<IAfTrack>& track : mActiveTracks) {
3359 std::vector<playback_track_metadata_v7_t>& sessionMetadata =
3360 allSessionsMetadata[track->sessionId()];
3361 auto backInserter = std::back_inserter(sessionMetadata);
3362 // No track is invalid as this is called after prepareTrack_l in the same
3363 // critical section
3364 track->copyMetadataTo(backInserter);
3365 }
3366 std::vector<playback_track_metadata_v7_t> spatializedTracksMetaData;
3367 for (const auto& [session, sessionTrackMetadata] : allSessionsMetadata) {
3368 metadata.tracks.insert(metadata.tracks.end(),
3369 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3370 if (auto chain = getEffectChain_l(session) ; chain != nullptr) {
3371 chain->sendMetadata_l(sessionTrackMetadata, {});
3372 }
3373 if ((hasAudioSession_l(session) & IAfThreadBase::SPATIALIZED_SESSION) != 0) {
3374 spatializedTracksMetaData.insert(spatializedTracksMetaData.end(),
3375 sessionTrackMetadata.begin(), sessionTrackMetadata.end());
3376 }
3377 }
3378 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); chain != nullptr) {
3379 chain->sendMetadata_l(metadata.tracks, {});
3380 }
3381 if (auto chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE); chain != nullptr) {
3382 chain->sendMetadata_l(metadata.tracks, spatializedTracksMetaData);
3383 }
3384 if (auto chain = getEffectChain_l(AUDIO_SESSION_DEVICE); chain != nullptr) {
3385 chain->sendMetadata_l(metadata.tracks, {});
3386 }
3387 } else {
3388 auto backInserter = std::back_inserter(metadata.tracks);
3389 for (const sp<IAfTrack>& track : mActiveTracks) {
3390 // No track is invalid as this is called after prepareTrack_l in the same
3391 // critical section
3392 track->copyMetadataTo(backInserter);
3393 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003394 }
Kevin Rocard12381092018-04-11 09:19:59 -07003395 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003396 MetadataUpdate change;
3397 change.playbackMetadataUpdate = metadata.tracks;
3398 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003399}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003400
Andy Hungee58e4a2023-07-07 13:47:37 -07003401void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003402 const StreamOutHalInterface::SourceMetadata& metadata)
3403{
3404 mOutput->stream->updateSourceMetadata(metadata);
3405};
3406
Andy Hungee58e4a2023-07-07 13:47:37 -07003407status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003408 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003409{
3410 if (halFrames == NULL || dspFrames == NULL) {
3411 return BAD_VALUE;
3412 }
Andy Hung972bec12023-08-31 16:13:39 -07003413 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003414 if (initCheck() != NO_ERROR) {
3415 return INVALID_OPERATION;
3416 }
Andy Hung818e7a32016-02-16 18:08:07 -08003417 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003418 *halFrames = framesWritten;
3419
3420 if (isSuspended()) {
3421 // return an estimation of rendered frames when the output is suspended
3422 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003423 *dspFrames = (uint32_t)
3424 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003425 return NO_ERROR;
3426 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003427 status_t status;
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003428 uint64_t frames = 0;
Phil Burk062e67a2015-02-11 13:40:50 -08003429 status = mOutput->getRenderPosition(&frames);
Mikhail Naganov0ea58fe2024-05-10 13:30:40 -07003430 *dspFrames = (uint32_t)frames;
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003431 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003432 }
3433}
3434
Andy Hungee58e4a2023-07-07 13:47:37 -07003435product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003436{
3437 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3438 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3439 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003440 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003441 }
3442 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003443 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003444 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003445 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003446 }
3447 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003448 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003449}
3450
3451
Andy Hungee58e4a2023-07-07 13:47:37 -07003452AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003453{
Andy Hung972bec12023-08-31 16:13:39 -07003454 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003455 return mOutput;
3456}
3457
Andy Hungee58e4a2023-07-07 13:47:37 -07003458AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003459{
Andy Hung972bec12023-08-31 16:13:39 -07003460 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003461 AudioStreamOut *output = mOutput;
3462 mOutput = NULL;
3463 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3464 // must push a NULL and wait for ack
3465 mOutputSink.clear();
3466 mPipeSink.clear();
3467 mNormalSink.clear();
3468 return output;
3469}
3470
Andy Hungc5007f82023-08-29 14:26:09 -07003471// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003472sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003473{
3474 if (mOutput == NULL) {
3475 return NULL;
3476 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003477 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003478}
3479
Andy Hungee58e4a2023-07-07 13:47:37 -07003480uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003481{
3482 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3483}
3484
Andy Hungee58e4a2023-07-07 13:47:37 -07003485status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003486{
3487 if (!isValidSyncEvent(event)) {
3488 return BAD_VALUE;
3489 }
3490
Andy Hung972bec12023-08-31 16:13:39 -07003491 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003492
3493 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003494 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003495 if (event->triggerSession() == track->sessionId()) {
3496 (void) track->setSyncEvent(event);
3497 return NO_ERROR;
3498 }
3499 }
3500
3501 return NAME_NOT_FOUND;
3502}
3503
Andy Hungee58e4a2023-07-07 13:47:37 -07003504bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003505{
3506 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3507}
3508
Andy Hungee58e4a2023-07-07 13:47:37 -07003509void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003510 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003511{
Andy Hungfe726a62018-09-27 15:17:25 -07003512 // Miscellaneous track cleanup when removed from the active list,
3513 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003514#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003515 for (const auto& track : tracksToRemove) {
3516 if (track->isExternalTrack()) {
3517 // to track the speaker usage
3518 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003519 }
3520 }
Andy Hungfe726a62018-09-27 15:17:25 -07003521#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003522}
3523
Andy Hungee58e4a2023-07-07 13:47:37 -07003524void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003525{
3526 if (!mMasterMute) {
3527 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003528 if (mOutDeviceTypeAddrs.empty()) {
3529 ALOGD("ro.audio.silent is ignored since no output device is set");
3530 return;
3531 }
Andy Hungab65b182023-09-06 19:41:47 -07003532 if (isSingleDeviceType(outDeviceTypes_l(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003533 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3534 return;
3535 }
Eric Laurent81784c32012-11-19 14:55:58 -08003536 if (property_get("ro.audio.silent", value, "0") > 0) {
3537 char *endptr;
3538 unsigned long ul = strtoul(value, &endptr, 0);
3539 if (*endptr == '\0' && ul != 0) {
Shunkai Yaodd3de692024-03-06 02:56:57 +00003540 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // The setprop command will not allow a property to be changed after
3542 // the first time it is set, so we don't have to worry about un-muting.
3543 setMasterMute_l(true);
3544 }
3545 }
3546 }
3547}
3548
3549// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003550ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003551{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003552 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003553 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003554 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003555 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003556
3557 // If an NBAIO sink is present, use it to write the normal mixer's submix
3558 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003559
Andy Hung010a1a12014-03-13 13:57:33 -07003560 const size_t count = mBytesRemaining / mFrameSize;
3561
Simon Wilson2d590962012-11-29 15:18:50 -08003562 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003563 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003564 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003565 if (screenState != mScreenState) {
3566 mScreenState = screenState;
3567 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3568 if (pipe != NULL) {
3569 pipe->setAvgFrames((mScreenState & 1) ?
3570 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3571 }
3572 }
Andy Hung010a1a12014-03-13 13:57:33 -07003573 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003574 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003575
Eric Laurent81784c32012-11-19 14:55:58 -08003576 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003577 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003578
Andy Hung8946a282018-04-19 20:04:56 -07003579#ifdef TEE_SINK
3580 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3581#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003582 } else {
3583 bytesWritten = framesWritten;
3584 }
3585 // otherwise use the HAL / AudioStreamOut directly
3586 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003588
Eric Laurentbfb1b832013-01-07 09:53:42 -08003589 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003590 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3591 mWriteAckSequence += 2;
3592 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003593 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003594 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003595 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003596 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003597 // FIXME We should have an implementation of timestamps for direct output threads.
3598 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003599 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003600 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003601
Eric Laurentbfb1b832013-01-07 09:53:42 -08003602 if (mUseAsyncWrite &&
3603 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3604 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003605 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003606 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003607 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003608 }
Eric Laurent81784c32012-11-19 14:55:58 -08003609 }
3610
Eric Laurent81784c32012-11-19 14:55:58 -08003611 mNumWrites++;
3612 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003613 if (mStandby) {
3614 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003615 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003616 mStandby = false;
3617 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003618 return bytesWritten;
3619}
3620
Andy Hungc5007f82023-08-29 14:26:09 -07003621// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003622void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003623 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003624{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003625 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003626 if (outputSink != nullptr) {
3627 outputSink->startMelComputation(processor);
3628 }
Vlad Popab042ee62022-10-20 18:05:00 +02003629}
3630
Andy Hungc5007f82023-08-29 14:26:09 -07003631// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003632void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003633{
3634 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003635 if (outputSink != nullptr) {
3636 outputSink->stopMelComputation();
3637 }
Vlad Popab042ee62022-10-20 18:05:00 +02003638}
3639
Andy Hungee58e4a2023-07-07 13:47:37 -07003640void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003641{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003642 bool supportsDrain = false;
3643 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003644 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3645 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003646 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3647 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003648 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003649 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003650 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003651 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003652 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003653 }
3654}
3655
Andy Hungee58e4a2023-07-07 13:47:37 -07003656void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003657{
Eric Laurent275e8e92014-11-30 15:14:47 -08003658 {
Andy Hung972bec12023-08-31 16:13:39 -07003659 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003660 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003661 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003662 track->invalidate();
3663 }
Andy Hungdae27702016-10-31 14:01:16 -07003664 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3665 // After we exit there are no more track changes sent to BatteryNotifier
3666 // because that requires an active threadLoop.
3667 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3668 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003669 }
Eric Laurent81784c32012-11-19 14:55:58 -08003670}
3671
3672/*
3673The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003674 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003675 - mActiveSleepTimeUs from activeSleepTimeUs()
3676 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003677 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3678 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003679 - maxPeriod from frame count and sample rate (MIXER only)
3680
3681The parameters that affect these derived values are:
3682 - frame count
3683 - frame size
3684 - sample rate
3685 - device type: A2DP or not
3686 - device latency
3687 - format: PCM or not
3688 - active sleep time
3689 - idle sleep time
3690*/
3691
Andy Hungee58e4a2023-07-07 13:47:37 -07003692void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003693{
Andy Hung25c2dac2014-02-27 14:56:00 -08003694 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003695 mActiveSleepTimeUs = activeSleepTimeUs();
3696 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003697
Andy Hung8fe87eb2023-07-20 21:31:38 -07003698 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003699
Eric Laurent42537be2016-01-08 17:16:42 -08003700 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3701 // truncating audio when going to standby.
Andy Hungab65b182023-09-06 19:41:47 -07003702 if (!Intersection(outDeviceTypes_l(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003703 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3704 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3705 }
3706 }
Eric Laurent81784c32012-11-19 14:55:58 -08003707}
3708
Andy Hungee58e4a2023-07-07 13:47:37 -07003709bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003710{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003711 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003712 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003713 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003714 size_t size = mTracks.size();
3715 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003716 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003717 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003718 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003719 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003720 }
3721 }
Eric Laurent13084622016-05-17 10:51:49 -07003722 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003723}
3724
Andy Hungee58e4a2023-07-07 13:47:37 -07003725void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003726{
Andy Hung972bec12023-08-31 16:13:39 -07003727 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003728 invalidateTracks_l(streamType);
3729}
3730
Andy Hungee58e4a2023-07-07 13:47:37 -07003731void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003732 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003733 invalidateTracks_l(portIds);
3734}
3735
Andy Hungee58e4a2023-07-07 13:47:37 -07003736bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003737 bool trackMatch = false;
3738 const size_t size = mTracks.size();
3739 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003740 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003741 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3742 t->invalidate();
3743 portIds.erase(t->portId());
3744 trackMatch = true;
3745 }
3746 if (portIds.empty()) {
3747 break;
3748 }
3749 }
3750 return trackMatch;
3751}
3752
jiabinf042b9b2021-05-07 23:46:28 +00003753// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003754IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003755 audio_port_handle_t trackPortId) {
3756 for (size_t i = 0; i < mTracks.size(); i++) {
3757 if (mTracks[i]->portId() == trackPortId) {
3758 return mTracks[i].get();
3759 }
3760 }
3761 return nullptr;
3762}
3763
Andy Hungee58e4a2023-07-07 13:47:37 -07003764status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003765{
Glenn Kastend848eb42016-03-08 13:42:11 -08003766 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003767 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003768 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003769
Andy Hungd3639922022-04-28 18:00:49 -07003770 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003771 if (!audio_is_global_session(session)) {
3772 // player sessions on a spatializer output will use a dedicated input buffer and
3773 // will either output multi channel to mEffectBuffer if the track is spatilaized
3774 // or stereo to mPostSpatializerBuffer if not spatialized.
3775 uint32_t channelMask;
3776 bool isSessionSpatialized =
3777 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3778 if (isSessionSpatialized) {
3779 channelMask = mMixerChannelMask;
3780 } else {
3781 channelMask = mChannelMask;
3782 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003783 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003784 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003785 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003786 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003787 &halInBuffer);
3788 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003789
Andy Hung583043b2023-07-17 17:05:00 -07003790 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003791 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3792 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3793 &halOutBuffer);
3794 if (result != OK) return result;
3795
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003796 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003797
Mikhail Naganov022b9952017-01-04 16:36:51 -08003798 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3799 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003800 } else {
3801 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3802 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3803 // mPostSpatializerBuffer as output buffer
3804 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003805 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003806 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3807 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003808 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003809 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3810 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003811
Eric Laurentb62d0362021-10-26 17:40:18 +02003812 if (session == AUDIO_SESSION_DEVICE) {
3813 halInBuffer = halOutBuffer;
3814 }
3815 }
3816 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003817 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003818 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3819 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3820 &halInBuffer);
3821 if (result != OK) return result;
3822 halOutBuffer = halInBuffer;
3823 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3824 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003825 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003826 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003827 // Only one effect chain can be present in direct output thread and it uses
3828 // the sink buffer as input
3829 if (mType != DIRECT) {
3830 size_t numSamples = mNormalFrameCount
3831 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3832 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003833 const status_t allocateStatus =
3834 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003835 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003836 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003837 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003838
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003839 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003840 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3841 buffer, session);
3842 }
3843 }
3844 }
3845
3846 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003847 // Attach all tracks with same session ID to this chain.
3848 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003849 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003850 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003851 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3852 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003853 track->setMainBuffer(buffer);
3854 chain->incTrackCnt();
3855 }
3856 }
3857
3858 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003859 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003860 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003861 ALOGV("addEffectChain_l() activating track %p on session %d",
3862 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003863 chain->incActiveTrackCnt();
3864 }
3865 }
3866 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003867
Eric Laurentaaa44472014-09-12 17:41:50 -07003868 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003869 chain->setInBuffer(halInBuffer);
3870 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003871 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3872 // chains list in order to be processed last as it contains output device effects.
3873 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3874 // processing effects specific to an output stream before effects applied to all streams
3875 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003876 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3877 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003878 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003879 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003880 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003881 // Effect chain for other sessions are inserted at beginning of effect
3882 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003883 // sessions is not important.
3884 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003885 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3886 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003887 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003888 size_t size = mEffectChains.size();
3889 size_t i = 0;
3890 for (i = 0; i < size; i++) {
3891 if (mEffectChains[i]->sessionId() < session) {
3892 break;
3893 }
3894 }
3895 mEffectChains.insertAt(chain, i);
3896 checkSuspendOnAddEffectChain_l(chain);
3897
3898 return NO_ERROR;
3899}
3900
Andy Hungee58e4a2023-07-07 13:47:37 -07003901size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003902{
Glenn Kastend848eb42016-03-08 13:42:11 -08003903 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003904
3905 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3906
3907 for (size_t i = 0; i < mEffectChains.size(); i++) {
3908 if (chain == mEffectChains[i]) {
3909 mEffectChains.removeAt(i);
3910 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003911 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003912 if (session == track->sessionId()) {
3913 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3914 chain.get(), session);
3915 chain->decActiveTrackCnt();
3916 }
3917 }
3918
3919 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003920 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003921 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003922 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003923 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003924 chain->decTrackCnt();
3925 }
3926 }
3927 break;
3928 }
3929 }
3930 return mEffectChains.size();
3931}
3932
Andy Hungee58e4a2023-07-07 13:47:37 -07003933status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003934 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003935{
Andy Hung972bec12023-08-31 16:13:39 -07003936 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003937 return attachAuxEffect_l(track, EffectId);
3938}
3939
Andy Hungee58e4a2023-07-07 13:47:37 -07003940status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003941 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003942{
3943 status_t status = NO_ERROR;
3944
3945 if (EffectId == 0) {
3946 track->setAuxBuffer(0, NULL);
3947 } else {
3948 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003949 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003950 if (effect != 0) {
3951 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3952 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3953 } else {
3954 status = INVALID_OPERATION;
3955 }
3956 } else {
3957 status = BAD_VALUE;
3958 }
3959 }
3960 return status;
3961}
3962
Andy Hungee58e4a2023-07-07 13:47:37 -07003963void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003964{
3965 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003966 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003967 if (track->auxEffectId() == effectId) {
3968 attachAuxEffect_l(track, 0);
3969 }
3970 }
3971}
3972
Andy Hungee58e4a2023-07-07 13:47:37 -07003973bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003974NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003975{
Andy Hung78d8d952023-05-30 18:10:23 -07003976 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003977
Andy Hung077d62e2023-10-03 10:49:34 -07003978 if (mType == SPATIALIZER) {
3979 const pid_t tid = getTid();
3980 if (tid == -1) { // odd: we are here, we must be a running thread.
3981 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3982 } else {
Andy Hung639dbc92023-11-28 18:21:55 +00003983 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3984 if (priorityBoost > 0) {
3985 stream()->setHalThreadPriority(priorityBoost);
3986 }
Andy Hung077d62e2023-10-03 10:49:34 -07003987 }
Pattara Teerapong9a332c52024-01-26 08:18:05 +00003988 } else if (property_get_bool("ro.boot.container", false /* default_value */)) {
3989 // In ARC experiments (b/73091832), the latency under using CFS scheduler with any priority
3990 // is not enough for PlaybackThread to process audio data in time. We request the lowest
3991 // real-time priority, SCHED_FIFO=1, for PlaybackThread in ARC. ro.boot.container is true
3992 // only on ARC.
3993 const pid_t tid = getTid();
3994 if (tid == -1) {
3995 ALOGW("%s: Cannot update PlaybackThread priority for ARC, no tid", __func__);
3996 } else {
3997 const status_t status = requestPriority(getpid(),
3998 tid,
3999 kPriorityPlaybackThreadArc,
4000 false /* isForApp */,
4001 true /* asynchronous */);
4002 if (status != OK) {
4003 ALOGW("%s: Cannot update PlaybackThread priority for ARC, status %d", __func__,
4004 status);
4005 } else {
4006 stream()->setHalThreadPriority(kPriorityPlaybackThreadArc);
4007 }
4008 }
Andy Hung077d62e2023-10-03 10:49:34 -07004009 }
4010
Andy Hung8d31fd22023-06-26 19:20:57 -07004011 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08004012
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004013 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08004014 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08004015
4016 // MIXER
4017 nsecs_t lastWarning = 0;
4018
4019 // DUPLICATING
4020 // FIXME could this be made local to while loop?
4021 writeFrames = 0;
4022
4023 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004024 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004025
Andy Hungd3639922022-04-28 18:00:49 -07004026 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004027 sleepTimeShift = 0;
4028 }
4029
4030 CpuStats cpuStats;
4031 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
4032
4033 acquireWakeLock();
4034
Glenn Kasteneef598c2017-04-03 14:41:13 -07004035 // mNBLogWriter logging APIs can only be called by a single thread, typically the
4036 // thread associated with this PlaybackThread.
4037 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
4038 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004039 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
4040 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07004041 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08004042 const char *logString = NULL;
4043
rago1bb90822017-05-02 18:31:48 -07004044 // Estimated time for next buffer to be written to hal. This is used only on
4045 // suspended mode (for now) to help schedule the wait time until next iteration.
4046 nsecs_t timeLoopNextNs = 0;
4047
Eric Laurent664539d2013-09-23 18:24:31 -07004048 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07004049
Andy Hung2dbffc22018-08-08 18:50:41 -07004050 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07004051
Eric Laurentb3f315a2021-07-13 15:09:05 +02004052 sendCheckOutputStageEffectsEvent();
4053
Andy Hung446f4df2019-02-21 12:26:41 -08004054 // loopCount is used for statistics and diagnostics.
4055 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08004056 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004057 // Log merge requests are performed during AudioFlinger binder transactions, but
4058 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07004059 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08004060
Eric Laurent81784c32012-11-19 14:55:58 -08004061 cpuStats.sample(myName);
4062
Andy Hung116bc262023-06-20 18:56:17 -07004063 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07004064 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02004065 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07004066 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08004067
Andy Hung2dbffc22018-08-08 18:50:41 -07004068 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
4069 //
Andy Hungc5007f82023-08-29 14:26:09 -07004070 // Note: we access outDeviceTypes() outside of mutex().
Andy Hungab65b182023-09-06 19:41:47 -07004071 if (isMsdDevice() && outDeviceTypes_l().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07004072 // Here, we try for the AF lock, but do not block on it as the latency
4073 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07004074 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07004075 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07004076 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07004077 status_t status = INVALID_OPERATION;
4078 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07004079 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07004080 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004081 && swPatches.size() > 0) {
4082 status = swPatches[0].getLatencyMs_l(&latencyMs);
4083 downstreamPatchHandle = swPatches[0].getPatchHandle();
4084 }
4085 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004086 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004087 lastDownstreamPatchHandle = downstreamPatchHandle;
4088 }
4089 if (status == OK) {
4090 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004091 // latency of 5 seconds).
4092 const double minLatency = 0., maxLatency = 5000.;
4093 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004094 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004095 } else {
4096 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07004097 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004098 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004099 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004100 }
Andy Hung583043b2023-07-17 17:05:00 -07004101 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004102 }
4103 } else {
4104 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4105 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004106 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004107 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4108 }
4109 }
4110
Eric Laurentb3f315a2021-07-13 15:09:05 +02004111 if (mCheckOutputStageEffects.exchange(false)) {
4112 checkOutputStageEffects();
4113 }
4114
Vlad Popa7e81cea2023-01-19 16:34:16 +01004115 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004116 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004117
Andy Hungc5007f82023-08-29 14:26:09 -07004118 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004119
Eric Laurent021cf962014-05-13 10:18:14 -07004120 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004121 if (mCheckOutputStageEffects.load()) {
4122 continue;
4123 }
Eric Laurent10351942014-05-08 18:49:52 -07004124
Andy Hungc5007f82023-08-29 14:26:09 -07004125 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004126 if (logString != NULL) {
4127 mNBLogWriter->logTimestamp();
4128 mNBLogWriter->log(logString);
4129 logString = NULL;
4130 }
4131
Dean Wheatley12473e92021-03-18 23:00:55 +11004132 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004133
Eric Laurent81784c32012-11-19 14:55:58 -08004134 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004135 if (mSignalPending) {
4136 // A signal was raised while we were unlocked
4137 mSignalPending = false;
4138 } else if (waitingAsyncCallback_l()) {
4139 if (exitPending()) {
4140 break;
4141 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004142 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004143 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004144 releaseWakeLock_l();
4145 released = true;
4146 }
Andy Hung10cbff12017-02-21 17:30:14 -08004147
4148 const int64_t waitNs = computeWaitTimeNs_l();
4149 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004150 std::cv_status cvstatus =
4151 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4152 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004153 mSignalPending = true; // if timeout recheck everything
4154 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004155 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004156 if (released) {
4157 acquireWakeLock_l();
4158 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004159 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4160 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004161
4162 continue;
4163 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004164 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004165 isSuspended()) {
4166 // put audio hardware into standby after short delay
4167 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004168
4169 threadLoop_standby();
4170
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004171 // This is where we go into standby
4172 if (!mStandby) {
4173 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004174 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004175 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004176 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004177 }
Andy Hungd0979812019-02-21 15:51:44 -08004178 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004179 }
4180
Eric Tan39ec8d62018-07-24 09:49:29 -07004181 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004182 // we're about to wait, flush the binder command buffer
4183 IPCThreadState::self()->flushCommands();
4184
4185 clearOutputTracks();
4186
4187 if (exitPending()) {
4188 break;
4189 }
4190
4191 releaseWakeLock_l();
4192 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004193 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004194 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004195 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004196 acquireWakeLock_l();
4197
4198 mMixerStatus = MIXER_IDLE;
4199 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4200 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004201 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004202 checkSilentMode_l();
4203
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004204 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4205 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004206 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004207 sleepTimeShift = 0;
4208 }
4209
4210 continue;
4211 }
4212 }
Eric Laurent81784c32012-11-19 14:55:58 -08004213 // mMixerStatusIgnoringFastTracks is also updated internally
4214 mMixerStatus = prepareTracks_l(&tracksToRemove);
4215
Andy Hungab65b182023-09-06 19:41:47 -07004216 mActiveTracks.updatePowerState_l(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004217
Vlad Popa7e81cea2023-01-19 16:34:16 +01004218 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004219
Andy Hungf302e812024-01-26 11:55:15 -08004220 // Acquire a local copy of active tracks with lock (release w/o lock).
4221 //
4222 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4223 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4224 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4225 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
4226
4227 setHalLatencyMode_l();
4228
4229 // updateTeePatches_l will acquire the ThreadBase_Mutex of other threads,
4230 // so this is done before we lock our effect chains.
4231 for (const auto& track : mActiveTracks) {
4232 track->updateTeePatches_l();
4233 }
4234
4235 // signal actual start of output stream when the render position reported by
4236 // the kernel starts moving.
4237 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4238 && (mKernelPositionOnStandby
4239 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
4240 mHalStarted = true;
4241 mWaitHalStartCV.notify_all();
4242 }
4243
Eric Laurent81784c32012-11-19 14:55:58 -08004244 // prevent any changes in effect chain list and in each effect chain
4245 // during mixing and effect process as the audio buffers could be deleted
4246 // or modified if an effect is created or deleted
4247 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004248
4249 // Determine which session to pick up haptic data.
4250 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004251 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004252 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004253 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004254 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004255 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004256 if (effectChain != nullptr
4257 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004258 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004259 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004260 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004261 break;
4262 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004263 if (activeHapticSessionId == AUDIO_SESSION_NONE
4264 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004265 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004266 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004267 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004268 }
4269 }
4270 }
Andy Hungc5007f82023-08-29 14:26:09 -07004271 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004272
Eric Laurentbfb1b832013-01-07 09:53:42 -08004273 if (mBytesRemaining == 0) {
4274 mCurrentWriteLength = 0;
4275 if (mMixerStatus == MIXER_TRACKS_READY) {
4276 // threadLoop_mix() sets mCurrentWriteLength
4277 threadLoop_mix();
4278 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4279 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004280 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004281 // must be written to HAL
4282 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004283 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004284 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004285
4286 // Tally underrun frames as we are inserting 0s here.
4287 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004288 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004289 && !track->isStopped()
4290 && !track->isPaused()
4291 && !track->isTerminated()) {
4292 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4293 __func__, track->id(), track->getTrackStateAsString(),
4294 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004295 track->audioTrackServerProxy()->tallyUnderrunFrames(
4296 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004297 }
4298 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004299 }
4300 }
Andy Hung98ef9782014-03-04 14:46:50 -08004301 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004302 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004303 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004304 // or mSinkBuffer (if there are no effects and there is no data already copied to
4305 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004306 //
4307 // This is done pre-effects computation; if effects change to
4308 // support higher precision, this needs to move.
4309 //
4310 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004311 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004312 uint32_t mixerChannelCount = mEffectBufferValid ?
4313 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004314 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004315 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4316 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4317
David Li88ee0902022-06-22 10:01:21 +08004318 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4319 // do these processes after effects are applied.
4320 if (!mEffectBufferValid) {
4321 // mono blend occurs for mixer threads only (not direct or offloaded)
4322 // and is handled here if we're going directly to the sink.
4323 if (requireMonoBlend()) {
4324 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4325 mNormalFrameCount, true /*limit*/);
4326 }
Andy Hung2ddee192015-12-18 17:34:44 -08004327
David Li88ee0902022-06-22 10:01:21 +08004328 if (!hasFastMixer()) {
4329 // Balance must take effect after mono conversion.
4330 // We do it here if there is no FastMixer.
4331 // mBalance detects zero balance within the class for speed
4332 // (not needed here).
4333 mBalance.setBalance(mMasterBalance.load());
4334 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4335 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004336 }
4337
Andy Hung98ef9782014-03-04 14:46:50 -08004338 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004339 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004340
4341 // If we're going directly to the sink and there are haptic channels,
4342 // we should adjust channels as the sample data is partially interleaved
4343 // in this case.
4344 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4345 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4346 mChannelCount + mHapticChannelCount,
4347 audio_bytes_per_sample(format),
4348 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4349 }
Andy Hung98ef9782014-03-04 14:46:50 -08004350 }
4351
Eric Laurentbfb1b832013-01-07 09:53:42 -08004352 mBytesRemaining = mCurrentWriteLength;
4353 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004354 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4355 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4356 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4357 mBytesWritten += mBytesRemaining;
4358 mFramesWritten += framesRemaining;
4359 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004360 mBytesRemaining = 0;
4361 }
Eric Laurent81784c32012-11-19 14:55:58 -08004362
Eric Laurentbfb1b832013-01-07 09:53:42 -08004363 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004364 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004365 for (size_t i = 0; i < effectChains.size(); i ++) {
4366 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004367 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004368 if (activeHapticSessionId != AUDIO_SESSION_NONE
4369 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004370 // Haptic data is active in this case, copy it directly from
4371 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004372 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4373 audio_channel_count_from_out_mask(mMixerChannelMask) :
4374 mChannelCount;
4375 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4376 hapticSessionChannelCount = mChannelCount;
4377 }
4378
jiabin47affe52019-04-04 18:02:07 -07004379 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004380 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004381 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004382 memcpy_by_audio_format(
4383 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004384 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004385 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004386 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004387 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004388 }
Eric Laurent81784c32012-11-19 14:55:58 -08004389 }
4390 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004391 // Process effect chains for offloaded thread even if no audio
4392 // was read from audio track: process only updates effect state
4393 // and thus does have to be synchronized with audio writes but may have
4394 // to be called while waiting for async write callback
4395 if (mType == OFFLOAD) {
4396 for (size_t i = 0; i < effectChains.size(); i ++) {
4397 effectChains[i]->process_l();
4398 }
4399 }
Eric Laurent81784c32012-11-19 14:55:58 -08004400
Andy Hung98ef9782014-03-04 14:46:50 -08004401 // Only if the Effects buffer is enabled and there is data in the
4402 // Effects buffer (buffer valid), we need to
4403 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004404 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004405 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004406 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004407 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004408 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004409 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004410 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004411 }
4412
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004413 if (!hasFastMixer()) {
4414 // Balance must take effect after mono conversion.
4415 // We do it here if there is no FastMixer.
4416 // mBalance detects zero balance within the class for speed (not needed here).
4417 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004418 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004419 }
4420
Eric Laurentb62d0362021-10-26 17:40:18 +02004421 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4422 // mPostSpatializerBuffer if the haptics track is spatialized.
4423 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4424 // For other thread types, the haptics channels are already in mEffectBuffer.
4425 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4426 const size_t srcBufferSize = mNormalFrameCount *
4427 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4428 mEffectBufferFormat);
4429 const size_t dstBufferSize = mNormalFrameCount
4430 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4431
4432 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4433 mEffectBufferFormat,
4434 (uint8_t*)mEffectBuffer + srcBufferSize,
4435 mEffectBufferFormat,
4436 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004437 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004438 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4439 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4440 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4441 // Clamp PCM float values more than this distance from 0 to insulate
4442 // a HAL which doesn't handle NaN correctly.
4443 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4444 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4445 static_cast<const float*>(effectBuffer),
4446 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4447 } else {
4448 memcpy_by_audio_format(mSinkBuffer, mFormat,
4449 effectBuffer, mEffectBufferFormat, framesToCopy);
4450 }
jiabin245cdd92018-12-07 17:55:15 -08004451 // The sample data is partially interleaved when haptic channels exist,
4452 // we need to adjust channels here.
4453 if (mHapticChannelCount > 0) {
4454 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4455 mChannelCount + mHapticChannelCount,
4456 audio_bytes_per_sample(mFormat),
4457 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4458 }
Andy Hung98ef9782014-03-04 14:46:50 -08004459 }
4460
Eric Laurent81784c32012-11-19 14:55:58 -08004461 // enable changes in effect chain
4462 unlockEffectChains(effectChains);
4463
Vlad Popafce10862023-02-03 10:37:07 +01004464 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004465 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004466 metadataUpdate.playbackMetadataUpdate);
4467 }
4468
Eric Laurentbfb1b832013-01-07 09:53:42 -08004469 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004470 // mSleepTimeUs == 0 means we must write to audio hardware
4471 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004472 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004473 // writePeriodNs is updated >= 0 when ret > 0.
4474 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004475 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004476 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004477 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004478 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004479 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004480 if (ret < 0) {
4481 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004482 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004483 mBytesWritten += ret;
4484 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004485 const int64_t frames = ret / mFrameSize;
4486 mFramesWritten += frames;
4487
4488 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4489 // process information relating to write time.
4490 if (audio_has_proportional_frames(mFormat)) {
4491 // we are in a continuous mixing cycle
4492 if (mMixerStatus == MIXER_TRACKS_READY &&
4493 loopCount == lastLoopCountWritten + 1) {
4494
4495 const double jitterMs =
4496 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4497 {frames, writePeriodNs},
4498 {0, 0} /* lastTimestamp */, mSampleRate);
4499 const double processMs =
4500 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4501
Andy Hung972bec12023-08-31 16:13:39 -07004502 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004503 mIoJitterMs.add(jitterMs);
4504 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004505
4506 if (mPipeSink.get() != nullptr) {
4507 // Using the Monopipe availableToWrite, we estimate the current
4508 // buffer size.
4509 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4510 const ssize_t
4511 availableToWrite = mPipeSink->availableToWrite();
4512 const size_t pipeFrames = monoPipe->maxFrames();
4513 const size_t
4514 remainingFrames = pipeFrames - max(availableToWrite, 0);
4515 mMonopipePipeDepthStats.add(remainingFrames);
4516 }
Andy Hung446f4df2019-02-21 12:26:41 -08004517 }
4518
4519 // write blocked detection
4520 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004521 if ((mType == MIXER || mType == SPATIALIZER)
4522 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004523 mNumDelayedWrites++;
4524 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4525 ATRACE_NAME("underrun");
4526 ALOGW("write blocked for %lld msecs, "
4527 "%d delayed writes, thread %d",
4528 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4529 mNumDelayedWrites, mId);
4530 lastWarning = lastIoEndNs;
4531 }
4532 }
4533 }
4534 // update timing info.
4535 mLastIoBeginNs = lastIoBeginNs;
4536 mLastIoEndNs = lastIoEndNs;
4537 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004538 }
4539 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4540 (mMixerStatus == MIXER_DRAIN_ALL)) {
4541 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004542 }
Andy Hungd3639922022-04-28 18:00:49 -07004543 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004544
4545 if (mThreadThrottle
4546 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004547 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004548 // Limit MixerThread data processing to no more than twice the
4549 // expected processing rate.
4550 //
4551 // This helps prevent underruns with NuPlayer and other applications
4552 // which may set up buffers that are close to the minimum size, or use
4553 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4554 //
4555 // The throttle smooths out sudden large data drains from the device,
4556 // e.g. when it comes out of standby, which often causes problems with
4557 // (1) mixer threads without a fast mixer (which has its own warm-up)
4558 // (2) minimum buffer sized tracks (even if the track is full,
4559 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004560 //
4561 // Total time spent in last processing cycle equals time spent in
4562 // 1. threadLoop_write, as well as time spent in
4563 // 2. threadLoop_mix (significant for heavy mixing, especially
4564 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004565
Andy Hung446f4df2019-02-21 12:26:41 -08004566 // it's OK if deltaMs is an overestimate.
4567
4568 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004569
Ivan Lozanoea04d392017-11-07 14:37:07 -08004570 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004571 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004572 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004573
Andy Hung08fb1742015-05-31 23:22:10 -07004574 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004575 // notify of throttle start on verbose log
4576 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4577 "mixer(%p) throttle begin:"
4578 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004579 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004580 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004581 // Throttle must be attributed to the previous mixer loop's write time
4582 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004583 // This also ensures proper timing statistics.
4584 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004585 } else {
4586 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4587 if (diff > 0) {
4588 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004589 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004590 ALOGD_IF(!isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004591 outDeviceTypes_l(), audio_is_a2dp_out_device) &&
jiabinc52b1ff2019-10-31 17:20:42 -07004592 !isSingleDeviceType(
Andy Hungab65b182023-09-06 19:41:47 -07004593 outDeviceTypes_l(),
4594 audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004595 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004596 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4597 }
Andy Hung08fb1742015-05-31 23:22:10 -07004598 }
4599 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004600 }
Eric Laurent81784c32012-11-19 14:55:58 -08004601
Eric Laurentbfb1b832013-01-07 09:53:42 -08004602 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004603 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004604 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004605 // suspended requires accurate metering of sleep time.
4606 if (isSuspended()) {
4607 // advance by expected sleepTime
4608 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4609 const nsecs_t nowNs = systemTime();
4610
4611 // compute expected next time vs current time.
4612 // (negative deltas are treated as delays).
4613 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4614 if (deltaNs < -kMaxNextBufferDelayNs) {
4615 // Delays longer than the max allowed trigger a reset.
4616 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4617 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4618 timeLoopNextNs = nowNs + deltaNs;
4619 } else if (deltaNs < 0) {
4620 // Delays within the max delay allowed: zero the delta/sleepTime
4621 // to help the system catch up in the next iteration(s)
4622 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4623 deltaNs = 0;
4624 }
4625 // update sleep time (which is >= 0)
4626 mSleepTimeUs = deltaNs / 1000;
4627 }
Eric Laurente93cc032016-05-05 10:15:10 -07004628 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004629 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004630 }
Glenn Kastene7754022014-10-31 12:11:26 -07004631 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004632 }
Eric Laurent81784c32012-11-19 14:55:58 -08004633 }
4634
4635 // Finally let go of removed track(s), without the lock held
4636 // since we can't guarantee the destructors won't acquire that
4637 // same lock. This will also mutate and push a new fast mixer state.
4638 threadLoop_removeTracks(tracksToRemove);
4639 tracksToRemove.clear();
4640
4641 // FIXME I don't understand the need for this here;
4642 // it was in the original code but maybe the
4643 // assignment in saveOutputTracks() makes this unnecessary?
4644 clearOutputTracks();
4645
4646 // Effect chains will be actually deleted here if they were removed from
4647 // mEffectChains list during mixing or effects processing
4648 effectChains.clear();
4649
4650 // FIXME Note that the above .clear() is no longer necessary since effectChains
4651 // is now local to this block, but will keep it for now (at least until merge done).
Andy Hung56ce2ed2024-06-12 16:03:16 -07004652
4653 mThreadloopExecutor.process();
Eric Laurent81784c32012-11-19 14:55:58 -08004654 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07004655 mThreadloopExecutor.process(); // process any remaining deferred actions.
4656 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08004657
Eric Laurentbfb1b832013-01-07 09:53:42 -08004658 threadLoop_exit();
4659
Eric Laurentcf817a22014-08-04 20:36:31 -07004660 if (!mStandby) {
4661 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004662 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004663 }
4664
4665 releaseWakeLock();
4666
4667 ALOGV("Thread %p type %d exiting", this, mType);
4668 return false;
4669}
4670
Andy Hungee58e4a2023-07-07 13:47:37 -07004671void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004672{
Dean Wheatley12473e92021-03-18 23:00:55 +11004673 if (mStandby) {
4674 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4675 return;
4676 } else if (mHwPaused) {
4677 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4678 return;
4679 }
4680
4681 // Gather the framesReleased counters for all active tracks,
4682 // and associate with the sink frames written out. We need
4683 // this to convert the sink timestamp to the track timestamp.
4684 bool kernelLocationUpdate = false;
4685 ExtendedTimestamp timestamp; // use private copy to fetch
4686
4687 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4688 // HAL may be draining some small duration buffered data for fade out.
4689 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4690 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4691 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4692 mSampleRate);
4693
Andy Hungab65b182023-09-06 19:41:47 -07004694 if (isTimestampCorrectionEnabled_l()) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004695 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4696 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4697 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4698 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4699 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4700 = correctedTimestamp.mFrames;
4701 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4702 = correctedTimestamp.mTimeNs;
4703 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4704 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4705 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4706
4707 // Note: Downstream latency only added if timestamp correction enabled.
4708 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4709 const int64_t newPosition =
4710 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4711 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4712 // prevent retrograde
4713 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4714 newPosition,
4715 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4716 - mSuspendedFrames));
4717 }
4718 }
4719
4720 // We always fetch the timestamp here because often the downstream
4721 // sink will block while writing.
4722
4723 // We keep track of the last valid kernel position in case we are in underrun
4724 // and the normal mixer period is the same as the fast mixer period, or there
4725 // is some error from the HAL.
4726 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4727 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4728 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4729 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4730 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4731
4732 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4733 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4734 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4735 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4736 }
4737
4738 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4739 kernelLocationUpdate = true;
4740 } else {
4741 ALOGVV("getTimestamp error - no valid kernel position");
4742 }
4743
4744 // copy over kernel info
4745 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4746 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4747 + mSuspendedFrames; // add frames discarded when suspended
4748 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4749 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4750 } else {
4751 mTimestampVerifier.error();
4752 }
4753
4754 // mFramesWritten for non-offloaded tracks are contiguous
4755 // even after standby() is called. This is useful for the track frame
4756 // to sink frame mapping.
4757 bool serverLocationUpdate = false;
4758 if (mFramesWritten != mLastFramesWritten) {
4759 serverLocationUpdate = true;
4760 mLastFramesWritten = mFramesWritten;
4761 }
4762 // Only update timestamps if there is a meaningful change.
4763 // Either the kernel timestamp must be valid or we have written something.
4764 if (kernelLocationUpdate || serverLocationUpdate) {
4765 if (serverLocationUpdate) {
4766 // use the time before we called the HAL write - it is a bit more accurate
4767 // to when the server last read data than the current time here.
4768 //
4769 // If we haven't written anything, mLastIoBeginNs will be -1
4770 // and we use systemTime().
4771 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4772 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
Andy Hung8d672e02023-09-15 18:19:28 -07004773 ? systemTime() : (int64_t)mLastIoBeginNs;
Dean Wheatley12473e92021-03-18 23:00:55 +11004774 }
4775
Andy Hung8d31fd22023-06-26 19:20:57 -07004776 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004777 if (!t->isFastTrack()) {
4778 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004779 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004780 mFramesWritten,
4781 mSampleRate,
4782 mTimestamp);
4783 }
4784 }
4785 }
4786
4787 if (audio_has_proportional_frames(mFormat)) {
4788 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4789 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4790 mLatencyMs.add(latencyMs);
4791 }
4792 }
4793#if 0
4794 // logFormat example
4795 if (z % 100 == 0) {
4796 timespec ts;
4797 clock_gettime(CLOCK_MONOTONIC, &ts);
4798 LOGT("This is an integer %d, this is a float %f, this is my "
4799 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4800 LOGT("A deceptive null-terminated string %\0");
4801 }
4802 ++z;
4803#endif
4804}
4805
Andy Hungc5007f82023-08-29 14:26:09 -07004806// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004807void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004808NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004809{
Andy Hung6c498e92023-12-05 17:28:17 -08004810 if (tracksToRemove.empty()) return;
4811
4812 // Block all incoming TrackHandle requests until we are finished with the release.
4813 setThreadBusy_l(true);
4814
Andy Hungfe726a62018-09-27 15:17:25 -07004815 for (const auto& track : tracksToRemove) {
Andy Hungfe726a62018-09-27 15:17:25 -07004816 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004817 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004818 if (chain != 0) {
4819 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4820 __func__, track->id(), chain.get(), track->sessionId());
4821 chain->decActiveTrackCnt();
4822 }
Andy Hung6c498e92023-12-05 17:28:17 -08004823
Andy Hungfe726a62018-09-27 15:17:25 -07004824 // If an external client track, inform APM we're no longer active, and remove if needed.
Andy Hung6c498e92023-12-05 17:28:17 -08004825 // Since the track is active, we do it here instead of TrackBase::destroy().
Andy Hungfe726a62018-09-27 15:17:25 -07004826 if (track->isExternalTrack()) {
Andy Hung6c498e92023-12-05 17:28:17 -08004827 mutex().unlock();
Andy Hungfe726a62018-09-27 15:17:25 -07004828 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004829 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004830 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004831 }
Andy Hung6c498e92023-12-05 17:28:17 -08004832 mutex().lock();
Andy Hungfe726a62018-09-27 15:17:25 -07004833 }
jiabineb3bda02020-06-30 14:07:03 -07004834 if (mHapticChannelCount > 0 &&
4835 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
Shunkai Yao29d10572024-03-19 04:31:47 +00004836 || (chain != nullptr && chain->containsHapticGeneratingEffect()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004837 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004838 // Unlock due to VibratorService will lock for this call and will
4839 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004840 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004841 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004842
4843 // When the track is stop, set the haptic intensity as MUTE
4844 // for the HapticGenerator effect.
4845 if (chain != nullptr) {
Ahmad Khalil229466a2024-02-05 12:15:30 +00004846 chain->setHapticScale_l(track->id(), os::HapticScale::mute());
jiabine70bc7f2020-06-30 22:07:55 -07004847 }
jiabin245cdd92018-12-07 17:55:15 -08004848 }
Andy Hung6c498e92023-12-05 17:28:17 -08004849
4850 // Under lock, the track is removed from the active tracks list.
4851 //
4852 // Once the track is no longer active, the TrackHandle may directly
4853 // modify it as the threadLoop() is no longer responsible for its maintenance.
4854 // Do not modify the track from threadLoop after the mutex is unlocked
4855 // if it is not active.
4856 mActiveTracks.remove(track);
4857
4858 if (track->isTerminated()) {
4859 // remove from our tracks vector
4860 removeTrack_l(track);
4861 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004862 }
Andy Hung6c498e92023-12-05 17:28:17 -08004863
4864 // Allow incoming TrackHandle requests. We still hold the mutex,
4865 // so pending TrackHandle requests will occur after we unlock it.
4866 setThreadBusy_l(false);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004867}
Eric Laurent81784c32012-11-19 14:55:58 -08004868
Andy Hungee58e4a2023-07-07 13:47:37 -07004869status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004870{
4871 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004872 ExtendedTimestamp ets;
4873 status_t status = mNormalSink->getTimestamp(ets);
4874 if (status == NO_ERROR) {
4875 status = ets.getBestTimestamp(&timestamp);
4876 }
4877 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004878 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004879 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004880 collectTimestamps_l();
4881 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4882 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004883 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004884 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4885 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4886 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4887 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4888 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004889 }
4890 return INVALID_OPERATION;
4891}
Eric Laurent1c333e22014-05-20 10:48:17 -07004892
Eric Laurenteab90452019-06-24 15:17:46 -07004893// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4894// still applied by the mixer.
4895// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4896// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4897// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004898status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004899{
4900 status_t result = NO_ERROR;
4901 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4902 if (*volume != mLeftVolFloat) {
4903 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004904 // HAL can return INVALID_OPERATION if operation is not supported.
4905 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004906 "Error when setting output stream volume: %d", result);
4907 if (result == NO_ERROR) {
4908 mLeftVolFloat = *volume;
4909 }
4910 }
4911 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4912 // remove stream volume contribution from software volume.
4913 if (mLeftVolFloat == *volume) {
4914 *volume = 1.0f;
4915 }
4916 }
4917 return result;
4918}
4919
Andy Hungee58e4a2023-07-07 13:47:37 -07004920status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004921 audio_patch_handle_t *handle)
4922{
Andy Hungf60abce2016-08-26 11:37:54 -07004923 status_t status;
4924 if (property_get_bool("af.patch_park", false /* default_value */)) {
4925 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4926 // or if HAL does not properly lock against access.
4927 AutoPark<FastMixer> park(mFastMixer);
4928 status = PlaybackThread::createAudioPatch_l(patch, handle);
4929 } else {
4930 status = PlaybackThread::createAudioPatch_l(patch, handle);
4931 }
Eric Laurentb0463942022-12-20 16:31:10 +01004932
4933 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004934 return status;
4935}
4936
Andy Hungee58e4a2023-07-07 13:47:37 -07004937status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 audio_patch_handle_t *handle)
4939{
4940 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004941
4942 // store new device and send to effects
4943 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004944 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004945 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004946 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4947 && !mOutput->audioHwDev->supportsAudioPatches(),
4948 "Enumerated device type(%#x) must not be used "
4949 "as it does not support audio patches",
4950 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004951 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004952 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4953 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004954 }
4955
François Gaffie0c280aa2018-07-25 10:02:15 +02004956 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004957#ifdef ADD_BATTERY_DATA
4958 // when changing the audio output device, call addBatteryData to notify
4959 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004960 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004961 uint32_t params = 0;
4962 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004963 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004964 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004965 }
4966
Eric Laurent054d9d32015-04-24 08:48:48 -07004967 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004968 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004969 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4970 }
4971
4972 if (params != 0) {
4973 addBatteryData(params);
4974 }
4975 }
4976#endif
4977
4978 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004979 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004980 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004981
jiabinc52b1ff2019-10-31 17:20:42 -07004982 // mPatch.num_sinks is not set when the thread is created so that
4983 // the first patch creation triggers an ioConfigChanged callback
4984 bool configChanged = (mPatch.num_sinks == 0) ||
4985 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004986 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004987 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004988 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004989
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004990 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004991 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4992 status = hwDevice->createAudioPatch(patch->num_sources,
4993 patch->sources,
4994 patch->num_sinks,
4995 patch->sinks,
4996 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004997 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004998 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004999 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07005000 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07005001 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07005002
5003 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07005004 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07005005 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07005006 // also dispatch to active AudioTracks for MediaMetrics
5007 for (const auto &track : mActiveTracks) {
5008 track->logEndInterval();
5009 track->logBeginInterval(patchSinksAsString);
5010 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005011
Eric Laurente8726fe2015-06-26 09:39:24 -07005012 if (configChanged) {
5013 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
5014 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01005015 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02005016 mActiveTracks.setHasChanged();
5017
Eric Laurent1c333e22014-05-20 10:48:17 -07005018 return status;
5019}
5020
Andy Hungee58e4a2023-07-07 13:47:37 -07005021status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07005022{
Andy Hungf60abce2016-08-26 11:37:54 -07005023 status_t status;
5024 if (property_get_bool("af.patch_park", false /* default_value */)) {
5025 // Park FastMixer to avoid potential DOS issues with writing to the HAL
5026 // or if HAL does not properly lock against access.
5027 AutoPark<FastMixer> park(mFastMixer);
5028 status = PlaybackThread::releaseAudioPatch_l(handle);
5029 } else {
5030 status = PlaybackThread::releaseAudioPatch_l(handle);
5031 }
Eric Laurent054d9d32015-04-24 08:48:48 -07005032 return status;
5033}
5034
Andy Hungee58e4a2023-07-07 13:47:37 -07005035status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005036{
5037 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07005038
jiabinc52b1ff2019-10-31 17:20:42 -07005039 mPatch = audio_patch{};
5040 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07005041
Mikhail Naganov9ee05402016-10-13 15:58:17 -07005042 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07005043 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
5044 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005045 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08005046 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07005047 }
Eric Laurentdda206a2022-07-08 17:28:35 +02005048 // Force meteadata update after a route change
5049 mActiveTracks.setHasChanged();
5050
Eric Laurent1c333e22014-05-20 10:48:17 -07005051 return status;
5052}
5053
Andy Hungee58e4a2023-07-07 13:47:37 -07005054void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005055{
Andy Hung972bec12023-08-31 16:13:39 -07005056 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005057 mTracks.add(track);
5058}
5059
Andy Hungee58e4a2023-07-07 13:47:37 -07005060void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07005061{
Andy Hung972bec12023-08-31 16:13:39 -07005062 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07005063 destroyTrack_l(track);
5064}
5065
Andy Hungee58e4a2023-07-07 13:47:37 -07005066void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07005067{
Mikhail Naganovdc769682018-05-04 15:34:08 -07005068 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07005069 config->role = AUDIO_PORT_ROLE_SOURCE;
5070 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
5071 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07005072 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
5073 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
5074 config->flags.output = mOutput->flags;
5075 }
Eric Laurent83b88082014-06-20 18:31:16 -07005076}
5077
Eric Laurent81784c32012-11-19 14:55:58 -08005078// ----------------------------------------------------------------------------
5079
Andy Hungee58e4a2023-07-07 13:47:37 -07005080/* static */
5081sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07005082 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07005083 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07005084 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07005085}
5086
Andy Hung583043b2023-07-17 17:05:00 -07005087MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005088 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07005089 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08005090 // mAudioMixer below
5091 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01005092 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005093 mFastMixerFutex(0),
5094 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08005095 // mOutputSink below
5096 // mPipeSink below
5097 // mNormalSink below
5098{
Andy Hung583043b2023-07-17 17:05:00 -07005099 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07005100 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005101 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07005102 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08005103 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
5104 mNormalFrameCount);
5105 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5106
Andy Hungfbfc3952015-01-15 13:33:51 -08005107 if (type == DUPLICATING) {
5108 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5109 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5110 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5111 return;
5112 }
Eric Laurent81784c32012-11-19 14:55:58 -08005113 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005114 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005115 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005116 const NBAIO_Format offers[1] = {Format_from_SR_C(
5117 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005118#if !LOG_NDEBUG
5119 ssize_t index =
5120#else
5121 (void)
5122#endif
5123 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005124 ALOG_ASSERT(index == 0);
5125
5126 // initialize fast mixer depending on configuration
5127 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005128 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005129 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005130 } else {
5131 switch (kUseFastMixer) {
5132 case FastMixer_Never:
5133 initFastMixer = false;
5134 break;
5135 case FastMixer_Always:
5136 initFastMixer = true;
5137 break;
5138 case FastMixer_Static:
5139 case FastMixer_Dynamic:
5140 initFastMixer = mFrameCount < mNormalFrameCount;
5141 break;
5142 }
5143 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5144 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5145 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005146 }
5147 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005148 audio_format_t fastMixerFormat;
5149 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5150 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5151 } else {
5152 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5153 }
5154 if (mFormat != fastMixerFormat) {
5155 // change our Sink format to accept our intermediate precision
5156 mFormat = fastMixerFormat;
5157 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005158 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005159 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5160 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5161 }
Eric Laurent81784c32012-11-19 14:55:58 -08005162
5163 // create a MonoPipe to connect our submix to FastMixer
5164 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005165
Andy Hung1258c1a2014-05-23 21:22:17 -07005166 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005167 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005168 format.mFormat = fastMixerFormat;
5169 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5170
Eric Laurent81784c32012-11-19 14:55:58 -08005171 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5172 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5173 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5174 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005175 const NBAIO_Format offersFast[1] = {format};
5176 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005177#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005178 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005179#else
5180 (void)
5181#endif
Andy Hung920f6572022-10-06 12:09:49 -07005182 monoPipe->negotiate(offersFast, std::size(offersFast),
5183 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005184 ALOG_ASSERT(index == 0);
5185 monoPipe->setAvgFrames((mScreenState & 1) ?
5186 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5187 mPipeSink = monoPipe;
5188
Eric Laurent81784c32012-11-19 14:55:58 -08005189 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005190 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005191 FastMixerStateQueue *sq = mFastMixer->sq();
5192#ifdef STATE_QUEUE_DUMP
5193 sq->setObserverDump(&mStateQueueObserverDump);
5194 sq->setMutatorDump(&mStateQueueMutatorDump);
5195#endif
5196 FastMixerState *state = sq->begin();
5197 FastTrack *fastTrack = &state->mFastTracks[0];
5198 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5199 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5200 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005201 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5202 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5203 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005204 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005205 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
Ahmad Khalil229466a2024-02-05 12:15:30 +00005206 fastTrack->mHapticScale = {/*level=*/os::HapticLevel::NONE };
Lais Andradebc3f37a2021-07-02 00:13:19 +01005207 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005208 fastTrack->mGeneration++;
5209 state->mFastTracksGen++;
5210 state->mTrackMask = 1;
5211 // fast mixer will use the HAL output sink
5212 state->mOutputSink = mOutputSink.get();
5213 state->mOutputSinkGen++;
5214 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005215 // specify sink channel mask when haptic channel mask present as it can not
5216 // be calculated directly from channel count
5217 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005218 ? AUDIO_CHANNEL_NONE
5219 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005220 state->mCommand = FastMixerState::COLD_IDLE;
5221 // already done in constructor initialization list
5222 //mFastMixerFutex = 0;
5223 state->mColdFutexAddr = &mFastMixerFutex;
5224 state->mColdGen++;
5225 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005226 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005227 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005228 sq->end();
5229 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5230
Eric Tan0513b5d2018-09-17 10:32:48 -07005231 NBLog::thread_info_t info;
5232 info.id = mId;
5233 info.type = NBLog::FASTMIXER;
5234 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5235
Eric Laurent81784c32012-11-19 14:55:58 -08005236 // start the fast mixer
5237 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5238 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005239 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005240 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005241
5242#ifdef AUDIO_WATCHDOG
5243 // create and start the watchdog
5244 mAudioWatchdog = new AudioWatchdog();
5245 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5246 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5247 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005248 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005249#endif
Andy Hung8946a282018-04-19 20:04:56 -07005250 } else {
5251#ifdef TEE_SINK
5252 // Only use the MixerThread tee if there is no FastMixer.
5253 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5254 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5255#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005256 }
5257
5258 switch (kUseFastMixer) {
5259 case FastMixer_Never:
5260 case FastMixer_Dynamic:
5261 mNormalSink = mOutputSink;
5262 break;
5263 case FastMixer_Always:
5264 mNormalSink = mPipeSink;
5265 break;
5266 case FastMixer_Static:
5267 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5268 break;
5269 }
5270}
5271
Andy Hungee58e4a2023-07-07 13:47:37 -07005272MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005273{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005274 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005275 FastMixerStateQueue *sq = mFastMixer->sq();
5276 FastMixerState *state = sq->begin();
5277 if (state->mCommand == FastMixerState::COLD_IDLE) {
5278 int32_t old = android_atomic_inc(&mFastMixerFutex);
5279 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005280 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005281 }
5282 }
5283 state->mCommand = FastMixerState::EXIT;
5284 sq->end();
5285 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5286 mFastMixer->join();
5287 // Though the fast mixer thread has exited, it's state queue is still valid.
5288 // We'll use that extract the final state which contains one remaining fast track
5289 // corresponding to our sub-mix.
5290 state = sq->begin();
5291 ALOG_ASSERT(state->mTrackMask == 1);
5292 FastTrack *fastTrack = &state->mFastTracks[0];
5293 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5294 delete fastTrack->mBufferProvider;
5295 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005296 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005297#ifdef AUDIO_WATCHDOG
5298 if (mAudioWatchdog != 0) {
5299 mAudioWatchdog->requestExit();
5300 mAudioWatchdog->requestExitAndWait();
5301 mAudioWatchdog.clear();
5302 }
5303#endif
5304 }
Andy Hung583043b2023-07-17 17:05:00 -07005305 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005306 delete mAudioMixer;
5307}
5308
Andy Hungee58e4a2023-07-07 13:47:37 -07005309void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005310 PlaybackThread::onFirstRef();
5311
Andy Hung972bec12023-08-31 16:13:39 -07005312 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005313 if (mOutput != nullptr && mOutput->stream != nullptr) {
5314 status_t status = mOutput->stream->setLatencyModeCallback(this);
5315 if (status != INVALID_OPERATION) {
5316 updateHalSupportedLatencyModes_l();
5317 }
5318 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5319 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5320 mBluetoothLatencyModesEnabled.store(
5321 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5322 }
5323}
Eric Laurent81784c32012-11-19 14:55:58 -08005324
Andy Hungee58e4a2023-07-07 13:47:37 -07005325uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005326{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005327 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005328 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5329 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5330 }
5331 return latency;
5332}
5333
Andy Hungee58e4a2023-07-07 13:47:37 -07005334ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005335{
5336 // FIXME we should only do one push per cycle; confirm this is true
5337 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005338 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005339 FastMixerStateQueue *sq = mFastMixer->sq();
5340 FastMixerState *state = sq->begin();
5341 if (state->mCommand != FastMixerState::MIX_WRITE &&
5342 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5343 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005344
5345 // FIXME workaround for first HAL write being CPU bound on some devices
5346 ATRACE_BEGIN("write");
5347 mOutput->write((char *)mSinkBuffer, 0);
5348 ATRACE_END();
5349
Eric Laurent81784c32012-11-19 14:55:58 -08005350 int32_t old = android_atomic_inc(&mFastMixerFutex);
5351 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005352 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005353 }
5354#ifdef AUDIO_WATCHDOG
5355 if (mAudioWatchdog != 0) {
5356 mAudioWatchdog->resume();
5357 }
5358#endif
5359 }
5360 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005361#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005362 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005363 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005364#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005365 sq->end();
5366 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5367 if (kUseFastMixer == FastMixer_Dynamic) {
5368 mNormalSink = mPipeSink;
5369 }
5370 } else {
5371 sq->end(false /*didModify*/);
5372 }
5373 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005374 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005375}
5376
Andy Hungee58e4a2023-07-07 13:47:37 -07005377void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005378{
5379 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005380 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005381 FastMixerStateQueue *sq = mFastMixer->sq();
5382 FastMixerState *state = sq->begin();
5383 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005384 // Report any frames trapped in the Monopipe
5385 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5386 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5387 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5388 "monoPipeWritten:%lld monoPipeLeft:%lld",
5389 (long long)mFramesWritten, (long long)mSuspendedFrames,
5390 (long long)mPipeSink->framesWritten(), pipeFrames);
5391 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5392
Eric Laurent81784c32012-11-19 14:55:58 -08005393 state->mCommand = FastMixerState::COLD_IDLE;
5394 state->mColdFutexAddr = &mFastMixerFutex;
5395 state->mColdGen++;
5396 mFastMixerFutex = 0;
5397 sq->end();
5398 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5399 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5400 if (kUseFastMixer == FastMixer_Dynamic) {
5401 mNormalSink = mOutputSink;
5402 }
5403#ifdef AUDIO_WATCHDOG
5404 if (mAudioWatchdog != 0) {
5405 mAudioWatchdog->pause();
5406 }
5407#endif
5408 } else {
5409 sq->end(false /*didModify*/);
5410 }
5411 }
5412 PlaybackThread::threadLoop_standby();
5413}
5414
Andy Hungee58e4a2023-07-07 13:47:37 -07005415bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005416{
5417 return false;
5418}
5419
Andy Hungee58e4a2023-07-07 13:47:37 -07005420bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005421{
5422 return !mStandby;
5423}
5424
Andy Hungee58e4a2023-07-07 13:47:37 -07005425bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005426{
Andy Hung972bec12023-08-31 16:13:39 -07005427 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005428 return waitingAsyncCallback_l();
5429}
5430
Eric Laurent81784c32012-11-19 14:55:58 -08005431// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005432void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005433{
Andy Hung8d672e02023-09-15 18:19:28 -07005434 ALOGV("%s: audio hardware entering standby, mixer %p, suspend count %d",
5435 __func__, this, (int32_t)mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005436 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005437 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005438 // discard any pending drain or write ack by incrementing sequence
5439 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5440 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005441 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005442 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5443 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005444 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005445 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005446 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005447}
5448
Andy Hungee58e4a2023-07-07 13:47:37 -07005449void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005450{
5451 ALOGV("signal playback thread");
5452 broadcast_l();
5453}
5454
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005455void PlaybackThread::onAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005456{
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005457 auto allTrackPortIds = getTrackPortIds();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005458 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5459 invalidateTracks((audio_stream_type_t)i);
5460 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07005461 if (isHardError) {
5462 mAfThreadCallback->onHardError(allTrackPortIds);
5463 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005464}
5465
Andy Hungee58e4a2023-07-07 13:47:37 -07005466void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005467{
Eric Laurent81784c32012-11-19 14:55:58 -08005468 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005469 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005470 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005471 // increase sleep time progressively when application underrun condition clears.
5472 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5473 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5474 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005475 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005476 sleepTimeShift--;
5477 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005478 mSleepTimeUs = 0;
5479 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005480 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005481
Eric Laurent81784c32012-11-19 14:55:58 -08005482}
5483
Andy Hungee58e4a2023-07-07 13:47:37 -07005484void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005485{
5486 // If no tracks are ready, sleep once for the duration of an output
5487 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005488 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005489 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005490 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5491 // Using the Monopipe availableToWrite, we estimate the
5492 // sleep time to retry for more data (before we underrun).
5493 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5494 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5495 const size_t pipeFrames = monoPipe->maxFrames();
5496 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5497 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5498 const size_t framesDelay = std::min(
5499 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5500 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5501 pipeFrames, framesLeft, framesDelay);
5502 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5503 } else {
5504 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5505 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5506 mSleepTimeUs = kMinThreadSleepTimeUs;
5507 }
5508 // reduce sleep time in case of consecutive application underruns to avoid
5509 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5510 // duration we would end up writing less data than needed by the audio HAL if
5511 // the condition persists.
5512 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5513 sleepTimeShift++;
5514 }
Eric Laurent81784c32012-11-19 14:55:58 -08005515 }
5516 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005517 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005518 }
5519 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005520 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5521 // before effects processing or output.
5522 if (mMixerBufferValid) {
5523 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005524 if (mType == SPATIALIZER) {
5525 memset(mSinkBuffer, 0, mSinkBufferSize);
5526 }
Andy Hung98ef9782014-03-04 14:46:50 -08005527 } else {
5528 memset(mSinkBuffer, 0, mSinkBufferSize);
5529 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005530 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005531 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5532 "anticipated start");
5533 }
5534 // TODO add standby time extension fct of effect tail
5535}
5536
Andy Hungc5007f82023-08-29 14:26:09 -07005537// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005538PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005539 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005540{
Andy Hungc0691382018-09-12 18:01:57 -07005541 // clean up deleted track ids in AudioMixer before allocating new tracks
5542 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5543 // for each trackId, destroy it in the AudioMixer
5544 if (mAudioMixer->exists(trackId)) {
5545 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005546 }
5547 });
Andy Hungc0691382018-09-12 18:01:57 -07005548 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005549
5550 mixer_state mixerStatus = MIXER_IDLE;
5551 // find out which tracks need to be processed
5552 size_t count = mActiveTracks.size();
5553 size_t mixedTracks = 0;
5554 size_t tracksWithEffect = 0;
5555 // counts only _active_ fast tracks
5556 size_t fastTracks = 0;
5557 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5558
5559 float masterVolume = mMasterVolume;
5560 bool masterMute = mMasterMute;
5561
5562 if (masterMute) {
5563 masterVolume = 0;
5564 }
5565 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005566 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005567 if (chain != 0) {
5568 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00005569 chain->setVolume(&v, &v);
Eric Laurent81784c32012-11-19 14:55:58 -08005570 masterVolume = (float)((v + (1 << 23)) >> 24);
5571 chain.clear();
5572 }
5573
5574 // prepare a new state to push
5575 FastMixerStateQueue *sq = NULL;
5576 FastMixerState *state = NULL;
5577 bool didModify = false;
5578 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005579 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005580 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005581 sq = mFastMixer->sq();
5582 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005583 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005584 }
5585
Andy Hung69aed5f2014-02-25 17:24:40 -08005586 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005587 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005588
Andy Hungbd3b2b02018-05-21 10:53:11 -07005589 // DeferredOperations handles statistics after setting mixerStatus.
5590 class DeferredOperations {
5591 public:
Andy Hungea840382020-05-05 21:50:17 -07005592 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5593 : mMixerStatus(mixerStatus)
5594 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005595
5596 // when leaving scope, tally frames properly.
5597 ~DeferredOperations() {
5598 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5599 // because that is when the underrun occurs.
5600 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005601 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005602 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005603 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005604 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005605 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005606 }
5607 }
Andy Hungea840382020-05-05 21:50:17 -07005608 // send the max underrun frames for this mixer period
5609 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005610 }
5611
5612 // tallyUnderrunFrames() is called to update the track counters
5613 // with the number of underrun frames for a particular mixer period.
5614 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005615 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005616 mUnderrunFrames.emplace_back(track, underrunFrames);
5617 }
5618
5619 private:
5620 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005621 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005622 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005623 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005624 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005625
jiabin245cdd92018-12-07 17:55:15 -08005626 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005627 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005628 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005629
5630 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005631 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005632
5633 // process fast tracks
5634 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005635 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5636 "%s(%d): FastTrack(%d) present without FastMixer",
5637 __func__, id(), track->id());
5638
jiabin245cdd92018-12-07 17:55:15 -08005639 if (track->getHapticPlaybackEnabled()) {
5640 noFastHapticTrack = false;
5641 }
Eric Laurent81784c32012-11-19 14:55:58 -08005642
5643 // It's theoretically possible (though unlikely) for a fast track to be created
5644 // and then removed within the same normal mix cycle. This is not a problem, as
5645 // the track never becomes active so it's fast mixer slot is never touched.
5646 // The converse, of removing an (active) track and then creating a new track
5647 // at the identical fast mixer slot within the same normal mix cycle,
5648 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005649 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005650 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005651 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5652 FastTrack *fastTrack = &state->mFastTracks[j];
5653
5654 // Determine whether the track is currently in underrun condition,
5655 // and whether it had a recent underrun.
5656 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5657 FastTrackUnderruns underruns = ftDump->mUnderruns;
5658 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005659 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005660 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005661 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005662 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005663 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005664 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005665 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005666 // don't count underruns that occur while stopping or pausing
5667 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005668 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005669 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5670 recentUnderruns > 0) {
5671 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005672 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005673 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005674 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005675 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005676
5677 // This is similar to the state machine for normal tracks,
5678 // with a few modifications for fast tracks.
5679 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005680 switch (track->state()) {
5681 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005682 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005683 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005684 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005685 }
5686 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005687 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005688 // ramp down is not yet implemented
5689 track->setPaused();
5690 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005691 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005692 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005693 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005694 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005695 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005696 if (recentFull > 0 || recentPartial > 0) {
5697 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005698 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005699 }
5700 if (recentUnderruns == 0) {
5701 // no recent underruns: stay active
5702 break;
5703 }
5704 // there has recently been an underrun of some kind
5705 if (track->sharedBuffer() == 0) {
5706 // were any of the recent underruns "empty" (no frames available)?
5707 if (recentEmpty == 0) {
5708 // no, then ignore the partial underruns as they are allowed indefinitely
5709 break;
5710 }
5711 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005712 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005713 break;
5714 }
5715 // indicate to client process that the track was disabled because of underrun;
5716 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005717 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005718 // remove from active list, but state remains ACTIVE [confusing but true]
5719 isActive = false;
5720 break;
5721 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005722 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005723 case IAfTrackBase::STOPPING_2:
5724 case IAfTrackBase::PAUSED:
5725 case IAfTrackBase::STOPPED:
5726 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005727 // Check for presentation complete if track is inactive
5728 // We have consumed all the buffers of this track.
5729 // This would be incomplete if we auto-paused on underrun
5730 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005731 uint32_t latency = 0;
5732 status_t result = mOutput->stream->getLatency(&latency);
5733 ALOGE_IF(result != OK,
5734 "Error when retrieving output stream latency: %d", result);
5735 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005736 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005737 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5738 // track stays in active list until presentation is complete
5739 break;
5740 }
5741 }
5742 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005743 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005744 }
5745 if (track->isStopped()) {
5746 // Can't reset directly, as fast mixer is still polling this track
5747 // track->reset();
5748 // So instead mark this track as needing to be reset after push with ack
5749 resetMask |= 1 << i;
5750 }
5751 isActive = false;
5752 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005753 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005754 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005755 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005756 }
5757
5758 if (isActive) {
5759 // was it previously inactive?
5760 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005761 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5762 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005763 fastTrack->mBufferProvider = eabp;
5764 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005765 fastTrack->mChannelMask = track->channelMask();
5766 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005767 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
Ahmad Khalil229466a2024-02-05 12:15:30 +00005768 fastTrack->mHapticScale = track->getHapticScale();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005769 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005770 fastTrack->mGeneration++;
5771 state->mTrackMask |= 1 << j;
5772 didModify = true;
5773 // no acknowledgement required for newly active tracks
5774 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005775 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005776 float volume;
5777 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5778 volume = 0.f;
5779 } else {
5780 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5781 }
5782
5783 handleVoipVolume_l(&volume);
5784
Eric Laurent81784c32012-11-19 14:55:58 -08005785 // cache the combined master volume and stream type volume for fast mixer; this
5786 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005787 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005788 proxy->framesReleased()).first;
5789 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005790 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005791 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005792 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5793 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5794
Andy Hung583043b2023-07-17 17:05:00 -07005795 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005796 /*muteState=*/{masterVolume == 0.f,
5797 mStreamTypes[track->streamType()].volume == 0.f,
5798 mStreamTypes[track->streamType()].mute,
5799 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005800 vlf == 0.f && vrf == 0.f,
5801 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005802
5803 vlf *= volume;
5804 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005805
jiabin220eea12024-05-17 17:55:20 +00005806 if (track->getInternalMute()) {
5807 vlf = 0.f;
5808 vrf = 0.f;
5809 }
5810
jiabin76d94692022-12-15 21:51:21 +00005811 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005812 ++fastTracks;
5813 } else {
5814 // was it previously active?
5815 if (state->mTrackMask & (1 << j)) {
5816 fastTrack->mBufferProvider = NULL;
5817 fastTrack->mGeneration++;
5818 state->mTrackMask &= ~(1 << j);
5819 didModify = true;
5820 // If any fast tracks were removed, we must wait for acknowledgement
5821 // because we're about to decrement the last sp<> on those tracks.
5822 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5823 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005824 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5825 // AudioTrack may start (which may not be with a start() but with a write()
5826 // after underrun) and immediately paused or released. In that case the
5827 // FastTrack state hasn't had time to update.
5828 // TODO Remove the ALOGW when this theory is confirmed.
5829 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005830 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005831 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005832 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005833 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005834 }
5835 tracksToRemove->add(track);
5836 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005837 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005838 }
jiabin245cdd92018-12-07 17:55:15 -08005839 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5840 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5841 didModify = true;
5842 }
Eric Laurent81784c32012-11-19 14:55:58 -08005843 continue;
5844 }
5845
5846 { // local variable scope to avoid goto warning
5847
5848 audio_track_cblk_t* cblk = track->cblk();
5849
5850 // The first time a track is added we wait
5851 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005852 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005853
5854 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005855 // use the trackId as the AudioMixer name.
5856 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005857 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005858 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005859 track->channelMask(),
5860 track->format(),
5861 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005862 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005863 ALOGW("%s(): AudioMixer cannot create track(%d)"
5864 " mask %#x, format %#x, sessionId %d",
5865 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005866 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005867 tracksToRemove->add(track);
5868 track->invalidate(); // consider it dead.
5869 continue;
5870 }
5871 }
5872
Eric Laurent81784c32012-11-19 14:55:58 -08005873 // make sure that we have enough frames to mix one full buffer.
5874 // enforce this condition only once to enable draining the buffer in case the client
5875 // app does not call stop() and relies on underrun to stop:
5876 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5877 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005878 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005879 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5880 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005881
5882 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005883 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005884 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5885 // add frames already consumed but not yet released by the resampler
5886 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005887 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005888
Eric Laurent81784c32012-11-19 14:55:58 -08005889 uint32_t minFrames = 1;
5890 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5891 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005892 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005893 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005894
5895 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005896 if (ATRACE_ENABLED()) {
5897 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005898 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005899 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005900 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005901 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005902 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005903 !track->isPaused() && !track->isTerminated())
5904 {
Andy Hungc0691382018-09-12 18:01:57 -07005905 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005906
5907 mixedTracks++;
5908
Shunkai Yaof4847652024-01-12 00:25:20 +00005909 // track->mainBuffer() != mSinkBuffer and mMixerBuffer means
Andy Hung69aed5f2014-02-25 17:24:40 -08005910 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005911 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005912 if (track->mainBuffer() != mSinkBuffer &&
5913 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005914 if (mEffectBufferEnabled) {
5915 mEffectBufferValid = true; // Later can set directly.
5916 }
Eric Laurent81784c32012-11-19 14:55:58 -08005917 chain = getEffectChain_l(track->sessionId());
5918 // Delegate volume control to effect in track effect chain if needed
5919 if (chain != 0) {
5920 tracksWithEffect++;
5921 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005922 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005923 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005924 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005925 }
5926 }
5927
5928
5929 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005930 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005931 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005932 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5933 if (track->state() == IAfTrackBase::RESUMING) {
5934 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005935 // If a new track is paused immediately after start, do not ramp on resume.
5936 if (cblk->mServer != 0) {
5937 param = AudioMixer::RAMP_VOLUME;
5938 }
Eric Laurent81784c32012-11-19 14:55:58 -08005939 }
Andy Hungc0691382018-09-12 18:01:57 -07005940 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005941 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005942 // FIXME should not make a decision based on mServer
5943 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005944 // If the track is stopped before the first frame was mixed,
5945 // do not apply ramp
5946 param = AudioMixer::RAMP_VOLUME;
5947 }
5948
5949 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005950 uint32_t vl, vr; // in U8.24 integer format
5951 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005952 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005953 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005954 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005955 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005956 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005957 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005958
Eric Laurenteab90452019-06-24 15:17:46 -07005959 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5960 v = 0;
5961 }
5962
5963 handleVoipVolume_l(&v);
5964
5965 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005966 vl = vr = 0;
5967 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005968 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005969 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005970 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005971 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5972 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005973 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005974 if (vlf > GAIN_FLOAT_UNITY) {
5975 ALOGV("Track left volume out of range: %.3g", vlf);
5976 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005977 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005978 if (vrf > GAIN_FLOAT_UNITY) {
5979 ALOGV("Track right volume out of range: %.3g", vrf);
5980 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005981 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005982
Andy Hung583043b2023-07-17 17:05:00 -07005983 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005984 /*muteState=*/{masterVolume == 0.f,
5985 mStreamTypes[track->streamType()].volume == 0.f,
5986 mStreamTypes[track->streamType()].mute,
5987 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005988 vlf == 0.f && vrf == 0.f,
5989 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005990
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005991 // now apply the master volume and stream type volume and shaper volume
5992 vlf *= v * vh;
5993 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005994 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005995 // then derive vl and vr as U8.24 versions for the effect chain
5996 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5997 vl = (uint32_t) (scaleto8_24 * vlf);
5998 vr = (uint32_t) (scaleto8_24 * vrf);
5999 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08006000 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08006001 // send level comes from shared memory and so may be corrupt
6002 if (sendLevel > MAX_GAIN_INT) {
6003 ALOGV("Track send level out of range: %04X", sendLevel);
6004 sendLevel = MAX_GAIN_INT;
6005 }
Andy Hung6be49402014-05-30 10:42:03 -07006006 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
6007 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08006008 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006009
jiabin220eea12024-05-17 17:55:20 +00006010 if (track->getInternalMute()) {
6011 vrf = 0.f;
6012 vlf = 0.f;
6013 }
6014
Jiabin Huang66aa1e32024-05-13 20:33:29 +00006015 track->setFinalVolume(vlf, vrf);
Kevin Rocard12381092018-04-11 09:19:59 -07006016
Eric Laurent81784c32012-11-19 14:55:58 -08006017 // Delegate volume control to effect in track effect chain if needed
Shunkai Yaof4847652024-01-12 00:25:20 +00006018 if (chain != 0 && chain->setVolume(&vl, &vr)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006019 // Do not ramp volume if volume is controlled by effect
6020 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08006021 // Update remaining floating point volume levels
6022 vlf = (float)vl / (1 << 24);
6023 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07006024 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08006025 } else {
6026 // force no volume ramp when volume controller was just disabled or removed
6027 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07006028 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006029 param = AudioMixer::VOLUME;
6030 }
Andy Hung8d31fd22023-06-26 19:20:57 -07006031 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08006032 }
6033
Eric Laurent81784c32012-11-19 14:55:58 -08006034 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07006035 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07006036 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006037
Andy Hungc0691382018-09-12 18:01:57 -07006038 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
6039 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
6040 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08006041 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006042 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006043 AudioMixer::TRACK,
6044 AudioMixer::FORMAT, (void *)track->format());
6045 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006046 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006047 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006048 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02006049
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006050 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006051 mAudioMixer->setParameter(
6052 trackId,
6053 AudioMixer::TRACK,
6054 AudioMixer::MIXER_CHANNEL_MASK,
6055 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
6056 } else {
6057 mAudioMixer->setParameter(
6058 trackId,
6059 AudioMixer::TRACK,
6060 AudioMixer::MIXER_CHANNEL_MASK,
6061 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
6062 }
6063
Glenn Kastene3aa6592012-12-04 12:22:46 -08006064 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07006065 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07006066 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08006067 if (reqSampleRate == 0) {
6068 reqSampleRate = mSampleRate;
6069 } else if (reqSampleRate > maxSampleRate) {
6070 reqSampleRate = maxSampleRate;
6071 }
Eric Laurent81784c32012-11-19 14:55:58 -08006072 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006073 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006074 AudioMixer::RESAMPLE,
6075 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00006076 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07006077
Andy Hung8edb8dc2015-03-26 19:13:55 -07006078 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006079 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07006080 AudioMixer::TIMESTRETCH,
6081 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07006082 // cast away constness for this generic API.
6083 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07006084
Andy Hung69aed5f2014-02-25 17:24:40 -08006085 /*
6086 * Select the appropriate output buffer for the track.
6087 *
Andy Hung98ef9782014-03-04 14:46:50 -08006088 * Tracks with effects go into their own effects chain buffer
6089 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08006090 *
6091 * Other tracks can use mMixerBuffer for higher precision
6092 * channel accumulation. If this buffer is enabled
6093 * (mMixerBufferEnabled true), then selected tracks will accumulate
6094 * into it.
6095 *
6096 */
6097 if (mMixerBufferEnabled
6098 && (track->mainBuffer() == mSinkBuffer
6099 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02006100 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02006101 mAudioMixer->setParameter(
6102 trackId,
6103 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006104 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02006105 mAudioMixer->setParameter(
6106 trackId,
6107 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02006108 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02006109 } else {
6110 mAudioMixer->setParameter(
6111 trackId,
6112 AudioMixer::TRACK,
6113 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
6114 mAudioMixer->setParameter(
6115 trackId,
6116 AudioMixer::TRACK,
6117 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
6118 // TODO: override track->mainBuffer()?
6119 mMixerBufferValid = true;
6120 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006121 } else {
6122 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006123 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006124 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006125 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006126 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006127 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006128 AudioMixer::TRACK,
6129 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6130 }
Eric Laurent81784c32012-11-19 14:55:58 -08006131 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006132 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006133 AudioMixer::TRACK,
6134 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006135 mAudioMixer->setParameter(
6136 trackId,
6137 AudioMixer::TRACK,
6138 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
Ahmad Khalil229466a2024-02-05 12:15:30 +00006139 const os::HapticScale hapticScale = track->getHapticScale();
jiabin77270b82018-12-18 15:41:29 -08006140 mAudioMixer->setParameter(
Ahmad Khalil229466a2024-02-05 12:15:30 +00006141 trackId,
6142 AudioMixer::TRACK,
6143 AudioMixer::HAPTIC_SCALE, (void *)&hapticScale);
Andy Hung8d31fd22023-06-26 19:20:57 -07006144 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006145 mAudioMixer->setParameter(
6146 trackId,
6147 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07006148 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006149
6150 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006151 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006152
6153 // If one track is ready, set the mixer ready if:
6154 // - the mixer was not ready during previous round OR
6155 // - no other track is not ready
6156 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6157 mixerStatus != MIXER_TRACKS_ENABLED) {
6158 mixerStatus = MIXER_TRACKS_READY;
6159 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006160
6161 // Enable the next few lines to instrument a test for underrun log handling.
6162 // TODO: Remove when we have a better way of testing the underrun log.
6163#if 0
6164 static int i;
6165 if ((++i & 0xf) == 0) {
6166 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6167 }
6168#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006169 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006170 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006171 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006172 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6173 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006174 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006175 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006176 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006177
Eric Laurent81784c32012-11-19 14:55:58 -08006178 // clear effect chain input buffer if an active track underruns to avoid sending
6179 // previous audio buffer again to effects
6180 chain = getEffectChain_l(track->sessionId());
6181 if (chain != 0) {
6182 chain->clearInputBuffer();
6183 }
6184
Andy Hungc0691382018-09-12 18:01:57 -07006185 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006186 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6187 track->isStopped() || track->isPaused()) {
6188 // We have consumed all the buffers of this track.
6189 // Remove it from the list of active tracks.
6190 // TODO: use actual buffer filling status instead of latency when available from
6191 // audio HAL
6192 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006193 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006194 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6195 if (track->isStopped()) {
6196 track->reset();
6197 }
6198 tracksToRemove->add(track);
6199 }
6200 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006201 // No buffers for this track. Give it a few chances to
6202 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006203 if (--(track->retryCount()) <= 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00006204 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to underrun"
6205 " on thread %d", __func__, trackId, mId);
Eric Laurent81784c32012-11-19 14:55:58 -08006206 tracksToRemove->add(track);
6207 // indicate to client process that the track was disabled because of underrun;
6208 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006209 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006210 // If one track is not ready, mark the mixer also not ready if:
6211 // - the mixer was ready during previous round OR
6212 // - no other track is ready
6213 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6214 mixerStatus != MIXER_TRACKS_READY) {
6215 mixerStatus = MIXER_TRACKS_ENABLED;
6216 }
6217 }
Andy Hungc0691382018-09-12 18:01:57 -07006218 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006219 }
6220
6221 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006222
6223 }
6224
jiabin245cdd92018-12-07 17:55:15 -08006225 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6226 // When there is no fast track playing haptic and FastMixer exists,
6227 // enabling the first FastTrack, which provides mixed data from normal
6228 // tracks, to play haptic data.
6229 FastTrack *fastTrack = &state->mFastTracks[0];
6230 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6231 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6232 didModify = true;
6233 }
6234 }
6235
Eric Laurent81784c32012-11-19 14:55:58 -08006236 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006237 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006238 if (didModify) {
6239 state->mFastTracksGen++;
6240 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6241 if (kUseFastMixer == FastMixer_Dynamic &&
6242 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6243 state->mCommand = FastMixerState::COLD_IDLE;
6244 state->mColdFutexAddr = &mFastMixerFutex;
6245 state->mColdGen++;
6246 mFastMixerFutex = 0;
6247 if (kUseFastMixer == FastMixer_Dynamic) {
6248 mNormalSink = mOutputSink;
6249 }
6250 // If we go into cold idle, need to wait for acknowledgement
6251 // so that fast mixer stops doing I/O.
6252 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6253 pauseAudioWatchdog = true;
6254 }
Eric Laurent81784c32012-11-19 14:55:58 -08006255 }
6256 if (sq != NULL) {
6257 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006258 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6259 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6260 // when bringing the output sink into standby.)
6261 //
6262 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6263 //
6264 // This occurs with BT suspend when we idle the FastMixer with
6265 // active tracks, which may be added or removed.
6266 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006267 }
6268#ifdef AUDIO_WATCHDOG
6269 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6270 mAudioWatchdog->pause();
6271 }
6272#endif
6273
6274 // Now perform the deferred reset on fast tracks that have stopped
6275 while (resetMask != 0) {
6276 size_t i = __builtin_ctz(resetMask);
6277 ALOG_ASSERT(i < count);
6278 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006279 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006280 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6281 track->reset();
6282 }
6283
Andy Hung80d03d22018-04-10 10:32:11 -07006284 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6285 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6286 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6287 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6288 // See also the implementation of destroyTrack_l().
6289 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006290 const int trackId = track->id();
6291 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6292 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006293 }
6294 }
6295
Eric Laurent81784c32012-11-19 14:55:58 -08006296 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006297 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006298
Eric Laurentb3f315a2021-07-13 15:09:05 +02006299 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6300 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006301 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006302 }
6303
6304 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006305 // as long as there are effects we should clear the effects buffer, to avoid
6306 // passing a non-clean buffer to the effect chain
6307 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006308 if (mType == SPATIALIZER) {
6309 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6310 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006311 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006312 // sink or mix buffer must be cleared if all tracks are connected to an
6313 // effect chain as in this case the mixer will not write to the sink or mix buffer
6314 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006315 // always clear sink buffer for spatializer output as the output of the spatializer
6316 // effect will be accumulated into it
6317 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6318 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006319 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006320 if (mMixerBufferValid) {
6321 memset(mMixerBuffer, 0, mMixerBufferSize);
6322 // TODO: In testing, mSinkBuffer below need not be cleared because
6323 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6324 // after mixing.
6325 //
6326 // To enforce this guarantee:
6327 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6328 // (mixedTracks == 0 && fastTracks > 0))
6329 // must imply MIXER_TRACKS_READY.
6330 // Later, we may clear buffers regardless, and skip much of this logic.
6331 }
Andy Hung98ef9782014-03-04 14:46:50 -08006332 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006333 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006334 }
6335
6336 // if any fast tracks, then status is ready
6337 mMixerStatusIgnoringFastTracks = mixerStatus;
6338 if (fastTracks > 0) {
6339 mixerStatus = MIXER_TRACKS_READY;
6340 }
6341 return mixerStatus;
6342}
6343
Andy Hungc5007f82023-08-29 14:26:09 -07006344// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006345uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006346{
6347 uint32_t trackCount = 0;
6348 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006349 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006350 trackCount++;
6351 }
6352 }
6353 return trackCount;
6354}
6355
Andy Hungee58e4a2023-07-07 13:47:37 -07006356bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006357{
Brian Lindahl65e90012022-07-27 18:01:07 +02006358 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6359 // could falsely detect that the frame position has stalled due to underrun because we haven't
6360 // given the Audio HAL enough time to update.
6361 const nsecs_t nowNs = systemTime();
6362 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6363 return mLatchedValue;
6364 }
6365 mPreviousNs = nowNs;
6366 mLatchedValue = false;
6367 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006368 uint64_t position = 0;
6369 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006370 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006371 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006372 if (position != mPreviousPosition) {
6373 mPreviousPosition = position;
6374 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006375 }
6376 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006377 return mLatchedValue;
6378}
6379
Andy Hungee58e4a2023-07-07 13:47:37 -07006380void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006381{
6382 mLatchedValue = true;
6383 mPreviousPosition = 0;
6384 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006385}
6386
Andy Hungc5007f82023-08-29 14:26:09 -07006387// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006388bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006389 audio_channel_mask_t channelMask, audio_format_t format,
6390 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006391{
Andy Hung1bc088a2018-02-09 15:57:31 -08006392 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6393 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006394 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006395 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006396 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006397 ALOGW("%s: invalid format: %#x", __func__, format);
6398 return false;
6399 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006400 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006401 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6402 return false;
6403 }
6404 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006405}
6406
Andy Hungc5007f82023-08-29 14:26:09 -07006407// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006408bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006409 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006410{
Eric Laurent81784c32012-11-19 14:55:58 -08006411 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006412 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006413
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006414 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006415
Eric Laurent10351942014-05-08 18:49:52 -07006416 AudioParameter param = AudioParameter(keyValuePair);
6417 int value;
6418 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6419 reconfig = true;
6420 }
6421 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006422 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006423 status = BAD_VALUE;
6424 } else {
6425 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006426 reconfig = true;
6427 }
Eric Laurent10351942014-05-08 18:49:52 -07006428 }
6429 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006430 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006431 status = BAD_VALUE;
6432 } else {
6433 // no need to save value, since it's constant
6434 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006435 }
Eric Laurent10351942014-05-08 18:49:52 -07006436 }
6437 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6438 // do not accept frame count changes if tracks are open as the track buffer
6439 // size depends on frame count and correct behavior would not be guaranteed
6440 // if frame count is changed after track creation
6441 if (!mTracks.isEmpty()) {
6442 status = INVALID_OPERATION;
6443 } else {
6444 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006445 }
Eric Laurent10351942014-05-08 18:49:52 -07006446 }
6447 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006448 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006449 }
Eric Laurent81784c32012-11-19 14:55:58 -08006450
Eric Laurent10351942014-05-08 18:49:52 -07006451 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006452 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006453 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006454 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6455 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006456 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006457 mThreadMetrics.logEndInterval();
6458 mThreadSnapshot.onEnd();
6459 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006460 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006461 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006462 }
Eric Laurent10351942014-05-08 18:49:52 -07006463 if (status == NO_ERROR && reconfig) {
6464 readOutputParameters_l();
6465 delete mAudioMixer;
6466 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006467 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006468 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006469 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006470 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006471 track->channelMask(),
6472 track->format(),
6473 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006474 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006475 "%s(): AudioMixer cannot create track(%d)"
6476 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006477 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006478 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006479 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006480 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006481 }
Eric Laurent81784c32012-11-19 14:55:58 -08006482 }
6483
Dean Wheatley68918102021-03-19 22:09:19 +11006484 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006485}
6486
6487
Andy Hungee58e4a2023-07-07 13:47:37 -07006488void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006489{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006490 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung8d672e02023-09-15 18:19:28 -07006491 dprintf(fd, " Thread throttle time (msecs): %u\n", (uint32_t)mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006492 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006493 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006494 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6495 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6496 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006497 if (hasFastMixer()) {
6498 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6499
6500 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6501 // while we are dumping it. It may be inconsistent, but it won't mutate!
6502 // This is a large object so we place it on the heap.
6503 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006504 const std::unique_ptr<FastMixerDumpState> copy =
6505 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006506 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006507
6508#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006509 // Similar for state queue
6510 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6511 observerCopy.dump(fd);
6512 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6513 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006514#endif
6515
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006516#ifdef AUDIO_WATCHDOG
6517 if (mAudioWatchdog != 0) {
6518 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6519 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6520 wdCopy.dump(fd);
6521 }
6522#endif
6523
6524 } else {
6525 dprintf(fd, " No FastMixer\n");
6526 }
Eric Laurent90cea102023-05-15 15:08:27 +02006527
6528 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6529 mBluetoothLatencyModesEnabled ? "" : "not ");
6530 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6531 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6532 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006533}
6534
Andy Hungee58e4a2023-07-07 13:47:37 -07006535uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006536{
6537 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6538}
6539
Andy Hungee58e4a2023-07-07 13:47:37 -07006540uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006541{
6542 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6543}
6544
Andy Hungee58e4a2023-07-07 13:47:37 -07006545void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006546{
6547 PlaybackThread::cacheParameters_l();
6548
6549 // FIXME: Relaxed timing because of a certain device that can't meet latency
6550 // Should be reduced to 2x after the vendor fixes the driver issue
6551 // increase threshold again due to low power audio mode. The way this warning
6552 // threshold is calculated and its usefulness should be reconsidered anyway.
6553 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6554}
6555
Andy Hungee58e4a2023-07-07 13:47:37 -07006556void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006557 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006558}
6559
Andy Hungee58e4a2023-07-07 13:47:37 -07006560void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006561 // Only handle latency mode if:
6562 // - mBluetoothLatencyModesEnabled is true
6563 // - the HAL supports latency modes
6564 // - the selected device is Bluetooth LE or A2DP
6565 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6566 return;
6567 }
6568 if (mOutDeviceTypeAddrs.size() != 1
6569 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6570 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6571 return;
6572 }
6573
6574 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6575 if (mSupportedLatencyModes.size() == 1) {
6576 // If the HAL only support one latency mode currently, confirm the choice
6577 latencyMode = mSupportedLatencyModes[0];
6578 } else if (mSupportedLatencyModes.size() > 1) {
6579 // Request low latency if:
6580 // - At least one active track is either:
6581 // - a fast track with gaming usage or
6582 // - a track with acessibility usage
6583 for (const auto& track : mActiveTracks) {
6584 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6585 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6586 latencyMode = AUDIO_LATENCY_MODE_LOW;
6587 break;
6588 }
6589 }
6590 }
6591
6592 if (latencyMode != mSetLatencyMode) {
6593 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6594 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6595 __func__, mId, toString(latencyMode).c_str(), status);
6596 if (status == NO_ERROR) {
6597 mSetLatencyMode = latencyMode;
6598 }
6599 }
6600}
6601
Andy Hungee58e4a2023-07-07 13:47:37 -07006602void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006603
6604 if (mOutput == nullptr || mOutput->stream == nullptr) {
6605 return;
6606 }
6607 std::vector<audio_latency_mode_t> latencyModes;
6608 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6609 if (status != NO_ERROR) {
6610 latencyModes.clear();
6611 }
6612 if (latencyModes != mSupportedLatencyModes) {
6613 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6614 __func__, mId, status, toString(latencyModes).c_str());
6615 mSupportedLatencyModes.swap(latencyModes);
6616 sendHalLatencyModesChangedEvent_l();
6617 }
6618}
6619
Andy Hungee58e4a2023-07-07 13:47:37 -07006620status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006621 std::vector<audio_latency_mode_t>* modes) {
6622 if (modes == nullptr) {
6623 return BAD_VALUE;
6624 }
Andy Hung972bec12023-08-31 16:13:39 -07006625 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006626 *modes = mSupportedLatencyModes;
6627 return NO_ERROR;
6628}
6629
Andy Hungee58e4a2023-07-07 13:47:37 -07006630void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006631 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006632 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006633 if (modes != mSupportedLatencyModes) {
6634 ALOGD("%s: thread(%d) supported latency modes: %s",
6635 __func__, mId, toString(modes).c_str());
6636 mSupportedLatencyModes.swap(modes);
6637 sendHalLatencyModesChangedEvent_l();
6638 }
6639}
6640
Andy Hungee58e4a2023-07-07 13:47:37 -07006641status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006642 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6643 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6644 return INVALID_OPERATION;
6645 }
6646 mBluetoothLatencyModesEnabled.store(enabled);
6647 return NO_ERROR;
6648}
6649
Eric Laurent81784c32012-11-19 14:55:58 -08006650// ----------------------------------------------------------------------------
6651
Andy Hungee58e4a2023-07-07 13:47:37 -07006652/* static */
6653sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006654 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006655 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6656 const audio_offload_info_t& offloadInfo) {
6657 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006658 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006659}
6660
Andy Hung583043b2023-07-17 17:05:00 -07006661DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006662 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6663 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006664 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006665 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006666{
Andy Hung583043b2023-07-17 17:05:00 -07006667 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006668}
6669
Andy Hungee58e4a2023-07-07 13:47:37 -07006670DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006671{
6672}
6673
Andy Hungee58e4a2023-07-07 13:47:37 -07006674void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006675{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006676 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006677 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6678 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6679}
6680
Andy Hungee58e4a2023-07-07 13:47:37 -07006681void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006682{
Andy Hung972bec12023-08-31 16:13:39 -07006683 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006684 if (mMasterBalance != balance) {
6685 mMasterBalance.store(balance);
6686 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6687 broadcast_l();
6688 }
6689}
6690
Andy Hungee58e4a2023-07-07 13:47:37 -07006691void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006692{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006693 float left, right;
6694
Andy Hung333ab962019-05-28 20:23:35 -07006695 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006696 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006697
Andy Hung398ffa22022-12-13 19:19:53 -08006698 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6699 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6700
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006701 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6702 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006703
6704 const int64_t volumeShaperFrames =
6705 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6706 const auto [shaperVolume, shaperActive] =
6707 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006708 mVolumeShaperActive = shaperActive;
6709
Vlad Popae2f5aef2022-07-25 16:00:20 +02006710 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6711 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6712 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6713
6714 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6715
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006716 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006717 left = right = 0;
6718 } else {
6719 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006720 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006721
Glenn Kastenc56f3422014-03-21 17:53:17 -07006722 if (left > GAIN_FLOAT_UNITY) {
6723 left = GAIN_FLOAT_UNITY;
6724 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006725 if (right > GAIN_FLOAT_UNITY) {
6726 right = GAIN_FLOAT_UNITY;
6727 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006728 left *= v;
6729 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006730 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006731 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6732 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6733 right *= mMasterBalanceRight;
6734 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006735 }
6736
Andy Hung583043b2023-07-17 17:05:00 -07006737 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006738 /*muteState=*/{mMasterMute,
6739 mStreamTypes[track->streamType()].volume == 0.f,
6740 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006741 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006742 clientVolumeMute,
6743 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006744
Eric Laurentbfb1b832013-01-07 09:53:42 -08006745 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006746 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006747 if (left != mLeftVolFloat || right != mRightVolFloat) {
6748 mLeftVolFloat = left;
6749 mRightVolFloat = right;
6750
Eric Laurentbfb1b832013-01-07 09:53:42 -08006751 // Delegate volume control to effect in track effect chain if needed
6752 // only one effect chain can be present on DirectOutputThread, so if
6753 // there is one, the track is connected to it
6754 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006755 // if effect chain exists, volume is handled by it.
6756 // Convert volumes from float to 8.24
6757 uint32_t vl = (uint32_t)(left * (1 << 24));
6758 uint32_t vr = (uint32_t)(right * (1 << 24));
Shunkai Yaof4847652024-01-12 00:25:20 +00006759 // Direct/Offload effect chains set output volume in setVolume().
6760 (void)mEffectChains[0]->setVolume(&vl, &vr);
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006761 } else {
6762 // otherwise we directly set the volume.
6763 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006764 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006765 }
6766 }
6767}
6768
Andy Hungee58e4a2023-07-07 13:47:37 -07006769void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006770{
Andy Hung8d31fd22023-06-26 19:20:57 -07006771 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6772 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006773
Eric Laurent0f0631e2015-07-06 18:01:25 -07006774 if (previousTrack != 0 && latestTrack != 0) {
6775 if (mType == DIRECT) {
6776 if (previousTrack.get() != latestTrack.get()) {
6777 mFlushPending = true;
6778 }
6779 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006780 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6781 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006782 mFlushPending = true;
6783 }
6784 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006785 } else if (previousTrack == 0) {
6786 // there could be an old track added back during track transition for direct
6787 // output, so always issues flush to flush data of the previous track if it
6788 // was already destroyed with HAL paused, then flush can resume the playback
6789 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006790 }
6791 PlaybackThread::onAddNewTrack_l();
6792}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006793
Andy Hungee58e4a2023-07-07 13:47:37 -07006794PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006795 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006796)
6797{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006798 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006799 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006800 bool doHwPause = false;
6801 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006802
6803 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006804 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006805 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006806 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006807 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006808 continue;
6809 }
6810
Andy Hung8d31fd22023-06-26 19:20:57 -07006811 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006812#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006813 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006814#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006815 // Only consider last track started for volume and mixer state control.
6816 // In theory an older track could underrun and restart after the new one starts
6817 // but as we only care about the transition phase between two tracks on a
6818 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006819 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006820 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006821
Kuowei Li23666472021-01-20 10:23:25 +08006822 if (track->isPausePending()) {
6823 track->pauseAck();
6824 // It is possible a track might have been flushed or stopped.
6825 // Other operations such as flush pending might occur on the next prepare.
6826 if (track->isPausing()) {
6827 track->setPaused();
6828 }
6829 // Always perform pause, as an immediate flush will change
6830 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006831 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006832 doHwPause = true;
6833 mHwPaused = true;
6834 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006835 } else if (track->isFlushPending()) {
6836 track->flushAck();
6837 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006838 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006839 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006840 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006841 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006842 if (last) {
6843 mLeftVolFloat = mRightVolFloat = -1.0;
6844 if (mHwPaused) {
6845 doHwResume = true;
6846 mHwPaused = false;
6847 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006848 }
6849 }
6850
Eric Laurent81784c32012-11-19 14:55:58 -08006851 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006852 // for all its buffers to be filled before processing it.
6853 // Allow draining the buffer in case the client
6854 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006855 // hence the test on (track->retryCount() > 1).
6856 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006857 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6858 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006859 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006860
6861 // target retry count that we will use is based on the time we wait for retries.
6862 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6863 // the retry threshold is when we accept any size for PCM data. This is slightly
6864 // smaller than the retry count so we can push small bits of data without a glitch.
6865 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006866 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006867 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006868 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006869 minFrames = mNormalFrameCount;
6870 } else {
6871 minFrames = 1;
6872 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006873
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006874 const size_t framesReady = track->framesReady();
6875 const int trackId = track->id();
6876 if (ATRACE_ENABLED()) {
6877 std::string traceName("nRdy");
6878 traceName += std::to_string(trackId);
6879 ATRACE_INT(traceName.c_str(), framesReady);
6880 }
6881 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006882 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006883 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006884 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006885
Andy Hung8d31fd22023-06-26 19:20:57 -07006886 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6887 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006888 if (last) {
6889 // make sure processVolume_l() will apply new volume even if 0
6890 mLeftVolFloat = mRightVolFloat = -1.0;
6891 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006892 if (!mHwSupportsPause) {
6893 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006894 }
6895 }
6896
6897 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006898 processVolume_l(track, last);
6899 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006900 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006901 if (previousTrack != 0) {
6902 if (track != previousTrack.get()) {
6903 // Flush any data still being written from last track
6904 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006905 // Invalidate previous track to force a seek when resuming.
6906 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006907 }
6908 }
6909 mPreviousTrack = track;
6910
Eric Laurentd595b7c2013-04-03 17:27:56 -07006911 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006912 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006913 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006914 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006915 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006916 doHwResume = true;
6917 mHwPaused = false;
6918 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006919 }
Eric Laurent81784c32012-11-19 14:55:58 -08006920 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006921 // clear effect chain input buffer if the last active track started underruns
6922 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006923 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006924 mEffectChains[0]->clearInputBuffer();
6925 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006926 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006927 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006928 if (last && mHwPaused) {
6929 doHwResume = true;
6930 mHwPaused = false;
6931 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006932 }
6933 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6934 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006935 // We have consumed all the buffers of this track.
6936 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006937 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006938 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006939 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006940 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006941 if (presComplete) {
6942 mOutput->presentationComplete();
6943 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006944 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006945 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006946 }
Eric Laurent81784c32012-11-19 14:55:58 -08006947 if (track->isStopped()) {
6948 track->reset();
6949 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006950 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006951 }
6952 } else {
6953 // No buffers for this track. Give it a few chances to
6954 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006955 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006956 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006957 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006958 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006959 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006960 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006961 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00006962 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
6963 " underrun on thread %d", __func__, trackId, mId);
ziyangch8f194f12021-12-01 13:48:04 -08006964 tracksToRemove->add(track);
6965 // indicate to client process that the track was disabled because of
6966 // underrun; it will then automatically call start() when data is available
6967 track->disable();
6968 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6969 // unlike mixerthread, HAL can be paused for direct output
6970 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6971 "minFrames = %u, mFormat = %#x",
6972 framesReady, minFrames, mFormat);
6973 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6974 doHwPause = true;
6975 mHwPaused = true;
6976 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006977 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006978 } else if (last) {
6979 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006980 }
6981 }
6982 }
6983 }
6984
Eric Laurentd1f69b02014-12-15 14:33:13 -08006985 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006986 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006987 for (size_t i = 0; i < mTracks.size(); i++) {
6988 if (mTracks[i]->isFlushPending()) {
6989 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006990 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006991 }
6992 }
6993 }
6994
6995 // make sure the pause/flush/resume sequence is executed in the right order.
6996 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6997 // before flush and then resume HW. This can happen in case of pause/flush/resume
6998 // if resume is received before pause is executed.
6999 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07007000 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007001 status_t result = mOutput->stream->pause();
7002 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007003 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007004 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007005 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007006 flushHw_l();
7007 }
7008 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007009 status_t result = mOutput->stream->resume();
7010 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007011 }
Eric Laurent81784c32012-11-19 14:55:58 -08007012 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08007013 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08007014
7015 return mixerStatus;
7016}
7017
Andy Hungee58e4a2023-07-07 13:47:37 -07007018void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007019{
Eric Laurent81784c32012-11-19 14:55:58 -08007020 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08007021 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007022 // output audio to hardware
7023 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07007024 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08007025 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08007026 status_t status = mActiveTrack->getNextBuffer(&buffer);
7027 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08007028 // no need to pad with 0 for compressed audio
7029 if (audio_has_proportional_frames(mFormat)) {
7030 memset(curBuf, 0, frameCount * mFrameSize);
7031 }
Eric Laurent81784c32012-11-19 14:55:58 -08007032 break;
7033 }
7034 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
7035 frameCount -= buffer.frameCount;
7036 curBuf += buffer.frameCount * mFrameSize;
7037 mActiveTrack->releaseBuffer(&buffer);
7038 }
Andy Hung2098f272014-02-27 14:00:06 -08007039 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007040 mSleepTimeUs = 0;
7041 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007042 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007043}
7044
Andy Hungee58e4a2023-07-07 13:47:37 -07007045void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007046{
Eric Laurentd1f69b02014-12-15 14:33:13 -08007047 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08007048 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007049 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007050 return;
7051 }
Andy Hung85ba3332021-04-27 17:40:26 -07007052 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7053 mSleepTimeUs = mActiveSleepTimeUs;
7054 } else {
7055 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007056 }
Andy Hung85ba3332021-04-27 17:40:26 -07007057 // Note: In S or later, we do not write zeroes for
7058 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08007059}
7060
Andy Hungee58e4a2023-07-07 13:47:37 -07007061void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007062{
7063 {
Andy Hung972bec12023-08-31 16:13:39 -07007064 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08007065 for (size_t i = 0; i < mTracks.size(); i++) {
7066 if (mTracks[i]->isFlushPending()) {
7067 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07007068 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007069 }
7070 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07007071 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08007072 flushHw_l();
7073 }
7074 }
7075 PlaybackThread::threadLoop_exit();
7076}
7077
7078// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007079bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08007080{
7081 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07007082 bool trackStopped = false;
Eric Laurent022a5132024-04-12 17:02:51 +00007083 bool trackDisabled = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08007084
Eric Laurent022a5132024-04-12 17:02:51 +00007085 // do not put the HAL in standby when paused. NuPlayer clear the offloaded AudioTrack
Eric Laurentd1f69b02014-12-15 14:33:13 -08007086 // after a timeout and we will enter standby then.
Eric Laurent022a5132024-04-12 17:02:51 +00007087 // On offload threads, do not enter standby if the main track is still underrunning.
Eric Laurentd1f69b02014-12-15 14:33:13 -08007088 if (mTracks.size() > 0) {
Eric Laurent022a5132024-04-12 17:02:51 +00007089 const auto& mainTrack = mTracks[mTracks.size() - 1];
7090
7091 trackPaused = mainTrack->isPaused();
7092 trackStopped = mainTrack->isStopped() || mainTrack->state() == IAfTrackBase::IDLE;
7093 trackDisabled = (mType == OFFLOAD) && mainTrack->isDisabled();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007094 }
7095
Eric Laurent022a5132024-04-12 17:02:51 +00007096 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped) || trackDisabled);
Eric Laurentd1f69b02014-12-15 14:33:13 -08007097}
7098
Andy Hungc5007f82023-08-29 14:26:09 -07007099// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07007100bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07007101 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08007102{
7103 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07007104 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08007105
Eric Laurent10351942014-05-08 18:49:52 -07007106 AudioParameter param = AudioParameter(keyValuePair);
7107 int value;
7108 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07007109 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08007110 }
Eric Laurent10351942014-05-08 18:49:52 -07007111 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
7112 // do not accept frame count changes if tracks are open as the track buffer
7113 // size depends on frame count and correct behavior would not be garantied
7114 // if frame count is changed after track creation
7115 if (!mTracks.isEmpty()) {
7116 status = INVALID_OPERATION;
7117 } else {
7118 reconfig = true;
7119 }
7120 }
7121 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007122 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007123 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08007124 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07007125 if (!mStandby) {
7126 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007127 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007128 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007129 }
Eric Laurent10351942014-05-08 18:49:52 -07007130 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007131 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007132 }
7133 if (status == NO_ERROR && reconfig) {
7134 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007135 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007136 }
7137 }
7138
Dean Wheatley68918102021-03-19 22:09:19 +11007139 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007140}
7141
Andy Hungee58e4a2023-07-07 13:47:37 -07007142uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007143{
7144 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007145 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007146 time = PlaybackThread::activeSleepTimeUs();
7147 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007148 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007149 }
7150 return time;
7151}
7152
Andy Hungee58e4a2023-07-07 13:47:37 -07007153uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007154{
7155 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007156 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007157 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7158 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007159 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007160 }
7161 return time;
7162}
7163
Andy Hungee58e4a2023-07-07 13:47:37 -07007164uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007165{
7166 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007167 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007168 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7169 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007170 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007171 }
7172 return time;
7173}
7174
Andy Hungee58e4a2023-07-07 13:47:37 -07007175void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007176{
7177 PlaybackThread::cacheParameters_l();
7178
7179 // use shorter standby delay as on normal output to release
7180 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007181 // no delay on outputs with HW A/V sync
7182 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007183 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007184 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007185 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007186 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007187 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007188 }
Eric Laurent81784c32012-11-19 14:55:58 -08007189}
7190
Andy Hungee58e4a2023-07-07 13:47:37 -07007191void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007192{
ziyangch8f194f12021-12-01 13:48:04 -08007193 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007194 mOutput->flush();
Haofan Wang5f1ee2c2024-06-17 16:18:31 +00007195 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007196 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007197 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007198 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007199 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007200}
7201
Andy Hungee58e4a2023-07-07 13:47:37 -07007202int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007203 // If a VolumeShaper is active, we must wake up periodically to update volume.
7204 const int64_t NS_PER_MS = 1000000;
7205 return mVolumeShaperActive ?
7206 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7207}
7208
Eric Laurent81784c32012-11-19 14:55:58 -08007209// ----------------------------------------------------------------------------
7210
Andy Hungee58e4a2023-07-07 13:47:37 -07007211AsyncCallbackThread::AsyncCallbackThread(
7212 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007213 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007214 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007215 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007216 mDrainSequence(0),
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007217 mAsyncError(ASYNC_ERROR_NONE)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007218{
7219}
7220
Andy Hungee58e4a2023-07-07 13:47:37 -07007221void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007222{
7223 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7224}
7225
Andy Hungee58e4a2023-07-07 13:47:37 -07007226bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007227{
7228 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007229 uint32_t writeAckSequence;
7230 uint32_t drainSequence;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007231 AsyncError asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007232
7233 {
Andy Hungc5007f82023-08-29 14:26:09 -07007234 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007235 while (!((mWriteAckSequence & 1) ||
7236 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007237 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007238 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007239 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007240 }
7241
Eric Laurentbfb1b832013-01-07 09:53:42 -08007242 if (exitPending()) {
7243 break;
7244 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007245 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7246 mWriteAckSequence, mDrainSequence);
7247 writeAckSequence = mWriteAckSequence;
7248 mWriteAckSequence &= ~1;
7249 drainSequence = mDrainSequence;
7250 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007251 asyncError = mAsyncError;
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007252 mAsyncError = ASYNC_ERROR_NONE;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007253 }
7254 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007255 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007256 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007257 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007258 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007259 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007260 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007261 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007262 }
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007263 if (asyncError != ASYNC_ERROR_NONE) {
7264 playbackThread->onAsyncError(asyncError == ASYNC_ERROR_HARD);
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007265 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007266 }
7267 }
7268 }
7269 return false;
7270}
7271
Andy Hungee58e4a2023-07-07 13:47:37 -07007272void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007273{
7274 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007275 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007276 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007277 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007278}
7279
Andy Hungee58e4a2023-07-07 13:47:37 -07007280void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007281{
Andy Hung972bec12023-08-31 16:13:39 -07007282 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007283 // bit 0 is cleared
7284 mWriteAckSequence = sequence << 1;
7285}
7286
Andy Hungee58e4a2023-07-07 13:47:37 -07007287void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007288{
Andy Hung972bec12023-08-31 16:13:39 -07007289 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007290 // ignore unexpected callbacks
7291 if (mWriteAckSequence & 2) {
7292 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007293 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007294 }
7295}
7296
Andy Hungee58e4a2023-07-07 13:47:37 -07007297void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007298{
Andy Hung972bec12023-08-31 16:13:39 -07007299 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007300 // bit 0 is cleared
7301 mDrainSequence = sequence << 1;
7302}
7303
Andy Hungee58e4a2023-07-07 13:47:37 -07007304void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007305{
Andy Hung972bec12023-08-31 16:13:39 -07007306 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007307 // ignore unexpected callbacks
7308 if (mDrainSequence & 2) {
7309 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007310 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007311 }
7312}
7313
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007314void AsyncCallbackThread::setAsyncError(bool isHardError)
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007315{
Andy Hung972bec12023-08-31 16:13:39 -07007316 audio_utils::lock_guard _l(mutex());
Mikhail Naganovbf203ce2024-05-23 16:27:59 -07007317 mAsyncError = isHardError ? ASYNC_ERROR_HARD : ASYNC_ERROR_SOFT;
Andy Hungc5007f82023-08-29 14:26:09 -07007318 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007319}
7320
Eric Laurentbfb1b832013-01-07 09:53:42 -08007321
7322// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007323
7324/* static */
7325sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007326 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007327 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7328 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007329 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007330}
7331
Andy Hung583043b2023-07-17 17:05:00 -07007332OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007333 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7334 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007335 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007336 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007337{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007338 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007339 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007340 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007341}
7342
Andy Hungee58e4a2023-07-07 13:47:37 -07007343void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007344{
7345 if (mFlushPending || mHwPaused) {
7346 // If a flush is pending or track was paused, just discard buffered data
Andy Hungab65b182023-09-06 19:41:47 -07007347 audio_utils::lock_guard l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007348 flushHw_l();
7349 } else {
7350 mMixerStatus = MIXER_DRAIN_ALL;
7351 threadLoop_drain();
7352 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007353 if (mUseAsyncWrite) {
7354 ALOG_ASSERT(mCallbackThread != 0);
7355 mCallbackThread->exit();
7356 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007357 PlaybackThread::threadLoop_exit();
7358}
7359
Andy Hungee58e4a2023-07-07 13:47:37 -07007360PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007361 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007362)
7363{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007364 size_t count = mActiveTracks.size();
7365
7366 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007367 bool doHwPause = false;
7368 bool doHwResume = false;
7369
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007370 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007371
Eric Laurentbfb1b832013-01-07 09:53:42 -08007372 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007373 for (const sp<IAfTrack>& t : mActiveTracks) {
7374 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007375#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007376 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007377#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007378 // Only consider last track started for volume and mixer state control.
7379 // In theory an older track could underrun and restart after the new one starts
7380 // but as we only care about the transition phase between two tracks on a
7381 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007382 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007383 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007384
Haynes Mathew George7844f672014-01-15 12:32:55 -08007385 if (track->isInvalid()) {
7386 ALOGW("An invalidated track shouldn't be in active list");
7387 tracksToRemove->add(track);
7388 continue;
7389 }
7390
Andy Hung8d31fd22023-06-26 19:20:57 -07007391 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007392 ALOGW("An idle track shouldn't be in active list");
7393 continue;
7394 }
7395
Kuowei Li23666472021-01-20 10:23:25 +08007396 if (track->isPausePending()) {
7397 track->pauseAck();
7398 // It is possible a track might have been flushed or stopped.
7399 // Other operations such as flush pending might occur on the next prepare.
7400 if (track->isPausing()) {
7401 track->setPaused();
7402 }
7403 // Always perform pause if last, as an immediate flush will change
7404 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007405 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007406 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007407 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007408 mHwPaused = true;
7409 }
7410 // If we were part way through writing the mixbuffer to
7411 // the HAL we must save this until we resume
7412 // BUG - this will be wrong if a different track is made active,
7413 // in that case we want to discard the pending data in the
7414 // mixbuffer and tell the client to present it again when the
7415 // track is resumed
7416 mPausedWriteLength = mCurrentWriteLength;
7417 mPausedBytesRemaining = mBytesRemaining;
7418 mBytesRemaining = 0; // stop writing
7419 }
7420 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007421 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007422 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007423 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007424 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007425 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007426 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007427 track->flushAck();
7428 if (last) {
7429 mFlushPending = true;
7430 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007431 } else if (track->isResumePending()){
7432 track->resumeAck();
7433 if (last) {
7434 if (mPausedBytesRemaining) {
7435 // Need to continue write that was interrupted
7436 mCurrentWriteLength = mPausedWriteLength;
7437 mBytesRemaining = mPausedBytesRemaining;
7438 mPausedBytesRemaining = 0;
7439 }
7440 if (mHwPaused) {
7441 doHwResume = true;
7442 mHwPaused = false;
7443 // threadLoop_mix() will handle the case that we need to
7444 // resume an interrupted write
7445 }
7446 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007447 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007448
Eric Laurent3df841a2016-07-15 15:15:40 -07007449 mLeftVolFloat = mRightVolFloat = -1.0;
7450
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007451 // Do not handle new data in this iteration even if track->framesReady()
7452 mixerStatus = MIXER_TRACKS_ENABLED;
7453 }
7454 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007455 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007456 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007457 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7458 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007459 if (last) {
7460 // make sure processVolume_l() will apply new volume even if 0
7461 mLeftVolFloat = mRightVolFloat = -1.0;
7462 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007463 }
7464
7465 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007466 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007467 if (previousTrack != 0) {
7468 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007469 // Flush any data still being written from last track
7470 mBytesRemaining = 0;
7471 if (mPausedBytesRemaining) {
7472 // Last track was paused so we also need to flush saved
7473 // mixbuffer state and invalidate track so that it will
7474 // re-submit that unwritten data when it is next resumed
7475 mPausedBytesRemaining = 0;
7476 // Invalidate is a bit drastic - would be more efficient
7477 // to have a flag to tell client that some of the
7478 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007479 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007480 }
7481 // flush data already sent to the DSP if changing audio session as audio
7482 // comes from a different source. Also invalidate previous track to force a
7483 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007484 if (previousTrack->sessionId() != track->sessionId()) {
7485 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007486 }
7487 }
7488 }
7489 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007490 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007491 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007492 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007493 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007494 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007495 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007496 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007497 mixerStatus = MIXER_TRACKS_READY;
7498 }
7499 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007500 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007501 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007502 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007503 // Hardware buffer can hold a large amount of audio so we must
7504 // wait for all current track's data to drain before we say
7505 // that the track is stopped.
7506 if (mBytesRemaining == 0) {
7507 // Only start draining when all data in mixbuffer
7508 // has been written
7509 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007510 track->setState(IAfTrackBase::STOPPING_2);
7511 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007512 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7513 if (last && !mStandby) {
7514 // do not modify drain sequence if we are already draining. This happens
7515 // when resuming from pause after drain.
7516 if ((mDrainSequence & 1) == 0) {
7517 mSleepTimeUs = 0;
7518 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7519 mixerStatus = MIXER_DRAIN_TRACK;
7520 mDrainSequence += 2;
7521 }
7522 if (mHwPaused) {
7523 // It is possible to move from PAUSED to STOPPING_1 without
7524 // a resume so we must ensure hardware is running
7525 doHwResume = true;
7526 mHwPaused = false;
7527 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007528 }
7529 }
Eric Laurente93cc032016-05-05 10:15:10 -07007530 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007531 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007532 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007533 }
7534 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007535 // Drain has completed or we are in standby, signal presentation complete
7536 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007537 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007538 mOutput->presentationComplete();
7539 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007540 track->reset();
7541 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007542 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007543 if (!mUseAsyncWrite) {
7544 // If we don't get explicit drain notification we must
7545 // register discontinuity regardless of whether this is
7546 // the previous (!last) or the upcoming (last) track
7547 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007548 mTimestampVerifier.discontinuity(
7549 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007550 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007551 }
7552 } else {
7553 // No buffers for this track. Give it a few chances to
7554 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007555 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007556 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007557 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007558 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007559 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007560 } else {
Eric Laurent022a5132024-04-12 17:02:51 +00007561 ALOGI("%s BUFFER TIMEOUT: remove track(%d) from active list due to"
7562 " underrun on thread %d", __func__, track->id(), mId);
Andy Hungf8044752016-07-27 14:58:11 -07007563 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007564 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007565 // it will then automatically call start() when data is available
7566 track->disable();
7567 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007568 } else if (last){
7569 mixerStatus = MIXER_TRACKS_ENABLED;
7570 }
7571 }
7572 }
7573 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007574 if (track->isReady()) { // check ready to prevent premature start.
7575 processVolume_l(track, last);
7576 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007577 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007578
Eric Laurentea0fade2013-10-04 16:23:48 -07007579 // make sure the pause/flush/resume sequence is executed in the right order.
7580 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7581 // before flush and then resume HW. This can happen in case of pause/flush/resume
7582 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007583 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007584 status_t result = mOutput->stream->pause();
7585 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007586 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007587 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007588 if (mFlushPending) {
7589 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007590 }
Eric Laurentfd477972013-10-25 18:10:40 -07007591 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007592 status_t result = mOutput->stream->resume();
7593 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007594 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007595
Eric Laurentbfb1b832013-01-07 09:53:42 -08007596 // remove all the tracks that need to be...
7597 removeTracks_l(*tracksToRemove);
7598
7599 return mixerStatus;
7600}
7601
Eric Laurentbfb1b832013-01-07 09:53:42 -08007602// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007603bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007604{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007605 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7606 mWriteAckSequence, mDrainSequence);
7607 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007608 return true;
7609 }
7610 return false;
7611}
7612
Andy Hungee58e4a2023-07-07 13:47:37 -07007613bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007614{
Andy Hung972bec12023-08-31 16:13:39 -07007615 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007616 return waitingAsyncCallback_l();
7617}
7618
Andy Hungee58e4a2023-07-07 13:47:37 -07007619void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007620{
Eric Laurente659ef42014-09-29 13:06:46 -07007621 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007622 // Flush anything still waiting in the mixbuffer
7623 mCurrentWriteLength = 0;
7624 mBytesRemaining = 0;
7625 mPausedWriteLength = 0;
7626 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007627 // reset bytes written count to reflect that DSP buffers are empty after flush.
7628 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007629
Eric Laurentbfb1b832013-01-07 09:53:42 -08007630 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007631 // discard any pending drain or write ack by incrementing sequence
7632 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7633 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007634 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007635 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7636 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007637 }
7638}
7639
Andy Hungee58e4a2023-07-07 13:47:37 -07007640void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007641{
Andy Hung972bec12023-08-31 16:13:39 -07007642 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007643 if (PlaybackThread::invalidateTracks_l(streamType)) {
7644 mFlushPending = true;
7645 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007646}
7647
Andy Hungee58e4a2023-07-07 13:47:37 -07007648void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007649 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007650 if (PlaybackThread::invalidateTracks_l(portIds)) {
7651 mFlushPending = true;
7652 }
7653}
7654
Eric Laurentbfb1b832013-01-07 09:53:42 -08007655// ----------------------------------------------------------------------------
7656
Andy Hungee58e4a2023-07-07 13:47:37 -07007657/* static */
7658sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007659 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007660 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007661 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007662}
7663
Andy Hung583043b2023-07-17 17:05:00 -07007664DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007665 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007666 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007667 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007668 mWaitTimeMs(UINT_MAX)
7669{
7670 addOutputTrack(mainThread);
7671}
7672
Andy Hungee58e4a2023-07-07 13:47:37 -07007673DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007674{
7675 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7676 mOutputTracks[i]->destroy();
7677 }
7678}
7679
Andy Hungee58e4a2023-07-07 13:47:37 -07007680void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007681{
7682 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007683 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007684 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007685 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007686 if (mMixerBufferValid) {
7687 memset(mMixerBuffer, 0, mMixerBufferSize);
7688 } else {
7689 memset(mSinkBuffer, 0, mSinkBufferSize);
7690 }
Eric Laurent81784c32012-11-19 14:55:58 -08007691 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007692 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007693 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007694 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007695 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007696}
7697
Andy Hungee58e4a2023-07-07 13:47:37 -07007698void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007699{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007700 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007701 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007702 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007703 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007704 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007705 }
7706 } else if (mBytesWritten != 0) {
7707 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7708 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007709 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007710 } else {
7711 // flush remaining overflow buffers in output tracks
7712 writeFrames = 0;
7713 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007714 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007715 }
7716}
7717
Andy Hungee58e4a2023-07-07 13:47:37 -07007718ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007719{
7720 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007721 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7722
7723 // Consider the first OutputTrack for timestamp and frame counting.
7724
7725 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7726 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7727 // we always claim success.
7728 if (i == 0) {
7729 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7730 ALOGD_IF(correction != 0 && writeFrames != 0,
7731 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7732 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7733 mFramesWritten -= correction;
7734 }
7735
7736 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007737 }
Andy Hungcf10d742020-04-28 15:38:24 -07007738 if (mStandby) {
7739 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007740 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007741 mStandby = false;
7742 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007743 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007744}
7745
Andy Hungee58e4a2023-07-07 13:47:37 -07007746void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007747{
7748 // DuplicatingThread implements standby by stopping all tracks
7749 for (size_t i = 0; i < outputTracks.size(); i++) {
7750 outputTracks[i]->stop();
7751 }
7752}
7753
Andy Hung8a5abfd2023-12-07 19:35:12 -08007754void DuplicatingThread::threadLoop_exit()
7755{
7756 // Prevent calling the OutputTrack dtor in the DuplicatingThread dtor
7757 // where other mutexes (i.e. AudioPolicyService_Mutex) may be held.
7758 // Do so here in the threadLoop_exit().
7759
7760 SortedVector <sp<IAfOutputTrack>> localTracks;
7761 {
7762 audio_utils::lock_guard l(mutex());
7763 localTracks = std::move(mOutputTracks);
7764 mOutputTracks.clear();
7765 }
7766 localTracks.clear();
7767 outputTracks.clear();
7768 PlaybackThread::threadLoop_exit();
7769}
7770
Andy Hungee58e4a2023-07-07 13:47:37 -07007771void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007772{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007773 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007774
7775 std::stringstream ss;
7776 const size_t numTracks = mOutputTracks.size();
7777 ss << " " << numTracks << " OutputTracks";
7778 if (numTracks > 0) {
7779 ss << ":";
7780 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007781 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007782 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007783 if (thread.get() != nullptr) {
7784 ss << thread.get() << ", " << thread->id();
7785 } else {
7786 ss << "null";
7787 }
7788 ss << ")";
7789 }
7790 }
7791 ss << "\n";
7792 std::string result = ss.str();
7793 write(fd, result.c_str(), result.size());
7794}
7795
Andy Hungee58e4a2023-07-07 13:47:37 -07007796void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007797{
7798 outputTracks = mOutputTracks;
7799}
7800
Andy Hungee58e4a2023-07-07 13:47:37 -07007801void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007802{
7803 outputTracks.clear();
7804}
7805
Andy Hungee58e4a2023-07-07 13:47:37 -07007806void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007807{
Andy Hung972bec12023-08-31 16:13:39 -07007808 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007809 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7810 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7811 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7812 const size_t frameCount =
7813 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7814 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7815 // from different OutputTracks and their associated MixerThreads (e.g. one may
7816 // nearly empty and the other may be dropping data).
7817
Svet Ganov33761132021-05-13 22:51:08 +00007818 // TODO b/182392769: use attribution source util, move to server edge
7819 AttributionSourceState attributionSource = AttributionSourceState();
7820 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007821 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007822 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007823 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007824 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007825 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007826 this,
7827 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007828 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007829 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007830 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007831 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007832 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7833 if (status != NO_ERROR) {
7834 ALOGE("addOutputTrack() initCheck failed %d", status);
7835 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007836 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007837 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7838 mOutputTracks.add(outputTrack);
7839 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7840 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007841}
7842
Andy Hungee58e4a2023-07-07 13:47:37 -07007843void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007844{
Andy Hung972bec12023-08-31 16:13:39 -07007845 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007846 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7847 if (mOutputTracks[i]->thread() == thread) {
7848 mOutputTracks[i]->destroy();
7849 mOutputTracks.removeAt(i);
7850 updateWaitTime_l();
Andy Hung8d672e02023-09-15 18:19:28 -07007851 // NO_THREAD_SAFETY_ANALYSIS
7852 // Lambda workaround: as thread != this
7853 // we can safely call the remote thread getOutput.
7854 const bool equalOutput =
7855 [&](){ return thread->getOutput() == mOutput; }();
7856 if (equalOutput) {
7857 mOutput = nullptr;
Eric Laurentf6870ae2015-05-08 10:50:03 -07007858 }
Eric Laurent81784c32012-11-19 14:55:58 -08007859 return;
7860 }
7861 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007862 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007863}
7864
Andy Hungc5007f82023-08-29 14:26:09 -07007865// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007866void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007867{
7868 mWaitTimeMs = UINT_MAX;
7869 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007870 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007871 if (strong != 0) {
7872 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7873 if (waitTimeMs < mWaitTimeMs) {
7874 mWaitTimeMs = waitTimeMs;
7875 }
7876 }
7877 }
7878}
7879
Andy Hungee58e4a2023-07-07 13:47:37 -07007880bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007881{
7882 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007883 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007884 if (thread == 0) {
7885 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7886 outputTracks[i].get());
7887 return false;
7888 }
Andy Hung87c693c2023-07-06 20:56:16 -07007889 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007890 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007891 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007892 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7893 thread.get());
7894 return false;
7895 }
7896 }
7897 return true;
7898}
7899
Andy Hungee58e4a2023-07-07 13:47:37 -07007900void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007901 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007902{
Kevin Rocard12381092018-04-11 09:19:59 -07007903 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7904 outputTrack->setMetadatas(metadata.tracks);
7905 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007906}
7907
Andy Hungee58e4a2023-07-07 13:47:37 -07007908uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007909{
Andy Hung7a6a0f02023-11-29 13:42:08 -08007910 // return half the wait time in microseconds.
7911 return std::min(mWaitTimeMs * 500ULL, (unsigned long long)UINT32_MAX); // prevent overflow.
Eric Laurent81784c32012-11-19 14:55:58 -08007912}
7913
Andy Hungee58e4a2023-07-07 13:47:37 -07007914void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007915{
7916 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7917 updateWaitTime_l();
7918
7919 MixerThread::cacheParameters_l();
7920}
7921
Eric Laurentb3f315a2021-07-13 15:09:05 +02007922// ----------------------------------------------------------------------------
7923
Andy Hungee58e4a2023-07-07 13:47:37 -07007924/* static */
7925sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007926 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007927 AudioStreamOut* output,
7928 audio_io_handle_t id,
7929 bool systemReady,
7930 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007931 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007932}
7933
Andy Hung583043b2023-07-17 17:05:00 -07007934SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007935 AudioStreamOut* output,
7936 audio_io_handle_t id,
7937 bool systemReady,
7938 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007939 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007940{
7941}
7942
Andy Hungee58e4a2023-07-07 13:47:37 -07007943void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007944 // if mSupportedLatencyModes is empty, the HAL stream does not support
7945 // latency mode control and we can exit.
7946 if (mSupportedLatencyModes.empty()) {
7947 return;
7948 }
Eric Laurent4c85e372024-02-23 16:50:06 +00007949 // Do not update the HAL latency mode if no track is active
7950 if (mActiveTracks.isEmpty()) {
7951 return;
7952 }
7953
Eric Laurent68a40a82022-05-03 18:15:04 +02007954 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7955 if (mSupportedLatencyModes.size() == 1) {
7956 // If the HAL only support one latency mode currently, confirm the choice
7957 latencyMode = mSupportedLatencyModes[0];
7958 } else if (mSupportedLatencyModes.size() > 1) {
7959 // Request low latency if:
7960 // - The low latency mode is requested by the spatializer controller
7961 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7962 // AND
7963 // - At least one active track is spatialized
Eric Laurent68a40a82022-05-03 18:15:04 +02007964 for (const auto& track : mActiveTracks) {
7965 if (track->isSpatialized()) {
Eric Laurentb0241572024-02-01 21:03:49 +01007966 latencyMode = mRequestedLatencyMode;
Eric Laurent68a40a82022-05-03 18:15:04 +02007967 break;
7968 }
7969 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007970 }
7971
7972 if (latencyMode != mSetLatencyMode) {
7973 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007974 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7975 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007976 if (status == NO_ERROR) {
7977 mSetLatencyMode = latencyMode;
7978 }
7979 }
7980}
7981
Andy Hungee58e4a2023-07-07 13:47:37 -07007982status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurentb0241572024-02-01 21:03:49 +01007983 if (mode < 0 || mode >= AUDIO_LATENCY_MODE_CNT) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007984 return BAD_VALUE;
7985 }
Andy Hung972bec12023-08-31 16:13:39 -07007986 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007987 mRequestedLatencyMode = mode;
7988 return NO_ERROR;
7989}
7990
Andy Hungee58e4a2023-07-07 13:47:37 -07007991void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007992NO_THREAD_SAFETY_ANALYSIS
7993// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007994{
7995 bool hasVirtualizer = false;
7996 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007997 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007998 {
Andy Hung972bec12023-08-31 16:13:39 -07007999 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07008000 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008001 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02008002 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02008003 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
8004 }
8005
8006 finalDownMixer = mFinalDownMixer;
8007 mFinalDownMixer.clear();
8008 }
8009
8010 if (hasVirtualizer) {
8011 if (finalDownMixer != nullptr) {
8012 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008013 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008014 }
8015 finalDownMixer.clear();
8016 } else if (!hasDownMixer) {
8017 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07008018 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02008019 EFFECT_UIID_DOWNMIX, &descriptors);
8020 if (status != NO_ERROR) {
8021 return;
8022 }
8023 ALOG_ASSERT(!descriptors.empty(),
8024 "%s getDescriptors() returned no error but empty list", __func__);
8025
8026 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
8027 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02008028 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008029
8030 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
8031 ALOGW("%s error creating downmixer %d", __func__, status);
8032 finalDownMixer.clear();
8033 } else {
8034 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07008035 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02008036 }
8037 }
8038
8039 {
Andy Hung972bec12023-08-31 16:13:39 -07008040 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02008041 mFinalDownMixer = finalDownMixer;
8042 }
8043}
8044
Andy Hunge2514462023-12-06 14:59:24 -08008045void SpatializerThread::threadLoop_exit()
8046{
8047 // The Spatializer EffectHandle must be released on the PlaybackThread
8048 // threadLoop() to prevent lock inversion in the SpatializerThread dtor.
8049 mFinalDownMixer.clear();
8050
8051 PlaybackThread::threadLoop_exit();
8052}
8053
Eric Laurent81784c32012-11-19 14:55:58 -08008054// ----------------------------------------------------------------------------
8055// Record
8056// ----------------------------------------------------------------------------
8057
Andy Hung583043b2023-07-17 17:05:00 -07008058sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07008059 AudioStreamIn* input,
8060 audio_io_handle_t id,
8061 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07008062 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07008063}
8064
Andy Hung583043b2023-07-17 17:05:00 -07008065RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08008066 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08008067 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07008068 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08008069 ) :
Andy Hung583043b2023-07-17 17:05:00 -07008070 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008071 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07008072 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008073 mActiveTracks(&this->mLocalLog),
8074 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07008075 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008076 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07008077 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
8078 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008079 // mFastCapture below
8080 , mFastCaptureFutex(0)
8081 // mInputSource
8082 // mPipeSink
8083 // mPipeSource
8084 , mPipeFramesP2(0)
8085 // mPipeMemory
8086 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008087 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07008088 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08008089{
Glenn Kastend7dca052015-03-05 16:05:54 -08008090 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07008091 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08008092
George Burgess IVa8f90c12020-05-14 11:27:19 -07008093 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07008094 mIsMsdDevice = strcmp(
8095 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
8096 }
8097
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008098 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008099
Andy Hungc8fddf32018-08-08 18:32:37 -07008100 // TODO: We may also match on address as well as device type for
8101 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07008102 // TODO: This property should be ensure that only contains one single device type.
8103 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
8104 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07008105 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
8106 : AUDIO_DEVICE_NONE));
8107
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008108 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07008109 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008110 size_t numCounterOffers = 0;
8111 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008112#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08008113 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07008114#else
8115 (void)
8116#endif
8117 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008118 ALOG_ASSERT(index == 0);
8119
8120 // initialize fast capture depending on configuration
8121 bool initFastCapture;
8122 switch (kUseFastCapture) {
8123 case FastCapture_Never:
8124 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008125 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008126 break;
8127 case FastCapture_Always:
8128 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008129 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008130 break;
8131 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11008132 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008133 && audio_is_linear_pcm(mFormat)
Sampath6fac2332022-12-16 17:34:37 +11008134 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Dean Wheatley8e5d9e42023-11-03 12:37:27 +11008135 ALOGV("%p kUseFastCapture = Static, format = 0x%x, (%lld * 1000) / %u vs %u, "
8136 "initFastCapture = %d, mIsMsdDevice = %d", this, mFormat, (long long)mFrameCount,
8137 mSampleRate, kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008138 break;
8139 // case FastCapture_Dynamic:
8140 }
8141
8142 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07008143 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008144 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07008145 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
8146 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008147 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008148 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008149 const sp<MemoryDealer> roHeap(readOnlyHeap());
8150 sp<IMemory> pipeMemory;
8151 if ((roHeap == 0) ||
8152 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07008153 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008154 ALOGE("not enough memory for pipe buffer size=%zu; "
8155 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
8156 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
8157 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008158 goto failed;
8159 }
8160 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8161 memset(pipeBuffer, 0, pipeSize);
8162 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07008163 const NBAIO_Format offersFast[1] = {format};
8164 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008165 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008166 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008167 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008168 mPipeSink = pipe;
8169 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07008170 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008171 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07008172 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008173 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008174 mPipeSource = pipeReader;
8175 mPipeFramesP2 = pipeFramesP2;
8176 mPipeMemory = pipeMemory;
8177
8178 // create fast capture
8179 mFastCapture = new FastCapture();
8180 FastCaptureStateQueue *sq = mFastCapture->sq();
8181#ifdef STATE_QUEUE_DUMP
8182 // FIXME
8183#endif
8184 FastCaptureState *state = sq->begin();
8185 state->mCblk = NULL;
8186 state->mInputSource = mInputSource.get();
8187 state->mInputSourceGen++;
8188 state->mPipeSink = pipe;
8189 state->mPipeSinkGen++;
8190 state->mFrameCount = mFrameCount;
8191 state->mCommand = FastCaptureState::COLD_IDLE;
8192 // already done in constructor initialization list
8193 //mFastCaptureFutex = 0;
8194 state->mColdFutexAddr = &mFastCaptureFutex;
8195 state->mColdGen++;
8196 state->mDumpState = &mFastCaptureDumpState;
8197#ifdef TEE_SINK
8198 // FIXME
8199#endif
Andy Hung583043b2023-07-17 17:05:00 -07008200 mFastCaptureNBLogWriter =
8201 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008202 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8203 sq->end();
8204 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8205
8206 // start the fast capture
8207 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8208 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008209 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008210 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008211#ifdef AUDIO_WATCHDOG
8212 // FIXME
8213#endif
8214
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008215 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008216 }
Andy Hung8946a282018-04-19 20:04:56 -07008217#ifdef TEE_SINK
8218 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8219 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8220#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008221failed: ;
8222
8223 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008224}
8225
Andy Hungee58e4a2023-07-07 13:47:37 -07008226RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008227{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008228 if (mFastCapture != 0) {
8229 FastCaptureStateQueue *sq = mFastCapture->sq();
8230 FastCaptureState *state = sq->begin();
8231 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8232 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8233 if (old == -1) {
8234 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8235 }
8236 }
8237 state->mCommand = FastCaptureState::EXIT;
8238 sq->end();
8239 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8240 mFastCapture->join();
8241 mFastCapture.clear();
8242 }
Andy Hung583043b2023-07-17 17:05:00 -07008243 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8244 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008245 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008246}
8247
Andy Hungee58e4a2023-07-07 13:47:37 -07008248void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008249{
Glenn Kastend7dca052015-03-05 16:05:54 -08008250 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008251}
8252
Andy Hungee58e4a2023-07-07 13:47:37 -07008253void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008254{
8255 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008256 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008257 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008258 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008259 track->invalidate();
8260 }
8261 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008262 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008263}
8264
Andy Hungee58e4a2023-07-07 13:47:37 -07008265bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008266{
Eric Laurent81784c32012-11-19 14:55:58 -08008267 nsecs_t lastWarning = 0;
8268
8269 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008270
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008271reacquire_wakelock:
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008272 {
Andy Hung972bec12023-08-31 16:13:39 -07008273 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008274 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008275 }
8276
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008277 // used to request a deferred sleep, to be executed later while mutex is unlocked
8278 uint32_t sleepUs = 0;
8279
Andy Hung95c94a22023-10-20 16:41:18 -07008280 // timestamp correction enable is determined under lock, used in processing step.
8281 bool timestampCorrectionEnabled = false;
8282
Andy Hung446f4df2019-02-21 12:26:41 -08008283 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8284
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008285 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008286 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung6e693662024-03-15 10:15:10 -07008287 // Note: these sp<> are released at the end of the for loop outside of the mutex() lock.
8288 sp<IAfRecordTrack> activeTrack;
Andy Hungef6d8ae2024-04-23 13:56:19 -07008289 std::vector<sp<IAfRecordTrack>> oldActiveTracks;
Andy Hung116bc262023-06-20 18:56:17 -07008290 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008291
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008292 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008293 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008294
Glenn Kasten735f45f2014-08-18 15:51:59 -07008295 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008296 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008297
Glenn Kasten735f45f2014-08-18 15:51:59 -07008298 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008299 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008300
Eric Laurent33403f02020-05-29 18:35:06 -07008301 bool silenceFastCapture = false;
8302
Andy Hungc5007f82023-08-29 14:26:09 -07008303 { // scope for mutex()
8304 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008305
Eric Laurent021cf962014-05-13 10:18:14 -07008306 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008307
Eric Laurent000a4192014-01-29 15:17:32 -08008308 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008309 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008310 if (exitPending()) {
8311 break;
8312 }
8313
Eric Laurent5c25d562016-07-13 17:17:45 -07008314 // sleep with mutex unlocked
8315 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008316 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008317 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008318 ATRACE_END();
8319 sleepUs = 0;
8320 continue;
8321 }
8322
Glenn Kasten2b806402013-11-20 16:37:38 -08008323 // if no active track(s), then standby and release wakelock
8324 size_t size = mActiveTracks.size();
8325 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008326 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008327 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008328 releaseWakeLock_l();
8329 ALOGV("RecordThread: loop stopping");
8330 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008331 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008332 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008333 goto reacquire_wakelock;
8334 }
8335
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008336 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008337 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008338 for (size_t i = 0; i < size; ) {
Andy Hungef6d8ae2024-04-23 13:56:19 -07008339 if (activeTrack) { // ensure track release is outside lock.
8340 oldActiveTracks.emplace_back(std::move(activeTrack));
8341 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008342 activeTrack = mActiveTracks[i];
8343 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008344 if (activeTrack->isFastTrack()) {
8345 ALOG_ASSERT(fastTrackToRemove == 0);
8346 fastTrackToRemove = activeTrack;
8347 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008348 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008349 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008350 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008351 continue;
8352 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008353
Andy Hung8d31fd22023-06-26 19:20:57 -07008354 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008355 switch (activeTrackState) {
8356
Andy Hung8d31fd22023-06-26 19:20:57 -07008357 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008358 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008359 activeTrack->setState(IAfTrackBase::PAUSED);
François Gaffie39634e42023-10-17 12:13:32 +02008360 if (activeTrack->isFastTrack()) {
8361 ALOGV("%s fast track is paused, thus removed from active list", __func__);
8362 // Keep a ref on fast track to wait for FastCapture thread to get updated
8363 // state before potential track removal
8364 fastTrackToRemove = activeTrack;
8365 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008366 doBroadcast = true;
8367 size--;
8368 continue;
8369
Andy Hung8d31fd22023-06-26 19:20:57 -07008370 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008371 sleepUs = 10000;
8372 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008373 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008374 continue;
8375
Andy Hung8d31fd22023-06-26 19:20:57 -07008376 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008377 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008378 if (mStandby) {
8379 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008380 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008381 mStandby = false;
8382 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008383 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008384 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008385 break;
8386
Andy Hung8d31fd22023-06-26 19:20:57 -07008387 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008388 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008389 break;
8390
Andy Hung8d31fd22023-06-26 19:20:57 -07008391 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8392 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8393 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008394 default:
Andy Hungce685402018-10-05 17:23:27 -07008395 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8396 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008397 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008398
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008399 if (activeTrack->isFastTrack()) {
8400 ALOG_ASSERT(!mFastTrackAvail);
8401 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008402 // if the active fast track is silenced either:
8403 // 1) silence the whole capture from fast capture buffer if this is
8404 // the only active track
8405 // 2) invalidate this track: this will cause the client to reconnect and possibly
8406 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008407 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008408 if (activeTrack->isSilenced()) {
8409 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008410 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008411 } else {
8412 silenceFastCapture = true;
8413 }
8414 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008415 // Invalidate fast tracks if access to audio history is required as this is not
8416 // possible with fast tracks. Once the fast track has been invalidated, no new
8417 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8418 if (mMaxSharedAudioHistoryMs != 0) {
8419 invalidate = true;
8420 }
8421 if (invalidate) {
8422 activeTrack->invalidate();
8423 ALOG_ASSERT(fastTrackToRemove == 0);
8424 fastTrackToRemove = activeTrack;
8425 removeTrack_l(activeTrack);
8426 mActiveTracks.remove(activeTrack);
8427 size--;
8428 continue;
8429 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008430 fastTrack = activeTrack;
8431 }
Eric Laurent33403f02020-05-29 18:35:06 -07008432
8433 activeTracks.add(activeTrack);
8434 i++;
8435
Glenn Kasten9e982352013-08-14 14:39:50 -07008436 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008437
Andy Hungab65b182023-09-06 19:41:47 -07008438 mActiveTracks.updatePowerState_l(this);
Andy Hungdae27702016-10-31 14:01:16 -07008439
Kevin Rocard069c2712018-03-29 19:09:14 -07008440 updateMetadata_l();
8441
Eric Laurent5c25d562016-07-13 17:17:45 -07008442 if (allStopped) {
8443 standbyIfNotAlreadyInStandby();
8444 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008445 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008446 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008447 }
8448
8449 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008450 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008451 if (sleepUs == 0) {
8452 sleepUs = kRecordThreadSleepUs;
8453 }
8454 continue;
8455 }
8456 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008457
Andy Hung95c94a22023-10-20 16:41:18 -07008458 timestampCorrectionEnabled = isTimestampCorrectionEnabled_l();
Eric Laurent81784c32012-11-19 14:55:58 -08008459 lockEffectChains_l(effectChains);
8460 }
8461
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008462 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008463
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008464 size_t size = effectChains.size();
8465 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008466 // thread mutex is not locked, but effect chain is locked
8467 effectChains[i]->process_l();
8468 }
8469
Glenn Kasten735f45f2014-08-18 15:51:59 -07008470 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008471 if (mFastCapture != 0) {
8472 FastCaptureStateQueue *sq = mFastCapture->sq();
8473 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008474 bool didModify = false;
8475 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008476 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8477 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8478 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8479 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8480 if (old == -1) {
8481 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8482 }
8483 }
8484 state->mCommand = FastCaptureState::READ_WRITE;
8485#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008486 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008487 FastThreadDumpState::kSamplingNforLowRamDevice :
8488 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008489#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008490 didModify = true;
8491 }
8492 audio_track_cblk_t *cblkOld = state->mCblk;
8493 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8494 if (cblkNew != cblkOld) {
8495 state->mCblk = cblkNew;
8496 // block until acked if removing a fast track
8497 if (cblkOld != NULL) {
8498 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8499 }
8500 didModify = true;
8501 }
jiabin01c8f562018-07-19 17:47:28 -07008502 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8503 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8504 if (state->mFastPatchRecordBufferProvider != abp) {
8505 state->mFastPatchRecordBufferProvider = abp;
8506 state->mFastPatchRecordFormat = fastTrack == 0 ?
8507 AUDIO_FORMAT_INVALID : fastTrack->format();
8508 didModify = true;
8509 }
Eric Laurent33403f02020-05-29 18:35:06 -07008510 if (state->mSilenceCapture != silenceFastCapture) {
8511 state->mSilenceCapture = silenceFastCapture;
8512 didModify = true;
8513 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008514 sq->end(didModify);
8515 if (didModify) {
8516 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008517#if 0
8518 if (kUseFastCapture == FastCapture_Dynamic) {
8519 mNormalSource = mPipeSource;
8520 }
8521#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008522 }
8523 }
8524
Glenn Kasten735f45f2014-08-18 15:51:59 -07008525 // now run the fast track destructor with thread mutex unlocked
8526 fastTrackToRemove.clear();
8527
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008528 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8529 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8530 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8531 // If destination is non-contiguous, first read past the nominal end of buffer, then
8532 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008533
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008534 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008535 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008536 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008537
8538 // If an NBAIO source is present, use it to read the normal capture's data
8539 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008540 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008541
8542 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8543 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8544 // we immediately retry the read() to get data and prevent another overflow.
8545 for (int retries = 0; retries <= 2; ++retries) {
8546 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8547 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8548 framesToRead);
8549 if (framesRead != OVERRUN) break;
8550 }
8551
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008552 const ssize_t availableToRead = mPipeSource->availableToRead();
8553 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008554 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008555 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008556 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8557 "more frames to read than fifo size, %zd > %zu",
8558 availableToRead, mPipeFramesP2);
8559 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8560 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8561 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8562 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008563 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8564 }
8565 if (framesRead < 0) {
8566 status_t status = (status_t) framesRead;
8567 switch (status) {
8568 case OVERRUN:
8569 ALOGW("overrun on read from pipe");
8570 framesRead = 0;
8571 break;
8572 case NEGOTIATE:
8573 ALOGE("re-negotiation is needed");
8574 framesRead = -1; // Will cause an attempt to recover.
8575 break;
8576 default:
8577 ALOGE("unknown error %d on read from pipe", status);
8578 break;
8579 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008580 }
8581 // otherwise use the HAL / AudioStreamIn directly
8582 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008583 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008584 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008585 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008586 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008587 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008588 if (result < 0) {
8589 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008590 } else {
8591 framesRead = bytesRead / mFrameSize;
8592 }
8593 }
8594
Andy Hung446f4df2019-02-21 12:26:41 -08008595 const int64_t lastIoEndNs = systemTime(); // end IO timing
8596
Andy Hung3f0c9022016-01-15 17:49:46 -08008597 // Update server timestamp with server stats
8598 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008599 if (framesRead >= 0) {
8600 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8601 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8602 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008603
8604 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008605 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008606 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008607 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008608 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8609 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8610 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008611 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008612 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8613
8614 mTimestampVerifier.add(position, time, mSampleRate);
Andy Hungab65b182023-09-06 19:41:47 -07008615 if (timestampCorrectionEnabled) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008616 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008617 id(), (long long)time, (long long)position);
8618 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8619 position = correctedTimestamp.mFrames;
8620 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008621 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008622 id(), (long long)time, (long long)position);
8623 }
8624
Andy Hung3f0c9022016-01-15 17:49:46 -08008625 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8626 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8627 // Note: In general record buffers should tend to be empty in
8628 // a properly running pipeline.
8629 //
8630 // Also, it is not advantageous to call get_presentation_position during the read
8631 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008632 } else {
8633 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008634 }
8635 }
Andy Hunge6c37112019-02-26 17:38:10 -08008636
8637 // From the timestamp, input read latency is negative output write latency.
8638 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008639 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008640 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8641 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8642 mLatencyMs.add(latencyMs);
8643 }
8644
Andy Hung3f0c9022016-01-15 17:49:46 -08008645 // Use this to track timestamp information
8646 // ALOGD("%s", mTimestamp.toString().c_str());
8647
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008648 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008649 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008650 // Force input into standby so that it tries to recover at next read attempt
8651 inputStandBy();
8652 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008653 }
8654 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008655 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008656 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008657 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008658 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008659
Andy Hung8946a282018-04-19 20:04:56 -07008660#ifdef TEE_SINK
8661 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8662#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008663 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008664 {
8665 size_t part1 = mRsmpInFramesP2 - rear;
8666 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008667 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008668 (framesRead - part1) * mFrameSize);
8669 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008670 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008671 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008672
8673 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008674
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008675 // loop over each active track
8676 for (size_t i = 0; i < size; i++) {
Andy Hunge8c6c532024-06-17 15:42:48 -07008677 if (activeTrack) { // ensure track release is outside lock.
8678 oldActiveTracks.emplace_back(std::move(activeTrack));
8679 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008680 activeTrack = activeTracks[i];
8681
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008682 // skip fast tracks, as those are handled directly by FastCapture
8683 if (activeTrack->isFastTrack()) {
8684 continue;
8685 }
8686
Andy Hung73c02e42015-03-29 01:13:58 -07008687 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008688 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8689
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008690 enum {
8691 OVERRUN_UNKNOWN,
8692 OVERRUN_TRUE,
8693 OVERRUN_FALSE
8694 } overrun = OVERRUN_UNKNOWN;
8695
8696 // loop over getNextBuffer to handle circular sink
8697 for (;;) {
8698
Andy Hung8d31fd22023-06-26 19:20:57 -07008699 activeTrack->sinkBuffer().frameCount = ~0;
8700 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8701 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008702 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8703
Andy Hung73c02e42015-03-29 01:13:58 -07008704 // check available frames and handle overrun conditions
8705 // if the record track isn't draining fast enough.
8706 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008707 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008708 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008709 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008710 overrun = OVERRUN_TRUE;
8711 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008712 if (framesOut == 0 || framesIn == 0) {
8713 break;
8714 }
8715
Andy Hung6770c6f2015-04-07 13:43:36 -07008716 // Don't allow framesOut to be larger than what is possible with resampling
8717 // from framesIn.
8718 // This isn't strictly necessary but helps limit buffer resizing in
8719 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008720 if (audio_is_linear_pcm(activeTrack->format())) {
8721 framesOut = min(framesOut,
8722 destinationFramesPossible(
8723 framesIn, mSampleRate, activeTrack->sampleRate()));
8724 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008725
8726 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008727 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008728 // straight from RecordThread buffer to RecordTrack buffer.
8729 AudioBufferProvider::Buffer buffer;
8730 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008731 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008732 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008733 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008734 ALOGV_IF(buffer.frameCount != framesOut,
8735 "%s() read less than expected (%zu vs %zu)",
8736 __func__, buffer.frameCount, framesOut);
8737 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008738 memcpy(activeTrack->sinkBuffer().raw,
8739 buffer.raw, buffer.frameCount * mFrameSize);
8740 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008741 } else {
8742 framesOut = 0;
8743 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008744 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008745 }
8746 } else {
8747 // process frames from the RecordThread buffer provider to the RecordTrack
8748 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008749 framesOut = activeTrack->recordBufferConverter()->convert(
8750 activeTrack->sinkBuffer().raw,
8751 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008752 framesOut);
8753 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008754
8755 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8756 overrun = OVERRUN_FALSE;
8757 }
8758
Andy Hung93bb5732023-05-04 21:16:34 -07008759 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8760 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008761 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008762 if (framesToDrop == 0) {
8763 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008764 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008765 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008766 // Sanitize before releasing if the track has no access to the source data
8767 // An idle UID receives silence from non virtual devices until active
8768 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008769 memset(activeTrack->sinkBuffer().raw,
8770 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008771 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008772 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008773 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008774 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008775 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008776 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008777 }
8778 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008779
8780 switch (overrun) {
8781 case OVERRUN_TRUE:
8782 // client isn't retrieving buffers fast enough
8783 if (!activeTrack->setOverflow()) {
8784 nsecs_t now = systemTime();
8785 // FIXME should lastWarning per track?
8786 if ((now - lastWarning) > kWarningThrottleNs) {
8787 ALOGW("RecordThread: buffer overflow");
8788 lastWarning = now;
8789 }
8790 }
8791 break;
8792 case OVERRUN_FALSE:
8793 activeTrack->clearOverflow();
8794 break;
8795 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008796 break;
8797 }
8798
Andy Hung3f0c9022016-01-15 17:49:46 -08008799 // update frame information and push timestamp out
8800 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008801 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008802 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8803 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008804 }
8805
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008806unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008807 // enable changes in effect chain
8808 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008809 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008810 if (audio_has_proportional_frames(mFormat)
8811 && loopCount == lastLoopCountRead + 1) {
8812 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8813 const double jitterMs =
8814 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8815 {framesRead, readPeriodNs},
8816 {0, 0} /* lastTimestamp */, mSampleRate);
8817 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8818
Andy Hung972bec12023-08-31 16:13:39 -07008819 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008820 mIoJitterMs.add(jitterMs);
8821 mProcessTimeMs.add(processMs);
8822 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008823 mThreadloopExecutor.process();
Eric Laurentcccbc762019-04-05 14:20:05 -07008824 // update timing info.
8825 mLastIoBeginNs = lastIoBeginNs;
8826 mLastIoEndNs = lastIoEndNs;
8827 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008828 }
Andy Hung56ce2ed2024-06-12 16:03:16 -07008829 mThreadloopExecutor.process(); // process any remaining deferred actions.
8830 // deferred actions after this point are ignored.
Eric Laurent81784c32012-11-19 14:55:58 -08008831
Glenn Kasten93e471f2013-08-19 08:40:07 -07008832 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008833
8834 {
Andy Hung972bec12023-08-31 16:13:39 -07008835 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008836 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008837 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008838 track->invalidate();
8839 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008840 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008841 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008842 }
8843
8844 releaseWakeLock();
8845
8846 ALOGV("RecordThread %p exiting", this);
8847 return false;
8848}
8849
Andy Hungee58e4a2023-07-07 13:47:37 -07008850void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008851{
8852 if (!mStandby) {
8853 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008854 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008855 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008856 mStandby = true;
8857 }
8858}
8859
Andy Hungee58e4a2023-07-07 13:47:37 -07008860void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008861{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008862 // Idle the fast capture if it's currently running
8863 if (mFastCapture != 0) {
8864 FastCaptureStateQueue *sq = mFastCapture->sq();
8865 FastCaptureState *state = sq->begin();
8866 if (!(state->mCommand & FastCaptureState::IDLE)) {
8867 state->mCommand = FastCaptureState::COLD_IDLE;
8868 state->mColdFutexAddr = &mFastCaptureFutex;
8869 state->mColdGen++;
8870 mFastCaptureFutex = 0;
8871 sq->end();
8872 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8873 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8874#if 0
8875 if (kUseFastCapture == FastCapture_Dynamic) {
8876 // FIXME
8877 }
8878#endif
8879#ifdef AUDIO_WATCHDOG
8880 // FIXME
8881#endif
8882 } else {
8883 sq->end(false /*didModify*/);
8884 }
8885 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008886 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008887 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008888
8889 // If going into standby, flush the pipe source.
8890 if (mPipeSource.get() != nullptr) {
8891 const ssize_t flushed = mPipeSource->flush();
8892 if (flushed > 0) {
8893 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8894 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8895 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8896 }
8897 }
Eric Laurent81784c32012-11-19 14:55:58 -08008898}
8899
Andy Hungc5007f82023-08-29 14:26:09 -07008900// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008901sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008902 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008903 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008904 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008905 audio_format_t format,
8906 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008907 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008908 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008909 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008910 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008911 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008912 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008913 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008914 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008915 audio_port_handle_t portId,
8916 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008917{
Glenn Kasten74935e42013-12-19 08:56:45 -08008918 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008919 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008920 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008921 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008922 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008923 audio_input_flags_t requestedFlags = *flags;
8924 uint32_t sampleRate;
8925
8926 lStatus = initCheck();
8927 if (lStatus != NO_ERROR) {
8928 ALOGE("createRecordTrack_l() audio driver not initialized");
8929 goto Exit;
8930 }
8931
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008932 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8933 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8934 lStatus = BAD_VALUE;
8935 goto Exit;
8936 }
8937
Eric Laurentec376dc2021-04-08 20:41:22 +02008938 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008939 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008940 lStatus = PERMISSION_DENIED;
8941 goto Exit;
8942 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008943 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008944 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008945 lStatus = BAD_VALUE;
8946 goto Exit;
8947 }
8948 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008949 if (*pSampleRate == 0) {
8950 *pSampleRate = mSampleRate;
8951 }
8952 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008953
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008954 // special case for FAST flag considered OK if fast capture is present and access to
8955 // audio history is not required
8956 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008957 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8958 }
8959
Eric Laurentf14db3c2017-12-08 14:20:36 -08008960 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008961 if ((*flags & inputFlags) != *flags) {
8962 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8963 " input flags (%08x)",
8964 *flags, inputFlags);
8965 *flags = (audio_input_flags_t)(*flags & inputFlags);
8966 }
Eric Laurent81784c32012-11-19 14:55:58 -08008967
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008968 // client expresses a preference for FAST and no access to audio history,
8969 // but we get the final say
8970 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008971 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008972 // we formerly checked for a callback handler (non-0 tid),
8973 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008974 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008975 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008976 // Frame count is not specified (0), or is less than or equal the pipe depth.
8977 // It is OK to provide a higher capacity than requested.
8978 // We will force it to mPipeFramesP2 below.
8979 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008980 // PCM data
8981 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008982 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008983 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008984 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008985 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008986 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008987 hasFastCapture() &&
8988 // there are sufficient fast track slots available
8989 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008990 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008991 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008992 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008993 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008994 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008995 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008996 audio_input_flags_t old = *flags;
8997 chain->checkInputFlagCompatibility(flags);
8998 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008999 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
9000 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07009001 }
9002 }
Eric Laurent122f7e72016-06-29 11:53:29 -07009003 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009004 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
9005 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009006 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009007 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
9008 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009009 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07009010 this, frameCount, mFrameCount, mPipeFramesP2,
9011 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07009012 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07009013 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07009014 }
9015 }
9016
Eric Laurentf14db3c2017-12-08 14:20:36 -08009017 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
9018 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
9019 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
9020 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
9021 lStatus = BAD_TYPE;
9022 goto Exit;
9023 }
9024
Glenn Kasten74105912014-07-03 12:28:53 -07009025 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07009026 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07009027 // fast track: frame count is exactly the pipe depth
9028 frameCount = mPipeFramesP2;
9029 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08009030 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07009031 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009032 // not fast track: max notification period is resampled equivalent of one HAL buffer time
9033 // or 20 ms if there is a fast capture
9034 // TODO This could be a roundupRatio inline, and const
9035 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
9036 * sampleRate + mSampleRate - 1) / mSampleRate;
9037 // minimum number of notification periods is at least kMinNotifications,
9038 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
9039 static const size_t kMinNotifications = 3;
9040 static const uint32_t kMinMs = 30;
9041 // TODO This could be a roundupRatio inline
9042 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
9043 // TODO This could be a roundupRatio inline
9044 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
9045 maxNotificationFrames;
9046 const size_t minFrameCount = maxNotificationFrames *
9047 max(kMinNotifications, minNotificationsByMs);
9048 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08009049 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
9050 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07009051 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07009052 }
Glenn Kasten74935e42013-12-19 08:56:45 -08009053 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08009054 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08009055
Andy Hungc5007f82023-08-29 14:26:09 -07009056 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07009057 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02009058 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02009059 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01009060 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02009061 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01009062 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009063 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009064 }
Eric Laurent81784c32012-11-19 14:55:58 -08009065
Andy Hung8d31fd22023-06-26 19:20:57 -07009066 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07009067 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009068 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07009069 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00009070 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08009071
Glenn Kasten03003332013-08-06 15:40:54 -07009072 lStatus = track->initCheck();
9073 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07009074 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08009075 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08009076 goto Exit;
9077 }
9078 mTracks.add(track);
9079
Eric Laurent05067782016-06-01 18:27:28 -07009080 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07009081 pid_t callingPid = IPCThreadState::self()->getCallingPid();
9082 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
9083 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07009084 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07009085 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009086
9087 if (maxSharedAudioHistoryMs != 0) {
9088 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
9089 }
Eric Laurent81784c32012-11-19 14:55:58 -08009090 }
Glenn Kasten05997e22014-03-13 15:08:33 -07009091
Eric Laurent81784c32012-11-19 14:55:58 -08009092 lStatus = NO_ERROR;
9093
9094Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07009095 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08009096 return track;
9097}
9098
Andy Hungee58e4a2023-07-07 13:47:37 -07009099status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08009100 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08009101 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08009102{
9103 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
9104 sp<ThreadBase> strongMe = this;
9105 status_t status = NO_ERROR;
9106
9107 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08009108 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08009109 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009110 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07009111 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07009112 event, triggerSession,
9113 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08009114 }
9115
9116 {
Glenn Kasten47c20702013-08-13 15:37:35 -07009117 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07009118 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009119 if (recordTrack->isInvalid()) {
9120 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07009121 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
9122 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009123 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009124 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009125 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07009126 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
9127 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009128 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07009129 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009130 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07009131 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009132 }
9133 return status;
9134 }
9135
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009136 // TODO consider other ways of handling this, such as changing the state to :STARTING and
9137 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
9138 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07009139 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08009140 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009141 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009142 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08009143 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07009144 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07009145 if (recordTrack->isInvalid()) {
9146 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07009147 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
9148 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07009149 // STARTING_2 forces destroy to call stopInput.
9150 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07009151 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
9152 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07009153 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009154 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07009155 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07009156 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07009157 // Someone else has changed state, let them take over,
9158 // leave mState in the new state.
9159 recordTrack->clearSyncStartEvent();
9160 return INVALID_OPERATION;
9161 }
9162 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07009163 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07009164 ALOGW("%s(%d): startInput failed, status %d",
9165 __func__, recordTrack->id(), status);
9166 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
9167 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07009168 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07009169 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07009170 return status;
9171 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07009172 sendIoConfigEvent_l(
9173 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08009174 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07009175
9176 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
9177
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009178 // Catch up with current buffer indices if thread is already running.
9179 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9180 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9181 // see previously buffered data before it called start(), but with greater risk of overrun.
9182
Andy Hung8d31fd22023-06-26 19:20:57 -07009183 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009184 if (!recordTrack->isDirect()) {
9185 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07009186 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009187 }
Andy Hung8d31fd22023-06-26 19:20:57 -07009188 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009189 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07009190 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009191 return status;
9192 }
Eric Laurent81784c32012-11-19 14:55:58 -08009193}
9194
Andy Hungee58e4a2023-07-07 13:47:37 -07009195void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009196{
Andy Hungee58e4a2023-07-07 13:47:37 -07009197 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009198
9199 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009200 sp<IAfTrackBase> ptr =
9201 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9202 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009203 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009204 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009205 }
Eric Laurent81784c32012-11-19 14:55:58 -08009206 }
9207}
9208
Andy Hungee58e4a2023-07-07 13:47:37 -07009209bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009210 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009211 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009212 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009213 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009214 return false;
9215 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009216 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009217 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009218
Andy Hungabfab202019-03-07 19:45:54 -08009219 // NOTE: Waiting here is important to keep stop synchronous.
9220 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009221 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009222 mWaitWorkCV.notify_all(); // signal thread to stop
Andy Hung77b1bb42024-05-06 12:16:36 -07009223 mStartStopCV.wait(_l, getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08009224 }
Andy Hungce685402018-10-05 17:23:27 -07009225
Andy Hung8d31fd22023-06-26 19:20:57 -07009226 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009227 ALOGV("Record stopped OK");
9228 return true;
9229 }
Andy Hungce685402018-10-05 17:23:27 -07009230
9231 // don't handle anything - we've been invalidated or restarted and in a different state
9232 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009233 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009234 return false;
9235}
9236
Andy Hungee58e4a2023-07-07 13:47:37 -07009237bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009238{
9239 return false;
9240}
9241
Andy Hungee58e4a2023-07-07 13:47:37 -07009242status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009243{
9244#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9245 if (!isValidSyncEvent(event)) {
9246 return BAD_VALUE;
9247 }
9248
Glenn Kastend848eb42016-03-08 13:42:11 -08009249 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009250 status_t ret = NAME_NOT_FOUND;
9251
Andy Hung972bec12023-08-31 16:13:39 -07009252 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009253
9254 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009255 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009256 if (eventSession == track->sessionId()) {
9257 (void) track->setSyncEvent(event);
9258 ret = NO_ERROR;
9259 }
9260 }
9261 return ret;
9262#else
9263 return BAD_VALUE;
9264#endif
9265}
9266
Andy Hungee58e4a2023-07-07 13:47:37 -07009267status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009268 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009269{
9270 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009271 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009272 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009273 return NO_INIT;
9274 }
jiabin9ff780e2018-03-19 18:19:52 -07009275 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9276 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009277}
9278
Andy Hungee58e4a2023-07-07 13:47:37 -07009279status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009280 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009281{
Paul McLean12340082019-03-19 09:35:05 -06009282 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009283 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009284 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009285 return NO_INIT;
9286 }
Paul McLean12340082019-03-19 09:35:05 -06009287 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009288}
9289
Andy Hungee58e4a2023-07-07 13:47:37 -07009290status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009291{
Paul McLean12340082019-03-19 09:35:05 -06009292 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009293 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009294 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009295 return NO_INIT;
9296 }
Paul McLean12340082019-03-19 09:35:05 -06009297 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009298}
9299
Andy Hungee58e4a2023-07-07 13:47:37 -07009300status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009301 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9302 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009303 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009304 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9305}
9306
Andy Hungee58e4a2023-07-07 13:47:37 -07009307status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009308 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9309 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009310
Eric Laurentec376dc2021-04-08 20:41:22 +02009311 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9312 return BAD_VALUE;
9313 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009314
9315 if (sharedAudioStartMs < 0
9316 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009317 return BAD_VALUE;
9318 }
9319
Eric Laurent2407ce32021-04-26 14:56:03 +02009320 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9321 // As we cannot detect more than one wraparound, only accept values up current write position
9322 // after one wraparound
9323 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9324 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009325 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009326 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9327 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009328 // Bring the start frame position within the input buffer to match the documented
9329 // "best effort" behavior of the API.
9330 if (sharedOffset < 0) {
9331 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009332 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009333 sharedAudioStartFrames =
9334 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009335 }
9336
Eric Laurentec376dc2021-04-08 20:41:22 +02009337 mSharedAudioPackageName = sharedAudioPackageName;
9338 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009339 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009340 } else {
9341 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009342 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009343 }
9344 return NO_ERROR;
9345}
9346
Andy Hungee58e4a2023-07-07 13:47:37 -07009347void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009348 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9349 mSharedAudioStartFrames = -1;
9350 mSharedAudioPackageName = "";
9351}
9352
Andy Hungee58e4a2023-07-07 13:47:37 -07009353ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009354{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009355 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009356 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009357 }
9358 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009359 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009360 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009361 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009362 }
9363 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009364 MetadataUpdate change;
9365 change.recordMetadataUpdate = metadata.tracks;
9366 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009367}
9368
Andy Hungc5007f82023-08-29 14:26:09 -07009369// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009370void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009371{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009372 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009373 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009374
Eric Laurent81784c32012-11-19 14:55:58 -08009375 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009376 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009377 removeTrack_l(track);
9378 }
9379}
9380
Andy Hungee58e4a2023-07-07 13:47:37 -07009381void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009382{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009383 String8 result;
9384 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009385 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009386
Eric Laurent81784c32012-11-19 14:55:58 -08009387 mTracks.remove(track);
9388 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009389 if (track->isFastTrack()) {
9390 ALOG_ASSERT(!mFastTrackAvail);
9391 mFastTrackAvail = true;
9392 }
Eric Laurent81784c32012-11-19 14:55:58 -08009393}
9394
Andy Hungee58e4a2023-07-07 13:47:37 -07009395void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009396{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009397 AudioStreamIn *input = mInput;
9398 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9399 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009400 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009401 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009402 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009403 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009404 }
Andy Hungbfa64962017-06-12 14:43:19 -07009405
9406 if (input != nullptr) {
9407 dprintf(fd, " Hal stream dump:\n");
9408 (void)input->stream->dump(fd);
9409 }
9410
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009411 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009412 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009413
Glenn Kasten2f90c512015-12-02 11:40:09 -08009414 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9415 // while we are dumping it. It may be inconsistent, but it won't mutate!
9416 // This is a large object so we place it on the heap.
9417 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009418 const std::unique_ptr<FastCaptureDumpState> copy =
9419 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009420 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009421}
9422
Andy Hungee58e4a2023-07-07 13:47:37 -07009423void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009424{
Eric Laurent81784c32012-11-19 14:55:58 -08009425 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009426 size_t numtracks = mTracks.size();
9427 size_t numactive = mActiveTracks.size();
9428 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009429 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009430 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009431 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009432 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009433 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009434 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009435 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009436 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009437 if (track != 0) {
9438 bool active = mActiveTracks.indexOf(track) >= 0;
9439 if (active) {
9440 numactiveseen++;
9441 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009442 result.append(prefix);
9443 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009444 }
Eric Laurent81784c32012-11-19 14:55:58 -08009445 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009446 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009447 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009448 }
9449
Marco Nelissenb2208842014-02-07 14:00:50 -08009450 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009451 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009452 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009453 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009454 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009455 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009456 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009457 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009458 result.append(prefix);
9459 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009460 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009461 }
Eric Laurent81784c32012-11-19 14:55:58 -08009462
9463 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009464 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009465}
9466
Andy Hungee58e4a2023-07-07 13:47:37 -07009467void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009468{
Andy Hung972bec12023-08-31 16:13:39 -07009469 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009470 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009471 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009472 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009473 track->setSilenced(silenced);
9474 }
9475 }
9476}
Andy Hung73c02e42015-03-29 01:13:58 -07009477
Andy Hung8d31fd22023-06-26 19:20:57 -07009478void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009479{
Andy Hung87c693c2023-07-06 20:56:16 -07009480 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009481 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009482 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009483 const int32_t rear = recordThread->mRsmpInRear;
9484 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009485 if (mRecordTrack->startFrames() >= 0) {
9486 int32_t startFrames = mRecordTrack->startFrames();
9487 // Accept a recent wraparound of mRsmpInRear
9488 if (startFrames <= rear) {
9489 deltaFrames = rear - startFrames;
9490 } else {
9491 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009492 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009493 // start frame cannot be further in the past than start of resampling buffer
9494 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9495 deltaFrames = recordThread->mRsmpInFrames;
9496 }
9497 }
9498 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009499}
9500
Andy Hung8d31fd22023-06-26 19:20:57 -07009501void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009502 size_t *framesAvailable, bool *hasOverrun)
9503{
Andy Hung87c693c2023-07-06 20:56:16 -07009504 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009505 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009506 const int32_t rear = recordThread->mRsmpInRear;
9507 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009508 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009509
9510 size_t framesIn;
9511 bool overrun = false;
9512 if (filled < 0) {
9513 // should not happen, but treat like a massive overrun and re-sync
9514 framesIn = 0;
9515 mRsmpInFront = rear;
9516 overrun = true;
9517 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9518 framesIn = (size_t) filled;
9519 } else {
9520 // client is not keeping up with server, but give it latest data
9521 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009522 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9523 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009524 overrun = true;
9525 }
9526 if (framesAvailable != NULL) {
9527 *framesAvailable = framesIn;
9528 }
9529 if (hasOverrun != NULL) {
9530 *hasOverrun = overrun;
9531 }
9532}
9533
Eric Laurent81784c32012-11-19 14:55:58 -08009534// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009535status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009536 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009537{
Andy Hung87c693c2023-07-06 20:56:16 -07009538 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009539 if (threadBase == 0) {
9540 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009541 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009542 return NOT_ENOUGH_DATA;
9543 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009544 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009545 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009546 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009547 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009548 // FIXME should not be P2 (don't want to increase latency)
9549 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009550 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009551 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009552
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009553 front &= recordThread->mRsmpInFramesP2 - 1;
9554 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009555 if (part1 > (size_t) filled) {
9556 part1 = filled;
9557 }
9558 size_t ask = buffer->frameCount;
9559 ALOG_ASSERT(ask > 0);
9560 if (part1 > ask) {
9561 part1 = ask;
9562 }
9563 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009564 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009565 buffer->raw = NULL;
9566 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009567 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009568 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009569 }
9570
Andy Hung57446612015-04-19 23:56:46 -07009571 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009572 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009573 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009574 return NO_ERROR;
9575}
9576
9577// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009578void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009579 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009580{
Hongwei Wang95e37682019-04-12 11:13:36 -07009581 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009582 if (stepCount == 0) {
9583 return;
9584 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009585 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009586 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009587 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009588 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009589 buffer->frameCount = 0;
9590}
9591
Andy Hungee58e4a2023-07-07 13:47:37 -07009592void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009593{
Andy Hung972bec12023-08-31 16:13:39 -07009594 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009595 checkBtNrec_l();
9596}
9597
Andy Hungee58e4a2023-07-07 13:47:37 -07009598void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009599{
9600 // disable AEC and NS if the device is a BT SCO headset supporting those
9601 // pre processings
Andy Hungab65b182023-09-06 19:41:47 -07009602 bool suspend = audio_is_bluetooth_sco_device(inDeviceType_l()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009603 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009604 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9605 for (size_t i = 0; i < mEffectChains.size(); i++) {
9606 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9607 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9608 }
9609 }
9610}
9611
Andy Hung97a893e2015-03-29 01:03:07 -07009612
Andy Hungee58e4a2023-07-07 13:47:37 -07009613bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009614 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009615{
9616 bool reconfig = false;
9617
Eric Laurent10351942014-05-08 18:49:52 -07009618 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009619
Eric Laurent10351942014-05-08 18:49:52 -07009620 audio_format_t reqFormat = mFormat;
9621 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009622 // 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 +08009623 [[maybe_unused]] audio_channel_mask_t channelMask =
9624 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009625
9626 AudioParameter param = AudioParameter(keyValuePair);
9627 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009628
9629 // scope for AutoPark extends to end of method
9630 AutoPark<FastCapture> park(mFastCapture);
9631
Eric Laurent10351942014-05-08 18:49:52 -07009632 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9633 // channel count change can be requested. Do we mandate the first client defines the
9634 // HAL sampling rate and channel count or do we allow changes on the fly?
9635 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9636 samplingRate = value;
9637 reconfig = true;
9638 }
9639 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009640 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009641 status = BAD_VALUE;
9642 } else {
9643 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009644 reconfig = true;
9645 }
Eric Laurent10351942014-05-08 18:49:52 -07009646 }
9647 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9648 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009649 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009650 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009651 status = BAD_VALUE;
9652 } else {
9653 channelMask = mask;
9654 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009655 }
Eric Laurent10351942014-05-08 18:49:52 -07009656 }
9657 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9658 // do not accept frame count changes if tracks are open as the track buffer
9659 // size depends on frame count and correct behavior would not be guaranteed
9660 // if frame count is changed after track creation
9661 if (mActiveTracks.size() > 0) {
9662 status = INVALID_OPERATION;
9663 } else {
9664 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009665 }
Eric Laurent10351942014-05-08 18:49:52 -07009666 }
9667 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009668 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009669 }
9670 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9671 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009672 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009673 }
Glenn Kastene198c362013-08-13 09:13:36 -07009674
Eric Laurent10351942014-05-08 18:49:52 -07009675 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009676 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009677 if (status == INVALID_OPERATION) {
9678 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009679 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009680 }
9681 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009682 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009683 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9684 if (mInput->stream->getAudioProperties(&config) == OK &&
9685 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9686 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009687 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009688 status = NO_ERROR;
9689 }
Eric Laurent81784c32012-11-19 14:55:58 -08009690 }
Eric Laurent10351942014-05-08 18:49:52 -07009691 if (status == NO_ERROR) {
9692 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009693 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009694 }
9695 }
Eric Laurent81784c32012-11-19 14:55:58 -08009696 }
Eric Laurent10351942014-05-08 18:49:52 -07009697
Eric Laurent81784c32012-11-19 14:55:58 -08009698 return reconfig;
9699}
9700
Andy Hungee58e4a2023-07-07 13:47:37 -07009701String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009702{
Andy Hung972bec12023-08-31 16:13:39 -07009703 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009704 if (initCheck() == NO_ERROR) {
9705 String8 out_s8;
9706 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9707 return out_s8;
9708 }
Eric Laurent81784c32012-11-19 14:55:58 -08009709 }
Andy Hung920f6572022-10-06 12:09:49 -07009710 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009711}
9712
Andy Hungab65b182023-09-06 19:41:47 -07009713void RecordThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009714 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009715 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009716 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009717 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009718 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009719 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009720 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9721 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009722 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009723 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009724 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009725 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009726 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009727 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009728 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009729 break;
9730 }
Andy Hungab65b182023-09-06 19:41:47 -07009731 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009732}
9733
Andy Hungee58e4a2023-07-07 13:47:37 -07009734void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009735{
Dean Wheatley6c009512023-10-23 09:34:14 +11009736 const audio_config_base_t audioConfig = mInput->getAudioProperties();
9737 mSampleRate = audioConfig.sample_rate;
9738 mChannelMask = audioConfig.channel_mask;
9739 if (!audio_is_input_channel(mChannelMask)) {
9740 LOG_ALWAYS_FATAL("Channel mask %#x not valid for input", mChannelMask);
9741 }
9742
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009743 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
Dean Wheatley6c009512023-10-23 09:34:14 +11009744
9745 // Get actual HAL format.
9746 status_t result = mInput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
9747 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving input stream format: %d", result);
9748 // Get format from the shim, which will be different than the HAL format
9749 // if recording compressed audio from IEC61937 wrapped sources.
9750 mFormat = audioConfig.format;
9751 if (!audio_is_valid_format(mFormat)) {
9752 LOG_ALWAYS_FATAL("Format %#x not valid for input", mFormat);
9753 }
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009754 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009755 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9756 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009757 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009758 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009759 ALOGI("HAL format %#x is not linear pcm", mFormat);
9760 }
Dean Wheatley6c009512023-10-23 09:34:14 +11009761 mFrameSize = mInput->getFrameSize();
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009762 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9763 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009764 result = mInput->stream->getBufferSize(&mBufferSize);
9765 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009766 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009767 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9768 "mBufferSize=%zu, mFrameCount=%zu",
9769 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009770
Eric Laurentec376dc2021-04-08 20:41:22 +02009771 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9772 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009773 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009774
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009775 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9776 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009777
9778 audio_input_flags_t flags = mInput->flags;
9779 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9780 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009781 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009782 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9783 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9784 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9785 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9786 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9787 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009788}
9789
Andy Hungee58e4a2023-07-07 13:47:37 -07009790uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009791{
Andy Hung972bec12023-08-31 16:13:39 -07009792 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009793 uint32_t result;
9794 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9795 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009796 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009797 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009798}
9799
Andy Hungee58e4a2023-07-07 13:47:37 -07009800KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009801{
Glenn Kastend848eb42016-03-08 13:42:11 -08009802 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009803 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009804 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009805 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009806 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009807 if (ids.indexOfKey(sessionId) < 0) {
9808 ids.add(sessionId, true);
9809 }
9810 }
9811 return ids;
9812}
9813
Andy Hungee58e4a2023-07-07 13:47:37 -07009814AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009815{
Andy Hung972bec12023-08-31 16:13:39 -07009816 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009817 AudioStreamIn *input = mInput;
9818 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009819 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009820 return input;
9821}
9822
Andy Hungc5007f82023-08-29 14:26:09 -07009823// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009824sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009825{
9826 if (mInput == NULL) {
9827 return NULL;
9828 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009829 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009830}
9831
Andy Hungee58e4a2023-07-07 13:47:37 -07009832status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009833{
Eric Laurent81784c32012-11-19 14:55:58 -08009834 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009835 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009836 chain->setInBuffer(NULL);
9837 chain->setOutBuffer(NULL);
9838
9839 checkSuspendOnAddEffectChain_l(chain);
9840
Eric Laurent1b928682014-10-02 19:41:47 -07009841 // make sure enabled pre processing effects state is communicated to the HAL as we
9842 // just moved them to a new input stream.
Shunkai Yaod125e402024-01-20 03:19:06 +00009843 chain->syncHalEffectsState_l();
Eric Laurent1b928682014-10-02 19:41:47 -07009844
Eric Laurent81784c32012-11-19 14:55:58 -08009845 mEffectChains.add(chain);
9846
9847 return NO_ERROR;
9848}
9849
Andy Hungee58e4a2023-07-07 13:47:37 -07009850size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009851{
9852 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009853
9854 for (size_t i = 0; i < mEffectChains.size(); i++) {
9855 if (chain == mEffectChains[i]) {
9856 mEffectChains.removeAt(i);
9857 break;
9858 }
Eric Laurent81784c32012-11-19 14:55:58 -08009859 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009860 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009861}
9862
Andy Hungee58e4a2023-07-07 13:47:37 -07009863status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009864 audio_patch_handle_t *handle)
9865{
9866 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009867
9868 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009869 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009870 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009871 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009872 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009873 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009874 }
9875
Eric Laurentd8365c52017-07-16 15:27:05 -07009876 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009877
9878 // store new source and send to effects
9879 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9880 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009881 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009882 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009883 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009884 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009885
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009886 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009887 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9888 status = hwDevice->createAudioPatch(patch->num_sources,
9889 patch->sources,
9890 patch->num_sinks,
9891 patch->sinks,
9892 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009893 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009894 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9895 patch->sinks[0].ext.mix.usecase.source,
9896 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009897 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009898 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009899
jiabinc52b1ff2019-10-31 17:20:42 -07009900 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009901 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009902 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009903 }
Eric Laurent296fb132015-05-01 11:38:42 -07009904
Andy Hungc2b11cb2020-04-22 09:04:01 -07009905 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009906 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009907 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009908 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009909 // also dispatch to active AudioRecords
9910 for (const auto &track : mActiveTracks) {
9911 track->logEndInterval();
9912 track->logBeginInterval(pathSourcesAsString);
9913 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009914 // Force meteadata update after a route change
9915 mActiveTracks.setHasChanged();
9916
Eric Laurent1c333e22014-05-20 10:48:17 -07009917 return status;
9918}
9919
Andy Hungee58e4a2023-07-07 13:47:37 -07009920status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009921{
9922 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009923
jiabinc52b1ff2019-10-31 17:20:42 -07009924 mPatch = audio_patch{};
9925 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009926
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009927 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009928 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9929 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009930 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009931 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009932 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009933 // Force meteadata update after a route change
9934 mActiveTracks.setHasChanged();
9935
Eric Laurent1c333e22014-05-20 10:48:17 -07009936 return status;
9937}
9938
Andy Hungee58e4a2023-07-07 13:47:37 -07009939void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009940{
Andy Hung972bec12023-08-31 16:13:39 -07009941 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009942 mOutDevices = outDevices;
9943 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9944 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009945 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009946 }
9947}
9948
Andy Hungee58e4a2023-07-07 13:47:37 -07009949int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009950{
9951 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009952 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009953 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009954 int32_t oldestFront = mRsmpInRear;
9955 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009956 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009957 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009958 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009959 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009960 if (filled > maxFilled) {
9961 oldestFront = front;
9962 maxFilled = filled;
9963 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009964 }
Andy Hung920f6572022-10-06 12:09:49 -07009965 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009966 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9967 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009968 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009969}
9970
Andy Hungee58e4a2023-07-07 13:47:37 -07009971void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009972{
9973 if (offset == 0) {
9974 return;
9975 }
9976 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009977 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009978 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009979 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009980 }
9981}
9982
Andy Hungee58e4a2023-07-07 13:47:37 -07009983void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009984{
9985 // This is the formula for calculating the temporary buffer size.
9986 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9987 // 1 full output buffer, regardless of the alignment of the available input.
9988 // The value is somewhat arbitrary, and could probably be even larger.
9989 // A larger value should allow more old data to be read after a track calls start(),
9990 // without increasing latency.
9991 //
9992 // Note this is independent of the maximum downsampling ratio permitted for capture.
9993 size_t minRsmpInFrames = mFrameCount * 7;
9994
9995 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9996 // capture history available to another client using the same session ID:
9997 // dimension the resampler input buffer accordingly.
9998
9999 // Get oldest client read position: getOldestFront_l() must be called before altering
10000 // mRsmpInRear, or mRsmpInFrames
10001 int32_t previousFront = getOldestFront_l();
10002 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
10003 int32_t previousRear = mRsmpInRear;
10004 mRsmpInRear = 0;
10005
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010006 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -070010007 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010008 "resizeInputBuffer_l() called with invalid max shared history %d",
10009 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +020010010 if (maxSharedAudioHistoryMs != 0) {
10011 // resizeInputBuffer_l should never be called with a non zero shared history if the
10012 // buffer was not already allocated
10013 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
10014 "resizeInputBuffer_l() called with shared history and unallocated buffer");
10015 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
10016 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +020010017 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +020010018 return;
10019 }
10020 mRsmpInFrames = rsmpInFrames;
10021 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +020010022 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +020010023 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
10024 // initialized
10025 if (mRsmpInFrames < minRsmpInFrames) {
10026 mRsmpInFrames = minRsmpInFrames;
10027 }
10028 mRsmpInFramesP2 = roundup(mRsmpInFrames);
10029
10030 // TODO optimize audio capture buffer sizes ...
10031 // Here we calculate the size of the sliding buffer used as a source
10032 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
10033 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
10034 // be better to have it derived from the pipe depth in the long term.
10035 // The current value is higher than necessary. However it should not add to latency.
10036
10037 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
10038 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
10039
10040 void *rsmpInBuffer;
10041 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
10042 // if posix_memalign fails, will segv here.
10043 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
10044
10045 // Copy audio history if any from old buffer before freeing it
10046 if (previousRear != 0) {
10047 ALOG_ASSERT(mRsmpInBuffer != nullptr,
10048 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
10049
10050 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
10051 previousFront &= previousRsmpInFramesP2 - 1;
10052 size_t part1 = previousRsmpInFramesP2 - previousFront;
10053 if (part1 > (size_t) unread) {
10054 part1 = unread;
10055 }
10056 if (part1 != 0) {
10057 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
10058 part1 * mFrameSize);
10059 mRsmpInRear = part1;
10060 part1 = unread - part1;
10061 if (part1 != 0) {
10062 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
10063 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
10064 mRsmpInRear += part1;
10065 }
10066 }
10067 // Update front for all clients according to new rear
10068 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
10069 } else {
10070 mRsmpInRear = 0;
10071 }
10072 free(mRsmpInBuffer);
10073 mRsmpInBuffer = rsmpInBuffer;
10074}
10075
Andy Hungee58e4a2023-07-07 13:47:37 -070010076void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010077{
Andy Hung972bec12023-08-31 16:13:39 -070010078 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -070010079 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -070010080 if (record->getSource()) {
10081 mSource = record->getSource();
10082 }
Eric Laurent83b88082014-06-20 18:31:16 -070010083}
10084
Andy Hungee58e4a2023-07-07 13:47:37 -070010085void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -070010086{
Andy Hung972bec12023-08-31 16:13:39 -070010087 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -070010088 if (mSource == record->getSource()) {
10089 mSource = mInput;
10090 }
Eric Laurent83b88082014-06-20 18:31:16 -070010091 destroyTrack_l(record);
10092}
10093
Andy Hungee58e4a2023-07-07 13:47:37 -070010094void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -070010095{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010096 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -070010097 config->role = AUDIO_PORT_ROLE_SINK;
10098 config->ext.mix.hw_module = mInput->audioHwDev->handle();
10099 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010100 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10101 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10102 config->flags.input = mInput->flags;
10103 }
Eric Laurent83b88082014-06-20 18:31:16 -070010104}
Eric Laurent1c333e22014-05-20 10:48:17 -070010105
Eric Laurent6acd1d42017-01-04 14:23:29 -080010106// ----------------------------------------------------------------------------
10107// Mmap
10108// ----------------------------------------------------------------------------
10109
Andy Hung7aa7d102023-07-07 15:58:48 -070010110// Mmap stream control interface implementation. Each MmapThreadHandle controls one
10111// MmapPlaybackThread or MmapCaptureThread instance.
10112class MmapThreadHandle : public MmapStreamInterface {
10113public:
10114 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
10115 ~MmapThreadHandle() override;
10116
10117 // MmapStreamInterface virtuals
10118 status_t createMmapBuffer(int32_t minSizeFrames,
10119 struct audio_mmap_buffer_info* info) final;
10120 status_t getMmapPosition(struct audio_mmap_position* position) final;
10121 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
10122 status_t start(const AudioClient& client,
10123 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
10124 status_t stop(audio_port_handle_t handle) final;
10125 status_t standby() final;
10126 status_t reportData(const void* buffer, size_t frameCount) final;
10127private:
10128 const sp<IAfMmapThread> mThread;
10129};
10130
10131/* static */
10132sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
10133 const sp<IAfMmapThread>& mmapThread) {
10134 return sp<MmapThreadHandle>::make(mmapThread);
10135}
10136
10137MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138 : mThread(thread)
10139{
Phil Burk9fabbf82017-08-03 12:02:00 -070010140 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141}
10142
Andy Hung7aa7d102023-07-07 15:58:48 -070010143// MmapStreamInterface could be directly implemented by MmapThread excepting this
10144// special handling on adapter dtor.
10145MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010146{
Phil Burk9fabbf82017-08-03 12:02:00 -070010147 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010148}
10149
Andy Hung7aa7d102023-07-07 15:58:48 -070010150status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010151 struct audio_mmap_buffer_info *info)
10152{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010153 return mThread->createMmapBuffer(minSizeFrames, info);
10154}
10155
Andy Hung7aa7d102023-07-07 15:58:48 -070010156status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010158 return mThread->getMmapPosition(position);
10159}
10160
Andy Hung7aa7d102023-07-07 15:58:48 -070010161status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -070010162 int64_t *timeNanos) {
10163 return mThread->getExternalPosition(position, timeNanos);
10164}
10165
Andy Hung7aa7d102023-07-07 15:58:48 -070010166status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010167 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168{
jiabind1f1cb62020-03-24 11:57:57 -070010169 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010170}
10171
Andy Hung7aa7d102023-07-07 15:58:48 -070010172status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010173{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010174 return mThread->stop(handle);
10175}
10176
Andy Hung7aa7d102023-07-07 15:58:48 -070010177status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010178{
Eric Laurent18b57012017-02-13 16:23:52 -080010179 return mThread->standby();
10180}
10181
Andy Hung7aa7d102023-07-07 15:58:48 -070010182status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
10183{
jiabinfc791ee2023-02-15 19:43:40 +000010184 return mThread->reportData(buffer, frameCount);
10185}
10186
Eric Laurent6acd1d42017-01-04 14:23:29 -080010187
Andy Hungee58e4a2023-07-07 13:47:37 -070010188MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -070010189 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -070010190 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -070010191 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010192 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010193 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010194 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010195 mActiveTracks(&this->mLocalLog),
10196 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10197 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010198{
Eric Laurent18b57012017-02-13 16:23:52 -080010199 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010200 readHalParameters_l();
10201}
10202
Andy Hungee58e4a2023-07-07 13:47:37 -070010203void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010204{
10205 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10206}
10207
Andy Hungee58e4a2023-07-07 13:47:37 -070010208void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010209{
Andy Hung8d31fd22023-06-26 19:20:57 -070010210 ActiveTracks<IAfMmapTrack> activeTracks;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010211 audio_port_handle_t localPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010212 {
Andy Hung972bec12023-08-31 16:13:39 -070010213 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010214 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010215 activeTracks.add(t);
10216 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010217 localPortId = mPortId;
Eric Laurent331679c2018-04-16 17:03:16 -070010218 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010219 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010220 stop(t->portId());
10221 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010222 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010223 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010224 AudioSystem::releaseOutput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010225 } else {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010226 AudioSystem::releaseInput(localPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010227 }
10228}
10229
10230
Andy Hung8d672e02023-09-15 18:19:28 -070010231void MmapThread::configure_l(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010232 audio_stream_type_t streamType __unused,
10233 audio_session_t sessionId,
10234 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010235 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010236 audio_port_handle_t portId)
10237{
10238 mAttr = *attr;
10239 mSessionId = sessionId;
10240 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010241 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242 mPortId = portId;
10243}
10244
Andy Hungee58e4a2023-07-07 13:47:37 -070010245status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246 struct audio_mmap_buffer_info *info)
10247{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010248 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010249 if (mHalStream == 0) {
10250 return NO_INIT;
10251 }
Eric Laurent18b57012017-02-13 16:23:52 -080010252 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010253 return mHalStream->createMmapBuffer(minSizeFrames, info);
10254}
10255
Andy Hungee58e4a2023-07-07 13:47:37 -070010256status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010257{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010258 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010259 if (mHalStream == 0) {
10260 return NO_INIT;
10261 }
10262 return mHalStream->getMmapPosition(position);
10263}
10264
Andy Hungee58e4a2023-07-07 13:47:37 -070010265status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010266{
Eric Laurentdda206a2022-07-08 17:28:35 +020010267 // The HAL must receive track metadata before starting the stream
10268 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010269 status_t ret = mHalStream->start();
10270 if (ret != NO_ERROR) {
10271 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10272 return ret;
10273 }
Andy Hungcf10d742020-04-28 15:38:24 -070010274 if (mStandby) {
10275 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010276 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010277 mStandby = false;
10278 }
Eric Laurent331679c2018-04-16 17:03:16 -070010279 return NO_ERROR;
10280}
10281
Andy Hungee58e4a2023-07-07 13:47:37 -070010282status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010283 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010284 audio_port_handle_t *handle)
10285{
Andy Hung3f49ebb2023-09-19 14:48:41 -070010286 audio_utils::lock_guard l(mutex());
Eric Laurenta54f1282017-07-01 19:39:32 -070010287 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010288 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010289 if (mHalStream == 0) {
10290 return NO_INIT;
10291 }
10292
10293 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294
Eric Laurentdda206a2022-07-08 17:28:35 +020010295 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010296 if (*handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010297 acquireWakeLock_l();
Eric Laurentdda206a2022-07-08 17:28:35 +020010298 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010299 }
10300
10301 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10302
10303 audio_io_handle_t io = mId;
Atneya Nair5997a652024-06-14 17:24:45 -070010304 AttributionSourceState adjAttributionSource;
10305 if (!com::android::media::audio::audioserver_permissions()) {
10306 adjAttributionSource = afutils::checkAttributionSourcePackage(
10307 client.attributionSource);
10308 } else {
10309 // TODO(b/342475009) validate in oboeservice, and plumb downwards
10310 auto validatedRes = ValidatedAttributionSourceState::createFromTrustedUidNoPackage(
10311 client.attributionSource,
10312 mAfThreadCallback->getPermissionProvider()
10313 );
10314 if (!validatedRes.has_value()) {
10315 ALOGE("MMAP client package validation fail: %s",
10316 validatedRes.error().toString8().c_str());
10317 return aidl_utils::statusTFromBinderStatus(validatedRes.error());
10318 }
10319 adjAttributionSource = std::move(validatedRes.value()).unwrapInto();
10320 }
Atneya Nairf59db5c2023-05-10 21:37:41 -070010321
Andy Hung3f49ebb2023-09-19 14:48:41 -070010322 const auto localSessionId = mSessionId;
10323 auto localAttr = mAttr;
Eric Laurenta54f1282017-07-01 19:39:32 -070010324 if (isOutput()) {
10325 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10326 config.sample_rate = mSampleRate;
10327 config.channel_mask = mChannelMask;
10328 config.format = mFormat;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010329 audio_stream_type_t stream = streamType_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010330 audio_output_flags_t flags =
10331 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010332 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010333 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010334 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010335 bool isBitPerfect;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010336 mutex().unlock();
10337 ret = AudioSystem::getOutputForAttr(&localAttr, &io,
10338 localSessionId,
Eric Laurenta54f1282017-07-01 19:39:32 -070010339 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010340 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010341 &config,
10342 flags,
10343 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010344 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010345 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010346 &isSpatialized,
10347 &isBitPerfect);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010348 mutex().lock();
10349 mAttr = localAttr;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010350 ALOGD_IF(!secondaryOutputs.empty(),
10351 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010352 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010353 audio_config_base_t config;
10354 config.sample_rate = mSampleRate;
10355 config.channel_mask = mChannelMask;
10356 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010357 audio_port_handle_t deviceId = mDeviceId;
Andy Hung3f49ebb2023-09-19 14:48:41 -070010358 mutex().unlock();
10359 ret = AudioSystem::getInputForAttr(&localAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010360 RECORD_RIID_INVALID,
Andy Hung3f49ebb2023-09-19 14:48:41 -070010361 localSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010362 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010363 &config,
10364 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10365 &deviceId,
10366 &portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010367 mutex().lock();
10368 // localAttr is const for getInputForAttr.
Eric Laurenta54f1282017-07-01 19:39:32 -070010369 }
10370 // APM should not chose a different input or output stream for the same set of attributes
10371 // and audo configuration
10372 if (ret != NO_ERROR || io != mId) {
10373 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10374 __FUNCTION__, ret, io, mId);
10375 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010376 }
10377
10378 if (isOutput()) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010379 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -070010380 ret = AudioSystem::startOutput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010381 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010382 } else {
jiabin09609032022-06-15 19:26:01 +000010383 {
10384 // Add the track record before starting input so that the silent status for the
10385 // client can be cached.
jiabin09609032022-06-15 19:26:01 +000010386 setClientSilencedState_l(portId, false /*silenced*/);
10387 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010388 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -080010389 ret = AudioSystem::startInput(portId);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010390 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010391 }
10392
10393 // abort if start is rejected by audio policy manager
10394 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010395 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010396 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010397 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010398 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010399 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010400 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010401 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 }
Andy Hungc5007f82023-08-29 14:26:09 -070010403 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010404 } else {
10405 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406 }
jiabin09609032022-06-15 19:26:01 +000010407 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010408 return PERMISSION_DENIED;
10409 }
10410
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010411 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010412 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10413 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010414 mChannelMask, mSessionId, isOutput(),
10415 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010416 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010417 if (!isOutput()) {
10418 track->setSilenced_l(isClientSilenced_l(portId));
10419 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420
Eric Laurent4eb58f12018-12-07 16:41:02 -080010421 if (isOutput()) {
10422 // force volume update when a new track is added
10423 mHalVolFloat = -1.0f;
10424 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010425 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010426 if (t->isSilenced_l()
10427 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010428 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010429 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010430 }
10431 }
10432
Eric Laurent6acd1d42017-01-04 14:23:29 -080010433 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010434 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010435 if (chain != 0) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010436 chain->setStrategy(getStrategyForStream(streamType_l()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010437 chain->incTrackCnt();
10438 chain->incActiveTrackCnt();
10439 }
10440
Andy Hungc2b11cb2020-04-22 09:04:01 -070010441 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010442 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010443
10444 if (mActiveTracks.size() == 1) {
10445 ret = exitStandby_l();
10446 }
10447
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 broadcast_l();
10449
Eric Laurentdda206a2022-07-08 17:28:35 +020010450 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451
Eric Laurentdda206a2022-07-08 17:28:35 +020010452 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010453}
10454
Andy Hungee58e4a2023-07-07 13:47:37 -070010455status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457 ALOGV("%s handle %d", __FUNCTION__, handle);
Andy Hung3f49ebb2023-09-19 14:48:41 -070010458 audio_utils::lock_guard l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459
10460 if (mHalStream == 0) {
10461 return NO_INIT;
10462 }
10463
Eric Laurenta54f1282017-07-01 19:39:32 -070010464 if (handle == mPortId) {
Andy Hung3f49ebb2023-09-19 14:48:41 -070010465 releaseWakeLock_l();
Eric Laurenta54f1282017-07-01 19:39:32 -070010466 return NO_ERROR;
10467 }
10468
Andy Hung8d31fd22023-06-26 19:20:57 -070010469 sp<IAfMmapTrack> track;
10470 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010471 if (handle == t->portId()) {
10472 track = t;
10473 break;
10474 }
10475 }
10476 if (track == 0) {
10477 return BAD_VALUE;
10478 }
10479
10480 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010481 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010482
Andy Hungc5007f82023-08-29 14:26:09 -070010483 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010484 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010485 AudioSystem::stopOutput(track->portId());
10486 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010487 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010488 AudioSystem::stopInput(track->portId());
10489 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010490 }
Andy Hungc5007f82023-08-29 14:26:09 -070010491 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010492
Andy Hung116bc262023-06-20 18:56:17 -070010493 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494 if (chain != 0) {
10495 chain->decActiveTrackCnt();
10496 chain->decTrackCnt();
10497 }
10498
Eric Laurentdda206a2022-07-08 17:28:35 +020010499 if (mActiveTracks.isEmpty()) {
10500 mHalStream->stop();
10501 }
10502
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503 broadcast_l();
10504
Eric Laurent6acd1d42017-01-04 14:23:29 -080010505 return NO_ERROR;
10506}
10507
Andy Hungee58e4a2023-07-07 13:47:37 -070010508status_t MmapThread::standby()
Andy Hung3f49ebb2023-09-19 14:48:41 -070010509NO_THREAD_SAFETY_ANALYSIS // clang bug
Eric Laurent18b57012017-02-13 16:23:52 -080010510{
10511 ALOGV("%s", __FUNCTION__);
Atneya Nair97a73882023-10-30 20:26:21 -070010512 audio_utils::lock_guard l_{mutex()};
Eric Laurent18b57012017-02-13 16:23:52 -080010513
10514 if (mHalStream == 0) {
10515 return NO_INIT;
10516 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010517 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010518 return INVALID_OPERATION;
10519 }
10520 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010521 if (!mStandby) {
10522 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010523 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010524 mStandby = true;
10525 }
Andy Hung3f49ebb2023-09-19 14:48:41 -070010526 releaseWakeLock_l();
Eric Laurent18b57012017-02-13 16:23:52 -080010527 return NO_ERROR;
10528}
10529
Andy Hungee58e4a2023-07-07 13:47:37 -070010530status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010531 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10532 return INVALID_OPERATION;
10533}
10534
Andy Hungee58e4a2023-07-07 13:47:37 -070010535void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536{
10537 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10538 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10539 mFormat = mHALFormat;
10540 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10541 result = mHalStream->getFrameSize(&mFrameSize);
10542 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010543 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10544 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545 result = mHalStream->getBufferSize(&mBufferSize);
10546 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10547 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010548
Andy Hungcf10d742020-04-28 15:38:24 -070010549 // TODO: make a readHalParameters call?
10550 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010551 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010552 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010553 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10554 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10555 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10556 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10557 /*
10558 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10559 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10560 (int32_t)mHapticChannelMask)
10561 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10562 (int32_t)mHapticChannelCount)
10563 */
10564 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010565 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010566 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10567 (int32_t)mFrameCount) // sic - added HAL
10568 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010569}
10570
Andy Hungee58e4a2023-07-07 13:47:37 -070010571bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010572{
Andy Hungab65b182023-09-06 19:41:47 -070010573 {
10574 audio_utils::unique_lock _l(mutex());
10575 checkSilentMode_l();
10576 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010577
10578 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10579
10580 while (!exitPending())
10581 {
Andy Hung116bc262023-06-20 18:56:17 -070010582 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010583
Andy Hung13850be2019-03-14 11:33:09 -070010584 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010585 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010586
Eric Laurent6acd1d42017-01-04 14:23:29 -080010587 if (mSignalPending) {
10588 // A signal was raised while we were unlocked
10589 mSignalPending = false;
10590 } else {
10591 if (mConfigEvents.isEmpty()) {
10592 // we're about to wait, flush the binder command buffer
10593 IPCThreadState::self()->flushCommands();
10594
10595 if (exitPending()) {
10596 break;
10597 }
10598
Eric Laurent6acd1d42017-01-04 14:23:29 -080010599 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010600 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010601 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010602 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010603
10604 checkSilentMode_l();
10605
10606 continue;
10607 }
10608 }
10609
10610 processConfigEvents_l();
10611
10612 processVolume_l();
10613
10614 checkInvalidTracks_l();
10615
Andy Hungab65b182023-09-06 19:41:47 -070010616 mActiveTracks.updatePowerState_l(this);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010617
Kevin Rocard069c2712018-03-29 19:09:14 -070010618 updateMetadata_l();
10619
Eric Laurent6acd1d42017-01-04 14:23:29 -080010620 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010621 } // release Thread lock
10622
Eric Laurent6acd1d42017-01-04 14:23:29 -080010623 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010624 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010625 }
Andy Hung13850be2019-03-14 11:33:09 -070010626
10627 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010628 unlockEffectChains(effectChains);
10629 // Effect chains will be actually deleted here if they were removed from
10630 // mEffectChains list during mixing or effects processing
Andy Hung56ce2ed2024-06-12 16:03:16 -070010631 mThreadloopExecutor.process();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010632 }
Andy Hung56ce2ed2024-06-12 16:03:16 -070010633 mThreadloopExecutor.process(); // process any remaining deferred actions.
10634 // deferred actions after this point are ignored.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010635
10636 threadLoop_exit();
10637
10638 if (!mStandby) {
10639 threadLoop_standby();
10640 mStandby = true;
10641 }
10642
Eric Laurent6acd1d42017-01-04 14:23:29 -080010643 ALOGV("Thread %p type %d exiting", this, mType);
10644 return false;
10645}
10646
Andy Hungc5007f82023-08-29 14:26:09 -070010647// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010648bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010649 status_t& status)
10650{
10651 AudioParameter param = AudioParameter(keyValuePair);
10652 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010653 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010654 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010655 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010656 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010657 if (sendToHal) {
10658 status = mHalStream->setParameters(keyValuePair);
10659 } else {
10660 status = NO_ERROR;
10661 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010662
10663 return false;
10664}
10665
Andy Hungee58e4a2023-07-07 13:47:37 -070010666String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010667{
Andy Hung972bec12023-08-31 16:13:39 -070010668 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 String8 out_s8;
10670 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10671 return out_s8;
10672 }
Andy Hung920f6572022-10-06 12:09:49 -070010673 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010674}
10675
Andy Hungab65b182023-09-06 19:41:47 -070010676void MmapThread::ioConfigChanged_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010677 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010678 sp<AudioIoDescriptor> desc;
10679 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010680 switch (event) {
10681 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010682 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010683 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010684 isInput = true;
10685 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010686 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010687 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010689 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10690 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010691 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010692 case AUDIO_INPUT_CLOSED:
10693 case AUDIO_OUTPUT_CLOSED:
10694 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010695 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010696 break;
10697 }
Andy Hungab65b182023-09-06 19:41:47 -070010698 mAfThreadCallback->ioConfigChanged_l(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699}
10700
Andy Hungee58e4a2023-07-07 13:47:37 -070010701status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010703NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704{
10705 status_t status = NO_ERROR;
10706
10707 // store new device and send to effects
10708 audio_devices_t type = AUDIO_DEVICE_NONE;
10709 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010710 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10711 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10712 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010713 if (isOutput()) {
10714 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010715 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10716 && !mAudioHwDev->supportsAudioPatches(),
10717 "Enumerated device type(%#x) must not be used "
10718 "as it does not support audio patches",
10719 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010720 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010721 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10722 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010723 }
10724 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010725 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010726 } else {
10727 type = patch->sources[0].ext.device.type;
10728 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010729 numDevices = mPatch.num_sources;
10730 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010731 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010732 }
10733
10734 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010735 if (isOutput()) {
10736 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10737 } else {
10738 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10739 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010740 }
10741
jiabinc52b1ff2019-10-31 17:20:42 -070010742 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010743 // store new source and send to effects
10744 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10745 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10746 for (size_t i = 0; i < mEffectChains.size(); i++) {
10747 mEffectChains[i]->setAudioSource_l(mAudioSource);
10748 }
10749 }
10750 }
10751
jiabin78b86f22024-02-22 00:39:29 +000010752 // For mmap streams, once the routing has changed, they will be disconnected. It should be
10753 // okay to notify the client earlier before the new patch creation.
10754 if (mDeviceId != deviceId) {
10755 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10756 // The aaudioservice handle the routing changed event asynchronously. In that case,
10757 // it is safe to hold the lock here.
10758 callback->onRoutingChanged(deviceId);
10759 }
10760 }
10761
Eric Laurent6acd1d42017-01-04 14:23:29 -080010762 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010763 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10764 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010765 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010766 audio_port_config port;
10767 std::optional<audio_source_t> source;
10768 if (isOutput()) {
10769 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010770 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010771 port = patch->sources[0];
10772 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010773 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010774 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010775 *handle = AUDIO_PATCH_HANDLE_NONE;
10776 }
10777
jiabinc52b1ff2019-10-31 17:20:42 -070010778 if (numDevices == 0 || mDeviceId != deviceId) {
10779 if (isOutput()) {
10780 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10781 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010782 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010783 } else {
10784 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10785 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10786 }
jiabinc52b1ff2019-10-31 17:20:42 -070010787 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010788 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010789 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010790 // Force meteadata update after a route change
10791 mActiveTracks.setHasChanged();
10792
Eric Laurent6acd1d42017-01-04 14:23:29 -080010793 return status;
10794}
10795
Andy Hungee58e4a2023-07-07 13:47:37 -070010796status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010797{
10798 status_t status = NO_ERROR;
10799
jiabinc52b1ff2019-10-31 17:20:42 -070010800 mPatch = audio_patch{};
10801 mOutDeviceTypeAddrs.clear();
10802 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010803
10804 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10805 supportsAudioPatches : false;
10806
10807 if (supportsAudioPatches) {
10808 status = mHalDevice->releaseAudioPatch(handle);
10809 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010810 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010811 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010812 // Force meteadata update after a route change
10813 mActiveTracks.setHasChanged();
10814
Eric Laurent6acd1d42017-01-04 14:23:29 -080010815 return status;
10816}
10817
Andy Hungee58e4a2023-07-07 13:47:37 -070010818void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Andy Hung3f49ebb2023-09-19 14:48:41 -070010819NO_THREAD_SAFETY_ANALYSIS // mAudioHwDev handle access
Eric Laurent6acd1d42017-01-04 14:23:29 -080010820{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010821 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010822 if (isOutput()) {
10823 config->role = AUDIO_PORT_ROLE_SOURCE;
10824 config->ext.mix.hw_module = mAudioHwDev->handle();
10825 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10826 } else {
10827 config->role = AUDIO_PORT_ROLE_SINK;
10828 config->ext.mix.hw_module = mAudioHwDev->handle();
10829 config->ext.mix.usecase.source = mAudioSource;
10830 }
10831}
10832
Andy Hungee58e4a2023-07-07 13:47:37 -070010833status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010834{
10835 audio_session_t session = chain->sessionId();
10836
10837 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10838 // Attach all tracks with same session ID to this chain.
10839 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010840 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010841 if (session == track->sessionId()) {
10842 chain->incTrackCnt();
10843 chain->incActiveTrackCnt();
10844 }
10845 }
10846
10847 chain->setThread(this);
10848 chain->setInBuffer(nullptr);
10849 chain->setOutBuffer(nullptr);
Shunkai Yaod125e402024-01-20 03:19:06 +000010850 chain->syncHalEffectsState_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010851
10852 mEffectChains.add(chain);
10853 checkSuspendOnAddEffectChain_l(chain);
10854 return NO_ERROR;
10855}
10856
Andy Hungee58e4a2023-07-07 13:47:37 -070010857size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010858{
10859 audio_session_t session = chain->sessionId();
10860
10861 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10862
10863 for (size_t i = 0; i < mEffectChains.size(); i++) {
10864 if (chain == mEffectChains[i]) {
10865 mEffectChains.removeAt(i);
10866 // detach all active tracks from the chain
10867 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010868 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010869 if (session == track->sessionId()) {
10870 chain->decActiveTrackCnt();
10871 chain->decTrackCnt();
10872 }
10873 }
10874 break;
10875 }
10876 }
10877 return mEffectChains.size();
10878}
10879
Andy Hungee58e4a2023-07-07 13:47:37 -070010880void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010881{
10882 mHalStream->standby();
10883}
10884
Andy Hungee58e4a2023-07-07 13:47:37 -070010885void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010886{
Phil Burk7dce7282017-09-27 13:51:41 -070010887 // Do not call callback->onTearDown() because it is redundant for thread exit
10888 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010889}
10890
Andy Hungee58e4a2023-07-07 13:47:37 -070010891status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010892{
10893 return BAD_VALUE;
10894}
10895
Andy Hungee58e4a2023-07-07 13:47:37 -070010896bool MmapThread::isValidSyncEvent(
10897 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010898{
10899 return false;
10900}
10901
Andy Hungee58e4a2023-07-07 13:47:37 -070010902status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010903 const effect_descriptor_t *desc, audio_session_t sessionId)
10904{
10905 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010906 if (audio_is_global_session(sessionId)) {
10907 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010908 desc->name, mThreadName);
10909 return BAD_VALUE;
10910 }
10911
10912 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10913 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10914 desc->name);
10915 return BAD_VALUE;
10916 }
10917 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010918 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10919 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010920 return BAD_VALUE;
10921 }
10922
10923 // Only allow effects without processing load or latency
10924 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10925 return BAD_VALUE;
10926 }
10927
Andy Hung116bc262023-06-20 18:56:17 -070010928 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010929 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10930 return BAD_VALUE;
10931 }
10932
Eric Laurent6acd1d42017-01-04 14:23:29 -080010933 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010934}
10935
Andy Hungee58e4a2023-07-07 13:47:37 -070010936void MmapThread::checkInvalidTracks_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010937{
Andy Hung8d31fd22023-06-26 19:20:57 -070010938 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010939 if (track->isInvalid()) {
jiabin78b86f22024-02-22 00:39:29 +000010940 if (const sp<MmapStreamCallback> callback = mCallback.promote()) {
10941 // The aaudioservice handle the routing changed event asynchronously. In that case,
10942 // it is safe to hold the lock here.
10943 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
10944 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010945 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10946 mNoCallbackWarningCount++;
10947 }
10948 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010949 }
10950 }
10951}
10952
Andy Hungee58e4a2023-07-07 13:47:37 -070010953void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010954{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010955 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10956 mAttr.content_type, mAttr.usage, mAttr.source);
10957 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010958 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010959 dprintf(fd, " No active clients\n");
10960 }
10961}
10962
Andy Hungee58e4a2023-07-07 13:47:37 -070010963void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010964{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010965 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010966 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010967 dprintf(fd, " %zu Tracks\n", numtracks);
10968 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010969 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010970 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010971 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010972 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010973 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010974 result.append(prefix);
10975 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010976 }
10977 } else {
10978 dprintf(fd, "\n");
10979 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010980 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010981}
10982
Andy Hungee58e4a2023-07-07 13:47:37 -070010983/* static */
10984sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010985 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010986 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010987 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010988}
10989
10990MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010991 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010992 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010993 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010994 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010995 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010996{
10997 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10998 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010999 mMasterVolume = afThreadCallback->masterVolume_l();
11000 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011001
11002 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
11003 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
11004 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070011005 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011006 }
11007 // Audio patch and call assistant volume are always max
11008 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
11009 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
11010 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
11011 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
11012
Eric Laurent6acd1d42017-01-04 14:23:29 -080011013 if (mAudioHwDev) {
11014 if (mAudioHwDev->canSetMasterVolume()) {
11015 mMasterVolume = 1.0;
11016 }
11017
11018 if (mAudioHwDev->canSetMasterMute()) {
11019 mMasterMute = false;
11020 }
11021 }
11022}
11023
Andy Hungee58e4a2023-07-07 13:47:37 -070011024void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011025 audio_stream_type_t streamType,
11026 audio_session_t sessionId,
11027 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070011028 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080011029 audio_port_handle_t portId)
11030{
Andy Hung8d672e02023-09-15 18:19:28 -070011031 audio_utils::lock_guard l(mutex());
11032 MmapThread::configure_l(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011033 mStreamType = streamType;
11034}
11035
Andy Hungee58e4a2023-07-07 13:47:37 -070011036AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011037{
Andy Hung972bec12023-08-31 16:13:39 -070011038 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011039 AudioStreamOut *output = mOutput;
11040 mOutput = NULL;
11041 return output;
11042}
11043
Andy Hungee58e4a2023-07-07 13:47:37 -070011044void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045{
Andy Hung972bec12023-08-31 16:13:39 -070011046 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011047 // Don't apply master volume in SW if our HAL can do it for us.
11048 if (mAudioHwDev &&
11049 mAudioHwDev->canSetMasterVolume()) {
11050 mMasterVolume = 1.0;
11051 } else {
11052 mMasterVolume = value;
11053 }
11054}
11055
Andy Hungee58e4a2023-07-07 13:47:37 -070011056void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011057{
Andy Hung972bec12023-08-31 16:13:39 -070011058 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011059 // Don't apply master mute in SW if our HAL can do it for us.
11060 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
11061 mMasterMute = false;
11062 } else {
11063 mMasterMute = muted;
11064 }
11065}
11066
Andy Hungee58e4a2023-07-07 13:47:37 -070011067void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011068{
Andy Hung972bec12023-08-31 16:13:39 -070011069 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011070 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011071 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011072 broadcast_l();
11073 }
11074}
11075
Andy Hungee58e4a2023-07-07 13:47:37 -070011076float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080011077{
Andy Hung972bec12023-08-31 16:13:39 -070011078 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011079 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011080}
11081
Andy Hungee58e4a2023-07-07 13:47:37 -070011082void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011083{
Andy Hung972bec12023-08-31 16:13:39 -070011084 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011085 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080011086 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011087 broadcast_l();
11088 }
11089}
11090
Andy Hungee58e4a2023-07-07 13:47:37 -070011091void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011092{
Andy Hung972bec12023-08-31 16:13:39 -070011093 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011094 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070011095 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011096 track->invalidate();
11097 }
11098 broadcast_l();
11099 }
11100}
11101
Andy Hungee58e4a2023-07-07 13:47:37 -070011102void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080011103{
Andy Hung972bec12023-08-31 16:13:39 -070011104 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080011105 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070011106 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080011107 if (portIds.find(track->portId()) != portIds.end()) {
11108 track->invalidate();
11109 trackMatch = true;
11110 portIds.erase(track->portId());
11111 }
11112 if (portIds.empty()) {
11113 break;
11114 }
11115 }
11116 if (trackMatch) {
11117 broadcast_l();
11118 }
11119}
11120
Andy Hungee58e4a2023-07-07 13:47:37 -070011121void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070011122NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080011123{
11124 float volume;
11125
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011126 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011127 volume = 0;
11128 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011129 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011130 }
11131
11132 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080011133 // Convert volumes from float to 8.24
11134 uint32_t vol = (uint32_t)(volume * (1 << 24));
11135
11136 // Delegate volume control to effect in track effect chain if needed
11137 // only one effect chain can be present on DirectOutputThread, so if
11138 // there is one, the track is connected to it
11139 if (!mEffectChains.isEmpty()) {
Shunkai Yaof4847652024-01-12 00:25:20 +000011140 mEffectChains[0]->setVolume(&vol, &vol);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011141 volume = (float)vol / (1 << 24);
11142 }
Eric Laurentdff774a2017-04-21 15:29:38 -070011143 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070011144 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
11145 mHalVolFloat = volume; // HW volume control worked, so update value.
11146 mNoCallbackWarningCount = 0;
11147 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070011148 sp<MmapStreamCallback> callback = mCallback.promote();
11149 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011150 mHalVolFloat = volume; // SW volume control worked, so update value.
11151 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070011152 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000011153 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070011154 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080011155 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070011156 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11157 ALOGW("Could not set MMAP stream volume: no volume callback!");
11158 mNoCallbackWarningCount++;
11159 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011160 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011161 }
Andy Hung8d31fd22023-06-26 19:20:57 -070011162 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011163 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070011164 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011165 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011166 streamVolume_l() == 0.f,
11167 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020011168 // TODO(b/241533526): adjust logic to include mute from AppOps
11169 false /*muteFromPlaybackRestricted*/,
11170 false /*muteFromClientVolume*/,
11171 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011172 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080011173 }
11174}
11175
Andy Hungee58e4a2023-07-07 13:47:37 -070011176ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011177{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011178 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011179 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011180 }
11181 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011182 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011183 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011184 playback_track_metadata_v7_t trackMetadata;
11185 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011186 .usage = track->attributes().usage,
11187 .content_type = track->attributes().content_type,
11188 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010011189 };
11190 trackMetadata.channel_mask = track->channelMask(),
11191 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11192 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011193 }
11194 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011195
11196 MetadataUpdate change;
11197 change.playbackMetadataUpdate = metadata.tracks;
11198 return change;
11199};
Kevin Rocard069c2712018-03-29 19:09:14 -070011200
Andy Hungee58e4a2023-07-07 13:47:37 -070011201void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011202{
11203 if (!mMasterMute) {
11204 char value[PROPERTY_VALUE_MAX];
11205 if (property_get("ro.audio.silent", value, "0") > 0) {
11206 char *endptr;
11207 unsigned long ul = strtoul(value, &endptr, 0);
11208 if (*endptr == '\0' && ul != 0) {
Andy Hung0e26ec62024-02-20 16:32:57 -080011209 ALOGW("%s: mute from ro.audio.silent. Silence is golden", __func__);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011210 // The setprop command will not allow a property to be changed after
11211 // the first time it is set, so we don't have to worry about un-muting.
11212 setMasterMute_l(true);
11213 }
11214 }
11215 }
11216}
11217
Andy Hungee58e4a2023-07-07 13:47:37 -070011218void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011219{
11220 MmapThread::toAudioPortConfig(config);
11221 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
11222 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11223 config->flags.output = mOutput->flags;
11224 }
11225}
11226
Andy Hungee58e4a2023-07-07 13:47:37 -070011227status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070011228 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011229{
11230 if (mOutput == nullptr) {
11231 return NO_INIT;
11232 }
11233 struct timespec timestamp;
11234 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11235 if (status == NO_ERROR) {
11236 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11237 }
11238 return status;
11239}
11240
Andy Hungee58e4a2023-07-07 13:47:37 -070011241status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011242 // Send to MelProcessor for sound dose measurement.
11243 auto processor = mMelProcessor.load();
11244 if (processor) {
11245 processor->process(buffer, frameCount * mFrameSize);
11246 }
11247
jiabinfc791ee2023-02-15 19:43:40 +000011248 return NO_ERROR;
11249}
11250
Andy Hungc5007f82023-08-29 14:26:09 -070011251// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011252void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011253 const sp<audio_utils::MelProcessor>& processor)
11254{
11255 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011256 mMelProcessor.store(processor);
11257 if (processor) {
11258 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011259 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011260
11261 // no need to update output format for MMapPlaybackThread since it is
11262 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011263}
11264
Andy Hungc5007f82023-08-29 14:26:09 -070011265// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011266void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011267{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011268 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11269 auto melProcessor = mMelProcessor.load();
11270 if (melProcessor != nullptr) {
11271 melProcessor->pause();
11272 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011273}
11274
Andy Hungee58e4a2023-07-07 13:47:37 -070011275void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011276{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011277 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011278
Glenn Kastend3bb6452016-12-05 18:14:37 -080011279 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011280 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011281 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11282}
11283
Andy Hungee58e4a2023-07-07 13:47:37 -070011284/* static */
11285sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011286 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011287 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011288 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011289}
11290
11291MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011292 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011293 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011294 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011295 mInput(input)
11296{
11297 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11298 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11299}
11300
Andy Hungee58e4a2023-07-07 13:47:37 -070011301status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011302{
Phil Burkf054fc32018-12-06 09:45:59 -080011303 {
11304 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011305 if (mInput != nullptr && mInput->stream != nullptr) {
11306 mInput->stream->setGain(1.0f);
11307 }
11308 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011309 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011310}
11311
Andy Hungee58e4a2023-07-07 13:47:37 -070011312AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011313{
Andy Hung972bec12023-08-31 16:13:39 -070011314 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011315 AudioStreamIn *input = mInput;
11316 mInput = NULL;
11317 return input;
11318}
Kevin Rocard069c2712018-03-29 19:09:14 -070011319
Andy Hungee58e4a2023-07-07 13:47:37 -070011320void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011321{
11322 bool changed = false;
11323 bool silenced = false;
11324
11325 sp<MmapStreamCallback> callback = mCallback.promote();
11326 if (callback == 0) {
11327 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11328 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11329 mNoCallbackWarningCount++;
11330 }
11331 }
11332
11333 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11334 // track is silenced and unmute otherwise
11335 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11336 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11337 changed = true;
11338 silenced = mActiveTracks[i]->isSilenced_l();
11339 }
11340 }
11341
11342 if (changed) {
11343 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11344 }
11345}
11346
Andy Hungee58e4a2023-07-07 13:47:37 -070011347ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011348{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011349 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011350 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011351 }
11352 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011353 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011354 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011355 record_track_metadata_v7_t trackMetadata;
11356 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011357 .source = track->attributes().source,
11358 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011359 };
11360 trackMetadata.channel_mask = track->channelMask(),
11361 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11362 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011363 }
11364 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011365 MetadataUpdate change;
11366 change.recordMetadataUpdate = metadata.tracks;
11367 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011368}
11369
Andy Hungee58e4a2023-07-07 13:47:37 -070011370void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011371{
Andy Hung972bec12023-08-31 16:13:39 -070011372 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011373 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011374 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011375 mActiveTracks[i]->setSilenced_l(silenced);
11376 broadcast_l();
11377 }
11378 }
jiabin09609032022-06-15 19:26:01 +000011379 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011380}
11381
Andy Hungee58e4a2023-07-07 13:47:37 -070011382void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011383{
11384 MmapThread::toAudioPortConfig(config);
11385 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11386 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11387 config->flags.input = mInput->flags;
11388 }
11389}
11390
Andy Hungee58e4a2023-07-07 13:47:37 -070011391status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011392 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011393{
11394 if (mInput == nullptr) {
11395 return NO_INIT;
11396 }
11397 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11398}
11399
jiabinc658e452022-10-21 20:52:21 +000011400// ----------------------------------------------------------------------------
11401
Andy Hungee58e4a2023-07-07 13:47:37 -070011402/* static */
11403sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011404 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011405 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011406 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011407}
11408
Andy Hung583043b2023-07-17 17:05:00 -070011409BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011410 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011411 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011412
Andy Hungee58e4a2023-07-07 13:47:37 -070011413PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011414 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011415 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11416 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011417 float volumeLeft = 1.0f;
11418 float volumeRight = 1.0f;
jiabin220eea12024-05-17 17:55:20 +000011419 if (sp<IAfTrack> bitPerfectTrack = getTrackToStreamBitPerfectly_l();
11420 bitPerfectTrack != nullptr) {
11421 const int trackId = bitPerfectTrack->id();
jiabinc658e452022-10-21 20:52:21 +000011422 mAudioMixer->setParameter(
11423 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11424 mAudioMixer->setParameter(
11425 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11426 (void *)(uintptr_t)mNormalFrameCount);
jiabin220eea12024-05-17 17:55:20 +000011427 bitPerfectTrack->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011428 mIsBitPerfect = true;
11429 } else {
11430 mIsBitPerfect = false;
11431 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11432 // active.
11433 for (const auto& track : mActiveTracks) {
11434 const int trackId = track->id();
11435 mAudioMixer->setParameter(
11436 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11437 }
11438 }
jiabin76d94692022-12-15 21:51:21 +000011439 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11440 mVolumeLeft = volumeLeft;
11441 mVolumeRight = volumeRight;
11442 setVolumeForOutput_l(volumeLeft, volumeRight);
11443 }
jiabinc658e452022-10-21 20:52:21 +000011444 return result;
11445}
11446
Andy Hungee58e4a2023-07-07 13:47:37 -070011447void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011448 MixerThread::threadLoop_mix();
11449 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11450}
11451
jiabin220eea12024-05-17 17:55:20 +000011452void BitPerfectThread::setTracksInternalMute(
11453 std::map<audio_port_handle_t, bool>* tracksInternalMute) {
11454 for (auto& track : mTracks) {
11455 if (auto it = tracksInternalMute->find(track->portId()); it != tracksInternalMute->end()) {
11456 track->setInternalMute(it->second);
11457 tracksInternalMute->erase(it);
11458 }
11459 }
11460}
11461
11462sp<IAfTrack> BitPerfectThread::getTrackToStreamBitPerfectly_l() {
11463 if (com::android::media::audioserver::
11464 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
11465 sp<IAfTrack> bitPerfectTrack = nullptr;
11466 bool allOtherTracksMuted = true;
11467 // Return the bit perfect track if all other tracks are muted
11468 for (const auto& track : mActiveTracks) {
11469 if (track->isBitPerfect()) {
11470 bitPerfectTrack = track;
11471 } else if (track->getFinalVolume() != 0.f) {
11472 allOtherTracksMuted = false;
11473 if (bitPerfectTrack != nullptr) {
11474 break;
11475 }
11476 }
11477 }
11478 return allOtherTracksMuted ? bitPerfectTrack : nullptr;
11479 } else {
11480 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11481 return mActiveTracks[0];
11482 }
11483 }
11484 return nullptr;
11485}
11486
Glenn Kasten63238ef2015-03-02 15:50:29 -080011487} // namespace android