blob: bbf97c9f760fd5a24c946fdc88dcd100f5a7c845 [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>
36#ifdef DEBUG_CPU_USAGE
37#include <audio_utils/Statistics.h>
38#include <cpustats/ThreadCpuUsage.h>
39#endif
40#include <audio_utils/channels.h>
41#include <audio_utils/format.h>
42#include <audio_utils/minifloat.h>
43#include <audio_utils/mono_blend.h>
44#include <audio_utils/primitives.h>
45#include <audio_utils/safe_math.h>
46#include <audiomanager/AudioManager.h>
47#include <binder/IPCThreadState.h>
48#include <binder/IServiceManager.h>
49#include <binder/PersistableBundle.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070050#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080051#include <cutils/properties.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070052#include <fastpath/AutoPark.h>
jiabinc52b1ff2019-10-31 17:20:42 -070053#include <media/AudioContainers.h>
54#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070055#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070056#include <media/AudioResamplerPublic.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070057#ifdef ADD_BATTERY_DATA
58#include <media/IMediaPlayerService.h>
59#include <media/IMediaDeathNotifier.h>
60#endif
61#include <media/MmapStreamCallback.h>
Andy Hung89816052017-01-11 17:08:23 -080062#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070063#include <media/TypeConverter.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070064#include <media/audiohal/EffectsFactoryHalInterface.h>
65#include <media/audiohal/StreamHalInterface.h>
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070066#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080067#include <media/nbaio/AudioStreamOutSink.h>
68#include <media/nbaio/MonoPipe.h>
69#include <media/nbaio/MonoPipeReader.h>
70#include <media/nbaio/Pipe.h>
71#include <media/nbaio/PipeReader.h>
72#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080073#include <mediautils/BatteryNotifier.h>
Andy Hungafc51db2022-04-08 17:33:40 -070074#include <mediautils/Process.h>
Andy Hungab7ef302018-05-15 19:35:29 -070075#include <mediautils/SchedulingPolicyService.h>
76#include <mediautils/ServiceUtilities.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070077#include <powermanager/PowerManager.h>
78#include <private/android_filesystem_config.h>
79#include <private/media/AudioTrackShared.h>
80#include <system/audio_effects/effect_aec.h>
81#include <system/audio_effects/effect_downmix.h>
82#include <system/audio_effects/effect_ns.h>
83#include <system/audio_effects/effect_spatializer.h>
84#include <utils/Log.h>
85#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080086
Andy Hung25a80ac2023-07-19 12:47:35 -070087#include <fcntl.h>
88#include <linux/futex.h>
89#include <math.h>
90#include <memory>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080091#include <pthread.h>
Andy Hung25a80ac2023-07-19 12:47:35 -070092#include <sstream>
93#include <string>
94#include <sys/stat.h>
95#include <sys/syscall.h>
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080096
Eric Laurent81784c32012-11-19 14:55:58 -080097// ----------------------------------------------------------------------------
98
99// Note: the following macro is used for extremely verbose logging message. In
100// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
101// 0; but one side effect of this is to turn all LOGV's as well. Some messages
102// are so verbose that we want to suppress them even when we have ALOG_ASSERT
103// turned on. Do not uncomment the #def below unless you really know what you
104// are doing and want to see all of the extremely verbose messages.
105//#define VERY_VERY_VERBOSE_LOGGING
106#ifdef VERY_VERY_VERBOSE_LOGGING
107#define ALOGVV ALOGV
108#else
109#define ALOGVV(a...) do { } while(0)
110#endif
111
Andy Hung6770c6f2015-04-07 13:43:36 -0700112// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700114
Andy Hung6770c6f2015-04-07 13:43:36 -0700115template <typename T>
116static inline T min(const T& a, const T& b)
117{
118 return a < b ? a : b;
119}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700120
Eric Laurent81784c32012-11-19 14:55:58 -0800121namespace android {
122
Andy Hungee58e4a2023-07-07 13:47:37 -0700123using audioflinger::SyncEvent;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700124using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000125using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700126
Andy Hung25a80ac2023-07-19 12:47:35 -0700127// Keep in sync with java definition in media/java/android/media/AudioRecord.java
128static constexpr int32_t kMaxSharedAudioHistoryMs = 5000;
129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// retry counts for buffer fill timeout
131// 50 * ~20msecs = 1 second
132static const int8_t kMaxTrackRetries = 50;
133static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700134
Eric Laurent81784c32012-11-19 14:55:58 -0800135// allow less retry attempts on direct output thread.
136// direct outputs can be a scarce resource in audio hardware and should
137// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700138// Notes:
139// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
140// in case the data write is bursty for the AudioTrack. The application
141// should endeavor to write at least once every kMaxTrackRetriesDirectMs
142// to prevent an underrun situation. If the data is bursty, then
143// the application can also throttle the data sent to be even.
144// 2) For compressed audio data, any data present in the AudioTrack buffer
145// will be sent and reset the retry count. This delivers data as
146// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
147// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
148// of data to be available, then any remaining data is delivered.
149// This is required to ensure the last bit of data is delivered before underrun.
150//
151// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
152// or the size of the HAL period for proportional / linear PCM tracks.
153static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800154
155// don't warn about blocked writes or record buffer overflows more often than this
156static const nsecs_t kWarningThrottleNs = seconds(5);
157
158// RecordThread loop sleep time upon application overrun or audio HAL read error
159static const int kRecordThreadSleepUs = 5000;
160
Eric Laurent10351942014-05-08 18:49:52 -0700161// maximum time to wait in sendConfigEvent_l() for a status to be received
162static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800163
164// minimum sleep time for the mixer thread loop when tracks are active but in underrun
165static const uint32_t kMinThreadSleepTimeUs = 5000;
166// maximum divider applied to the active sleep time in the mixer thread loop
167static const uint32_t kMaxThreadSleepTimeShift = 2;
168
Andy Hung09a50072014-02-27 14:30:47 -0800169// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800171static const uint32_t kMinNormalSinkBufferSizeMs = 20;
172// maximum normal sink buffer size
173static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800174
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700175// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
176// FIXME This should be based on experimentally observed scheduling jitter
177static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
178
Eric Laurent972a1732013-09-04 09:42:59 -0700179// Offloaded output thread standby delay: allows track transition without going to standby
180static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
181
Eric Laurent51716182016-02-29 18:00:56 -0800182// Direct output thread minimum sleep time in idle or active(underrun) state
183static const nsecs_t kDirectMinSleepTimeUs = 10000;
184
Brian Lindahl65e90012022-07-27 18:01:07 +0200185// Minimum amount of time between checking to see if the timestamp is advancing
186// for underrun detection. If we check too frequently, we may not detect a
187// timestamp update and will falsely detect underrun.
188static const nsecs_t kMinimumTimeBetweenTimestampChecksNs = 150 /* ms */ * 1000;
189
Glenn Kasten1b291842016-07-18 14:55:21 -0700190// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
191// balance between power consumption and latency, and allows threads to be scheduled reliably
192// by the CFS scheduler.
193// FIXME Express other hardcoded references to 20ms with references to this constant and move
194// it appropriately.
195#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800196
Eric Laurent81784c32012-11-19 14:55:58 -0800197// Whether to use fast mixer
198static const enum {
199 FastMixer_Never, // never initialize or use: for debugging only
200 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
201 // normal mixer multiplier is 1
202 FastMixer_Static, // initialize if needed, then use all the time if initialized,
203 // multiplier is calculated based on min & max normal mixer buffer size
204 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
205 // multiplier is calculated based on min & max normal mixer buffer size
206 // FIXME for FastMixer_Dynamic:
207 // Supporting this option will require fixing HALs that can't handle large writes.
208 // For example, one HAL implementation returns an error from a large write,
209 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
210 // We could either fix the HAL implementations, or provide a wrapper that breaks
211 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
212} kUseFastMixer = FastMixer_Static;
213
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214// Whether to use fast capture
215static const enum {
216 FastCapture_Never, // never initialize or use: for debugging only
217 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
218 FastCapture_Static, // initialize if needed, then use all the time if initialized
219} kUseFastCapture = FastCapture_Static;
220
Eric Laurent81784c32012-11-19 14:55:58 -0800221// Priorities for requestPriority
222static const int kPriorityAudioApp = 2;
223static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700224static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800225
Glenn Kastenea38ee72016-04-18 11:08:01 -0700226// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
227// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
228// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700229
230// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800231static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800232
Glenn Kasten03490092014-05-27 12:30:54 -0700233// The minimum and maximum allowed values
234static const int kFastTrackMultiplierMin = 1;
235static const int kFastTrackMultiplierMax = 2;
236
237// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
238static int sFastTrackMultiplier = kFastTrackMultiplier;
239
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700240// See Thread::readOnlyHeap().
241// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
242// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
243// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700244static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700245
Andy Hung25a80ac2023-07-19 12:47:35 -0700246static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung8fe87eb2023-07-20 21:31:38 -0700247
248static nsecs_t getStandbyTimeInNanos() {
249 static nsecs_t standbyTimeInNanos = []() {
250 const int ms = property_get_int32("ro.audio.flinger_standbytime_ms",
251 kDefaultStandbyTimeInNsecs / NANOS_PER_MILLISECOND);
252 ALOGI("%s: Using %d ms as standby time", __func__, ms);
253 return milliseconds(ms);
254 }();
255 return standbyTimeInNanos;
256}
257
Andy Hung81994d62023-07-20 21:44:14 -0700258// Set kEnableExtendedChannels to true to enable greater than stereo output
259// for the MixerThread and device sink. Number of channels allowed is
260// FCC_2 <= channels <= FCC_LIMIT.
261constexpr bool kEnableExtendedChannels = true;
262
263// Returns true if channel mask is permitted for the PCM sink in the MixerThread
264/* static */
265bool IAfThreadBase::isValidPcmSinkChannelMask(audio_channel_mask_t channelMask) {
266 switch (audio_channel_mask_get_representation(channelMask)) {
267 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
268 // Haptic channel mask is only applicable for channel position mask.
269 const uint32_t channelCount = audio_channel_count_from_out_mask(
270 static_cast<audio_channel_mask_t>(channelMask & ~AUDIO_CHANNEL_HAPTIC_ALL));
271 const uint32_t maxChannelCount = kEnableExtendedChannels
272 ? FCC_LIMIT : FCC_2;
273 if (channelCount < FCC_2 // mono is not supported at this time
274 || channelCount > maxChannelCount) {
275 return false;
276 }
277 // check that channelMask is the "canonical" one we expect for the channelCount.
278 return audio_channel_position_mask_is_out_canonical(channelMask);
279 }
280 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
281 if (kEnableExtendedChannels) {
282 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
283 if (channelCount >= FCC_2 // mono is not supported at this time
284 && channelCount <= FCC_LIMIT) {
285 return true;
286 }
287 }
288 return false;
289 default:
290 return false;
291 }
292}
293
294// Set kEnableExtendedPrecision to true to use extended precision in MixerThread
295constexpr bool kEnableExtendedPrecision = true;
296
297// Returns true if format is permitted for the PCM sink in the MixerThread
298/* static */
299bool IAfThreadBase::isValidPcmSinkFormat(audio_format_t format) {
300 switch (format) {
301 case AUDIO_FORMAT_PCM_16_BIT:
302 return true;
303 case AUDIO_FORMAT_PCM_FLOAT:
304 case AUDIO_FORMAT_PCM_24_BIT_PACKED:
305 case AUDIO_FORMAT_PCM_32_BIT:
306 case AUDIO_FORMAT_PCM_8_24_BIT:
307 return kEnableExtendedPrecision;
308 default:
309 return false;
310 }
311}
312
Eric Laurent81784c32012-11-19 14:55:58 -0800313// ----------------------------------------------------------------------------
314
Andy Hung25a80ac2023-07-19 12:47:35 -0700315// formatToString() needs to be exact for MediaMetrics purposes.
316// Do not use media/TypeConverter.h toString().
317/* static */
318std::string IAfThreadBase::formatToString(audio_format_t format) {
319 std::string result;
320 FormatConverter::toString(format, result);
321 return result;
322}
323
Andy Hungb68f5eb2019-12-03 16:49:17 -0800324// TODO: move all toString helpers to audio.h
325// under #ifdef __cplusplus #endif
326static std::string patchSinksToString(const struct audio_patch *patch)
327{
328 std::stringstream ss;
329 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700330 if (i > 0) {
331 ss << "|";
332 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800333 ss << "(" << toString(patch->sinks[i].ext.device.type)
334 << ", " << patch->sinks[i].ext.device.address << ")";
335 }
336 return ss.str();
337}
338
339static std::string patchSourcesToString(const struct audio_patch *patch)
340{
341 std::stringstream ss;
342 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700343 if (i > 0) {
344 ss << "|";
345 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800346 ss << "(" << toString(patch->sources[i].ext.device.type)
347 << ", " << patch->sources[i].ext.device.address << ")";
348 }
349 return ss.str();
350}
351
Andy Hung4bd53e72022-11-17 17:21:45 -0800352static std::string toString(audio_latency_mode_t mode) {
353 // We convert to the AIDL type to print (eventually the legacy type will be removed).
Mikhail Naganovf53e1822022-12-18 02:48:14 +0000354 const auto result = legacy2aidl_audio_latency_mode_t_AudioLatencyMode(mode);
355 return result.has_value() ? media::audio::common::toString(*result) : "UNKNOWN";
Andy Hung4bd53e72022-11-17 17:21:45 -0800356}
357
358// Could be made a template, but other toString overloads for std::vector are confused.
359static std::string toString(const std::vector<audio_latency_mode_t>& elements) {
360 std::string s("{ ");
361 for (const auto& e : elements) {
362 s.append(toString(e));
363 s.append(" ");
364 }
365 s.append("}");
366 return s;
367}
368
Glenn Kasten03490092014-05-27 12:30:54 -0700369static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
370
371static void sFastTrackMultiplierInit()
372{
373 char value[PROPERTY_VALUE_MAX];
374 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
375 char *endptr;
376 unsigned long ul = strtoul(value, &endptr, 0);
377 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
378 sFastTrackMultiplier = (int) ul;
379 }
380 }
381}
382
383// ----------------------------------------------------------------------------
384
Eric Laurent81784c32012-11-19 14:55:58 -0800385#ifdef ADD_BATTERY_DATA
386// To collect the amplifier usage
387static void addBatteryData(uint32_t params) {
388 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
389 if (service == NULL) {
390 // it already logged
391 return;
392 }
393
394 service->addBatteryData(params);
395}
396#endif
397
Andy Hung3f0c9022016-01-15 17:49:46 -0800398// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
399struct {
400 // call when you acquire a partial wakelock
401 void acquire(const sp<IBinder> &wakeLockToken) {
402 pthread_mutex_lock(&mLock);
403 if (wakeLockToken.get() == nullptr) {
404 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
405 } else {
406 if (mCount == 0) {
407 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
408 }
409 ++mCount;
410 }
411 pthread_mutex_unlock(&mLock);
412 }
413
414 // call when you release a partial wakelock.
415 void release(const sp<IBinder> &wakeLockToken) {
416 if (wakeLockToken.get() == nullptr) {
417 return;
418 }
419 pthread_mutex_lock(&mLock);
420 if (--mCount < 0) {
421 ALOGE("negative wakelock count");
422 mCount = 0;
423 }
424 pthread_mutex_unlock(&mLock);
425 }
426
427 // retrieves the boottime timebase offset from monotonic.
428 int64_t getBoottimeOffset() {
429 pthread_mutex_lock(&mLock);
430 int64_t boottimeOffset = mBoottimeOffset;
431 pthread_mutex_unlock(&mLock);
432 return boottimeOffset;
433 }
434
435 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
436 // and the selected timebase.
437 // Currently only TIMEBASE_BOOTTIME is allowed.
438 //
439 // This only needs to be called upon acquiring the first partial wakelock
440 // after all other partial wakelocks are released.
441 //
442 // We do an empirical measurement of the offset rather than parsing
443 // /proc/timer_list since the latter is not a formal kernel ABI.
444 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
445 int clockbase;
446 switch (timebase) {
447 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
448 clockbase = SYSTEM_TIME_BOOTTIME;
449 break;
450 default:
451 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
452 break;
453 }
454 // try three times to get the clock offset, choose the one
455 // with the minimum gap in measurements.
456 const int tries = 3;
Andy Hung920f6572022-10-06 12:09:49 -0700457 nsecs_t bestGap = 0, measured = 0; // not required, initialized for clang-tidy
Andy Hung3f0c9022016-01-15 17:49:46 -0800458 for (int i = 0; i < tries; ++i) {
459 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
460 const nsecs_t tbase = systemTime(clockbase);
461 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
462 const nsecs_t gap = tmono2 - tmono;
463 if (i == 0 || gap < bestGap) {
464 bestGap = gap;
465 measured = tbase - ((tmono + tmono2) >> 1);
466 }
467 }
468
469 // to avoid micro-adjusting, we don't change the timebase
470 // unless it is significantly different.
471 //
472 // Assumption: It probably takes more than toleranceNs to
473 // suspend and resume the device.
474 static int64_t toleranceNs = 10000; // 10 us
475 if (llabs(*offset - measured) > toleranceNs) {
476 ALOGV("Adjusting timebase offset old: %lld new: %lld",
477 (long long)*offset, (long long)measured);
478 *offset = measured;
479 }
480 }
481
482 pthread_mutex_t mLock;
483 int32_t mCount;
484 int64_t mBoottimeOffset;
485} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800486
487// ----------------------------------------------------------------------------
488// CPU Stats
489// ----------------------------------------------------------------------------
490
491class CpuStats {
492public:
493 CpuStats();
494 void sample(const String8 &title);
495#ifdef DEBUG_CPU_USAGE
496private:
497 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700498 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800499
Andy Hung16698b82018-08-01 10:48:38 -0700500 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800501
502 int mCpuNum; // thread's current CPU number
503 int mCpukHz; // frequency of thread's current CPU in kHz
504#endif
505};
506
507CpuStats::CpuStats()
508#ifdef DEBUG_CPU_USAGE
509 : mCpuNum(-1), mCpukHz(-1)
510#endif
511{
512}
513
Glenn Kasten0f11b512014-01-31 16:18:54 -0800514void CpuStats::sample(const String8 &title
515#ifndef DEBUG_CPU_USAGE
516 __unused
517#endif
518 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800519#ifdef DEBUG_CPU_USAGE
520 // get current thread's delta CPU time in wall clock ns
521 double wcNs;
522 bool valid = mCpuUsage.sampleAndEnable(wcNs);
523
524 // record sample for wall clock statistics
525 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700526 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800527 }
528
529 // get the current CPU number
530 int cpuNum = sched_getcpu();
531
532 // get the current CPU frequency in kHz
533 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
534
535 // check if either CPU number or frequency changed
536 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
537 mCpuNum = cpuNum;
538 mCpukHz = cpukHz;
539 // ignore sample for purposes of cycles
540 valid = false;
541 }
542
543 // if no change in CPU number or frequency, then record sample for cycle statistics
544 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700545 const double cycles = wcNs * cpukHz * 0.000001;
546 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800547 }
548
Eric Tan5b13ff82018-07-27 11:20:17 -0700549 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800550 // mCpuUsage.elapsed() is expensive, so don't call it every loop
551 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700552 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800553 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700554 const double perLoop = elapsed / (double) n;
555 const double perLoop100 = perLoop * 0.01;
556 const double perLoop1k = perLoop * 0.001;
557 const double mean = mWcStats.getMean();
558 const double stddev = mWcStats.getStdDev();
559 const double minimum = mWcStats.getMin();
560 const double maximum = mWcStats.getMax();
561 const double meanCycles = mHzStats.getMean();
562 const double stddevCycles = mHzStats.getStdDev();
563 const double minCycles = mHzStats.getMin();
564 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800565 mCpuUsage.resetElapsed();
566 mWcStats.reset();
567 mHzStats.reset();
568 ALOGD("CPU usage for %s over past %.1f secs\n"
569 " (%u mixer loops at %.1f mean ms per loop):\n"
570 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
571 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
572 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000573 title.c_str(),
Eric Laurent81784c32012-11-19 14:55:58 -0800574 elapsed * .000000001, n, perLoop * .000001,
575 mean * .001,
576 stddev * .001,
577 minimum * .001,
578 maximum * .001,
579 mean / perLoop100,
580 stddev / perLoop100,
581 minimum / perLoop100,
582 maximum / perLoop100,
583 meanCycles / perLoop1k,
584 stddevCycles / perLoop1k,
585 minCycles / perLoop1k,
586 maxCycles / perLoop1k);
587
588 }
589 }
590#endif
591};
592
593// ----------------------------------------------------------------------------
594// ThreadBase
595// ----------------------------------------------------------------------------
596
Glenn Kasten97b7b752014-09-28 13:04:24 -0700597// static
Andy Hungee58e4a2023-07-07 13:47:37 -0700598const char* ThreadBase::threadTypeToString(ThreadBase::type_t type)
Glenn Kasten97b7b752014-09-28 13:04:24 -0700599{
600 switch (type) {
601 case MIXER:
602 return "MIXER";
603 case DIRECT:
604 return "DIRECT";
605 case DUPLICATING:
606 return "DUPLICATING";
607 case RECORD:
608 return "RECORD";
609 case OFFLOAD:
610 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700611 case MMAP_PLAYBACK:
612 return "MMAP_PLAYBACK";
613 case MMAP_CAPTURE:
614 return "MMAP_CAPTURE";
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200615 case SPATIALIZER:
616 return "SPATIALIZER";
jiabinc658e452022-10-21 20:52:21 +0000617 case BIT_PERFECT:
618 return "BIT_PERFECT";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700619 default:
620 return "unknown";
621 }
622}
623
Andy Hung583043b2023-07-17 17:05:00 -0700624ThreadBase::ThreadBase(const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700625 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800626 : Thread(false /*canCallJava*/),
627 mType(type),
Andy Hung583043b2023-07-17 17:05:00 -0700628 mAfThreadCallback(afThreadCallback),
Andy Hungcf10d742020-04-28 15:38:24 -0700629 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
630 isOut),
631 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700632 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800633 // are set by PlaybackThread::readOutputParameters_l() or
634 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700635 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700636 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700637 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800638 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700639 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800640 mSystemReady(systemReady),
641 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800642{
Andy Hungcf10d742020-04-28 15:38:24 -0700643 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700644 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800645}
646
Andy Hungee58e4a2023-07-07 13:47:37 -0700647ThreadBase::~ThreadBase()
Eric Laurent81784c32012-11-19 14:55:58 -0800648{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700649 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700650 mConfigEvents.clear();
651
Eric Laurent81784c32012-11-19 14:55:58 -0800652 // do not lock the mutex in destructor
653 releaseWakeLock_l();
654 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800655 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800656 binder->unlinkToDeath(mDeathRecipient);
657 }
Andy Hungd0979812019-02-21 15:51:44 -0800658
659 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800660}
661
Andy Hungee58e4a2023-07-07 13:47:37 -0700662status_t ThreadBase::readyToRun()
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700663{
664 status_t status = initCheck();
665 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800666 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700667 } else {
668 ALOGE("No working audio driver found.");
669 }
670 return status;
671}
672
Andy Hungee58e4a2023-07-07 13:47:37 -0700673void ThreadBase::exit()
Eric Laurent81784c32012-11-19 14:55:58 -0800674{
675 ALOGV("ThreadBase::exit");
676 // do any cleanup required for exit to succeed
677 preExit();
678 {
679 // This lock prevents the following race in thread (uniprocessor for illustration):
680 // if (!exitPending()) {
681 // // context switch from here to exit()
682 // // exit() calls requestExit(), what exitPending() observes
683 // // exit() calls signal(), which is dropped since no waiters
684 // // context switch back from exit() to here
685 // mWaitWorkCV.wait(...);
686 // // now thread is hung
687 // }
Andy Hungc5007f82023-08-29 14:26:09 -0700688 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800689 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -0700690 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -0800691 }
692 // When Thread::requestExitAndWait is made virtual and this method is renamed to
693 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
694 requestExitAndWait();
695}
696
Andy Hungee58e4a2023-07-07 13:47:37 -0700697status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800698{
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000699 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hung972bec12023-08-31 16:13:39 -0700700 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800701
Eric Laurent10351942014-05-08 18:49:52 -0700702 return sendSetParameterConfigEvent_l(keyValuePairs);
703}
704
705// sendConfigEvent_l() must be called with ThreadBase::mLock held
706// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
Andy Hungee58e4a2023-07-07 13:47:37 -0700707status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung920f6572022-10-06 12:09:49 -0700708NO_THREAD_SAFETY_ANALYSIS // condition variable
Eric Laurent10351942014-05-08 18:49:52 -0700709{
710 status_t status = NO_ERROR;
711
Eric Laurent72e3f392015-05-20 14:43:50 -0700712 if (event->mRequiresSystemReady && !mSystemReady) {
713 event->mWaitStatus = false;
714 mPendingConfigEvents.add(event);
715 return status;
716 }
Eric Laurent10351942014-05-08 18:49:52 -0700717 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700718 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Andy Hungc5007f82023-08-29 14:26:09 -0700719 mWaitWorkCV.notify_one();
720 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700721 {
Andy Hungc5007f82023-08-29 14:26:09 -0700722 audio_utils::unique_lock _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700723 while (event->mWaitStatus) {
Andy Hungc5007f82023-08-29 14:26:09 -0700724 if (event->mCondition.wait_for(_l, std::chrono::nanoseconds(kConfigEventTimeoutNs))
725 == std::cv_status::timeout) {
Eric Laurent10351942014-05-08 18:49:52 -0700726 event->mStatus = TIMED_OUT;
727 event->mWaitStatus = false;
728 }
729 }
730 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800731 }
Andy Hungc5007f82023-08-29 14:26:09 -0700732 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800733 return status;
734}
735
Andy Hungee58e4a2023-07-07 13:47:37 -0700736void ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700737 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800738{
Andy Hung972bec12023-08-31 16:13:39 -0700739 audio_utils::lock_guard _l(mutex());
Eric Laurent09f1ed22019-04-24 17:45:17 -0700740 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800741}
742
Andy Hungc5007f82023-08-29 14:26:09 -0700743// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700744void ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700745 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800746{
Andy Hungd0979812019-02-21 15:51:44 -0800747 // The audio statistics history is exponentially weighted to forget events
748 // about five or more seconds in the past. In order to have
749 // crisper statistics for mediametrics, we reset the statistics on
750 // an IoConfigEvent, to reflect different properties for a new device.
751 mIoJitterMs.reset();
752 mLatencyMs.reset();
753 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000754 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100755 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800756
Eric Laurent09f1ed22019-04-24 17:45:17 -0700757 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700758 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800759}
760
Andy Hungee58e4a2023-07-07 13:47:37 -0700761void ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700762{
Andy Hung972bec12023-08-31 16:13:39 -0700763 audio_utils::lock_guard _l(mutex());
Mikhail Naganov83f04272017-02-07 10:45:09 -0800764 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700765}
766
Andy Hungc5007f82023-08-29 14:26:09 -0700767// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700768void ThreadBase::sendPrioConfigEvent_l(
Mikhail Naganov83f04272017-02-07 10:45:09 -0800769 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800770{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800771 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700772 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800773}
774
Andy Hungc5007f82023-08-29 14:26:09 -0700775// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -0700776status_t ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800777{
Andy Hung2ddee192015-12-18 17:34:44 -0800778 sp<ConfigEvent> configEvent;
779 AudioParameter param(keyValuePair);
780 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700781 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800782 setMasterMono_l(value != 0);
783 if (param.size() == 1) {
784 return NO_ERROR; // should be a solo parameter - we don't pass down
785 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700786 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800787 configEvent = new SetParameterConfigEvent(param.toString());
788 } else {
789 configEvent = new SetParameterConfigEvent(keyValuePair);
790 }
Eric Laurent10351942014-05-08 18:49:52 -0700791 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700792}
793
Andy Hungee58e4a2023-07-07 13:47:37 -0700794status_t ThreadBase::sendCreateAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700795 const struct audio_patch *patch,
796 audio_patch_handle_t *handle)
797{
Andy Hung972bec12023-08-31 16:13:39 -0700798 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
800 status_t status = sendConfigEvent_l(configEvent);
801 if (status == NO_ERROR) {
802 CreateAudioPatchConfigEventData *data =
803 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
804 *handle = data->mHandle;
805 }
806 return status;
807}
808
Andy Hungee58e4a2023-07-07 13:47:37 -0700809status_t ThreadBase::sendReleaseAudioPatchConfigEvent(
Eric Laurent1c333e22014-05-20 10:48:17 -0700810 const audio_patch_handle_t handle)
811{
Andy Hung972bec12023-08-31 16:13:39 -0700812 audio_utils::lock_guard _l(mutex());
Eric Laurent1c333e22014-05-20 10:48:17 -0700813 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
814 return sendConfigEvent_l(configEvent);
815}
816
Andy Hungee58e4a2023-07-07 13:47:37 -0700817status_t ThreadBase::sendUpdateOutDeviceConfigEvent(
jiabinc52b1ff2019-10-31 17:20:42 -0700818 const DeviceDescriptorBaseVector& outDevices)
819{
820 if (type() != RECORD) {
821 // The update out device operation is only for record thread.
822 return INVALID_OPERATION;
823 }
Andy Hung972bec12023-08-31 16:13:39 -0700824 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -0700825 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
826 return sendConfigEvent_l(configEvent);
827}
828
Andy Hungee58e4a2023-07-07 13:47:37 -0700829void ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +0200830{
831 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
832 sp<ConfigEvent> configEvent =
833 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
834 sendConfigEvent_l(configEvent);
835}
Eric Laurent1c333e22014-05-20 10:48:17 -0700836
Andy Hungee58e4a2023-07-07 13:47:37 -0700837void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200838{
Andy Hung972bec12023-08-31 16:13:39 -0700839 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +0200840 sendCheckOutputStageEffectsEvent_l();
841}
842
Andy Hungee58e4a2023-07-07 13:47:37 -0700843void ThreadBase::sendCheckOutputStageEffectsEvent_l()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200844{
845 sp<ConfigEvent> configEvent =
846 (ConfigEvent *)new CheckOutputStageEffectsEvent();
847 sendConfigEvent_l(configEvent);
848}
849
Andy Hungee58e4a2023-07-07 13:47:37 -0700850void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent68a40a82022-05-03 18:15:04 +0200851{
852 sp<ConfigEvent> configEvent = sp<HalLatencyModesChangedEvent>::make();
853 sendConfigEvent_l(configEvent);
854}
855
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700856// post condition: mConfigEvents.isEmpty()
Andy Hungee58e4a2023-07-07 13:47:37 -0700857void ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700858{
Eric Laurent10351942014-05-08 18:49:52 -0700859 bool configChanged = false;
860
Eric Laurent81784c32012-11-19 14:55:58 -0800861 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700862 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700863 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800864 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700865 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700866 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700867 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
868 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800869 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700870 true /*asynchronous*/);
871 if (err != 0) {
872 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700873 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700874 }
875 } break;
876 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700877 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700878 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700879 } break;
880 case CFG_EVENT_SET_PARAMETER: {
881 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
882 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
883 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700884 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000885 data->mKeyValuePairs.c_str());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700886 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700887 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700888 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700889 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700890 CreateAudioPatchConfigEventData *data =
891 (CreateAudioPatchConfigEventData *)event->mData.get();
892 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700893 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200894 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700895 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
896 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
897 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700898 } break;
899 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700900 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700901 ReleaseAudioPatchConfigEventData *data =
902 (ReleaseAudioPatchConfigEventData *)event->mData.get();
903 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700904 const DeviceTypeSet newDevices = getDeviceTypes();
Eric Laurent52568142022-10-28 11:23:28 +0200905 configChanged = oldDevices != newDevices;
jiabinc52b1ff2019-10-31 17:20:42 -0700906 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
907 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
908 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
909 } break;
910 case CFG_EVENT_UPDATE_OUT_DEVICE: {
911 UpdateOutDevicesConfigEventData *data =
912 (UpdateOutDevicesConfigEventData *)event->mData.get();
913 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200915 case CFG_EVENT_RESIZE_BUFFER: {
916 ResizeBufferConfigEventData *data =
917 (ResizeBufferConfigEventData *)event->mData.get();
918 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
919 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200920
921 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
922 setCheckOutputStageEffects();
923 } break;
924
Eric Laurent68a40a82022-05-03 18:15:04 +0200925 case CFG_EVENT_HAL_LATENCY_MODES_CHANGED: {
926 onHalLatencyModesChanged_l();
927 } break;
928
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700929 default:
Eric Laurent10351942014-05-08 18:49:52 -0700930 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700931 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800932 }
Eric Laurent10351942014-05-08 18:49:52 -0700933 {
Andy Hung972bec12023-08-31 16:13:39 -0700934 audio_utils::lock_guard _l(event->mutex());
Eric Laurent10351942014-05-08 18:49:52 -0700935 if (event->mWaitStatus) {
936 event->mWaitStatus = false;
Andy Hungc5007f82023-08-29 14:26:09 -0700937 event->mCondition.notify_one();
Eric Laurent10351942014-05-08 18:49:52 -0700938 }
939 }
940 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
941 }
942
943 if (configChanged) {
944 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800945 }
Eric Laurent81784c32012-11-19 14:55:58 -0800946}
947
Marco Nelissenb2208842014-02-07 14:00:50 -0800948String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
949 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700950 const audio_channel_representation_t representation =
951 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700952
953 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800954 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700955 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
956 if (output) {
957 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
958 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
959 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700960 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700961 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
962 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
963 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
964 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
965 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
966 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
967 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
968 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
969 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
970 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
971 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
972 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700973 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
974 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
975 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
976 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
977 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
978 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
979 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700980 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700981 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
982 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700983 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
984 } else {
985 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
986 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
987 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
988 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
989 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
990 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
991 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
992 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
993 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
994 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
995 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
996 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700997 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
998 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
999 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -07001000 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -07001001 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
1002 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -07001003 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
1004 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
1005 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
1006 }
1007 const int len = s.length();
1008 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07001009 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -07001010 s.unlockBuffer(len - 2); // remove trailing ", "
1011 }
1012 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001013 }
Andy Hungf98ec8d2015-05-19 12:53:24 -07001014 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
1015 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
1016 return s;
1017 default:
1018 s.appendFormat("unknown mask, representation:%d bits:%#x",
1019 representation, audio_channel_mask_get_bits(mask));
1020 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -08001021 }
Marco Nelissenb2208842014-02-07 14:00:50 -08001022}
1023
Andy Hungee58e4a2023-07-07 13:47:37 -07001024void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung920f6572022-10-06 12:09:49 -07001025NO_THREAD_SAFETY_ANALYSIS // conditional try lock
Eric Laurent81784c32012-11-19 14:55:58 -08001026{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001027 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
1028 this, mThreadName, getTid(), type(), threadTypeToString(type()));
1029
Andy Hungc5007f82023-08-29 14:26:09 -07001030 const bool locked = afutils::dumpTryLock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001031 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08001032 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001033 }
1034
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001035 dumpBase_l(fd, args);
1036 dumpInternals_l(fd, args);
1037 dumpTracks_l(fd, args);
1038 dumpEffectChains_l(fd, args);
1039
1040 if (locked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001041 mutex().unlock();
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001042 }
1043
1044 dprintf(fd, " Local log:\n");
1045 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
Andy Hungafc51db2022-04-08 17:33:40 -07001046
1047 // --all does the statistics
1048 bool dumpAll = false;
1049 for (const auto &arg : args) {
1050 if (arg == String16("--all")) {
1051 dumpAll = true;
1052 }
1053 }
1054 if (dumpAll || type() == SPATIALIZER) {
Andy Hung44d648b2022-04-08 17:33:40 -07001055 const std::string sched = mThreadSnapshot.toString();
Andy Hungafc51db2022-04-08 17:33:40 -07001056 if (!sched.empty()) {
1057 (void)write(fd, sched.c_str(), sched.size());
1058 }
1059 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001060}
1061
Andy Hungee58e4a2023-07-07 13:47:37 -07001062void ThreadBase::dumpBase_l(int fd, const Vector<String16>& /* args */)
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001063{
Elliott Hughes87cebad2014-05-22 10:14:43 -07001064 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001065 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -07001066 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001067 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Andy Hung25a80ac2023-07-19 12:47:35 -07001068 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat,
1069 IAfThreadBase::formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001070 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001071 dprintf(fd, " Channel count: %u\n", mChannelCount);
1072 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00001073 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung25a80ac2023-07-19 12:47:35 -07001074 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat,
1075 IAfThreadBase::formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -07001076 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001077 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -08001078 size_t numConfig = mConfigEvents.size();
1079 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001080 const size_t SIZE = 256;
1081 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -08001082 for (size_t i = 0; i < numConfig; i++) {
1083 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001084 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -08001085 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001086 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -08001087 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07001088 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -08001089 }
Andy Hung293558a2017-03-21 12:19:20 -07001090 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -07001091 dprintf(fd, " Output devices: %s (%s)\n",
1092 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
1093 dprintf(fd, " Input device: %#x (%s)\n",
1094 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -08001095 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08001096
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001097 // Dump timestamp statistics for the Thread types that support it.
1098 if (mType == RECORD
1099 || mType == MIXER
1100 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07001101 || mType == DIRECT
Andy Hung4b7f54f2022-04-28 17:45:28 -07001102 || mType == OFFLOAD
1103 || mType == SPATIALIZER) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001104 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -07001105 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -07001106 }
1107
Andy Hung446f4df2019-02-21 12:26:41 -08001108 if (mLastIoBeginNs > 0) { // MMAP may not set this
1109 dprintf(fd, " Last %s occurred (msecs): %lld\n",
1110 isOutput() ? "write" : "read",
1111 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
1112 }
1113
1114 if (mProcessTimeMs.getN() > 0) {
1115 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
1116 }
1117
1118 if (mIoJitterMs.getN() > 0) {
1119 dprintf(fd, " Hal %s jitter ms stats: %s\n",
1120 isOutput() ? "write" : "read",
1121 mIoJitterMs.toString().c_str());
1122 }
1123
Andy Hunge6c37112019-02-26 17:38:10 -08001124 if (mLatencyMs.getN() > 0) {
1125 dprintf(fd, " Threadloop %s latency stats: %s\n",
1126 isOutput() ? "write" : "read",
1127 mLatencyMs.toString().c_str());
1128 }
Robert Wu06db0a32021-08-10 19:05:34 +00001129
1130 if (mMonopipePipeDepthStats.getN() > 0) {
1131 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
1132 isOutput() ? "write" : "read",
1133 mMonopipePipeDepthStats.toString().c_str());
1134 }
Eric Laurent81784c32012-11-19 14:55:58 -08001135}
1136
Andy Hungee58e4a2023-07-07 13:47:37 -07001137void ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001138{
1139 const size_t SIZE = 256;
1140 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001141
Marco Nelissenb2208842014-02-07 14:00:50 -08001142 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001143 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001144 write(fd, buffer, strlen(buffer));
1145
Marco Nelissenb2208842014-02-07 14:00:50 -08001146 for (size_t i = 0; i < numEffectChains; ++i) {
Andy Hung116bc262023-06-20 18:56:17 -07001147 sp<IAfEffectChain> chain = mEffectChains[i];
Eric Laurent81784c32012-11-19 14:55:58 -08001148 if (chain != 0) {
1149 chain->dump(fd, args);
1150 }
1151 }
1152}
1153
Andy Hungee58e4a2023-07-07 13:47:37 -07001154void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001155{
Andy Hung972bec12023-08-31 16:13:39 -07001156 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07001157 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001158}
1159
Andy Hungee58e4a2023-07-07 13:47:37 -07001160String16 ThreadBase::getWakeLockTag()
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001161{
1162 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001163 case MIXER:
1164 return String16("AudioMix");
1165 case DIRECT:
1166 return String16("AudioDirectOut");
1167 case DUPLICATING:
1168 return String16("AudioDup");
1169 case RECORD:
1170 return String16("AudioIn");
1171 case OFFLOAD:
1172 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001173 case MMAP_PLAYBACK:
1174 return String16("MmapPlayback");
1175 case MMAP_CAPTURE:
1176 return String16("MmapCapture");
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001177 case SPATIALIZER:
1178 return String16("AudioSpatial");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001179 default:
1180 ALOG_ASSERT(false);
1181 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001182 }
1183}
1184
Andy Hungee58e4a2023-07-07 13:47:37 -07001185void ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001186{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001187 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001188 if (mPowerManager != 0) {
1189 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001190 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001191 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1192 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001193 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001194 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001195 {} /* workSource */,
1196 {} /* historyTag */);
1197 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001198 mWakeLockToken = binder;
1199 }
Chris Ye6597d732020-02-28 22:38:25 -08001200 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001201 }
Wei Jia3f273d12015-11-24 09:06:49 -08001202
Andy Hung3f0c9022016-01-15 17:49:46 -08001203 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001204 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1205 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001206}
1207
Andy Hungee58e4a2023-07-07 13:47:37 -07001208void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001209{
Andy Hung972bec12023-08-31 16:13:39 -07001210 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001211 releaseWakeLock_l();
1212}
1213
Andy Hungee58e4a2023-07-07 13:47:37 -07001214void ThreadBase::releaseWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001215{
Andy Hung3f0c9022016-01-15 17:49:46 -08001216 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001217 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001218 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001219 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001220 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001221 }
1222 mWakeLockToken.clear();
1223 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001224}
1225
Andy Hungee58e4a2023-07-07 13:47:37 -07001226void ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001227 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001228 // use checkService() to avoid blocking if power service is not up yet
1229 sp<IBinder> binder =
1230 defaultServiceManager()->checkService(String16("power"));
1231 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001232 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001233 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001234 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001235 binder->linkToDeath(mDeathRecipient);
1236 }
1237 }
1238}
1239
Andy Hungee58e4a2023-07-07 13:47:37 -07001240void ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t>& uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001241 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001242
1243#if !LOG_NDEBUG
1244 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001245 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001246 s << uid << " ";
1247 }
1248 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1249#endif
1250
Andy Hung438e7572015-12-14 15:51:17 -08001251 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1252 if (mSystemReady) {
1253 ALOGE("no wake lock to update, but system ready!");
1254 } else {
1255 ALOGW("no wake lock to update, system not ready yet");
1256 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001257 return;
1258 }
1259 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001260 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001261 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1262 mWakeLockToken, uidsAsInt);
1263 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001264 }
1265}
1266
Andy Hungee58e4a2023-07-07 13:47:37 -07001267void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001268{
Andy Hung972bec12023-08-31 16:13:39 -07001269 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001270 releaseWakeLock_l();
1271 mPowerManager.clear();
1272}
1273
Andy Hungee58e4a2023-07-07 13:47:37 -07001274void ThreadBase::updateOutDevices(
jiabinc52b1ff2019-10-31 17:20:42 -07001275 const DeviceDescriptorBaseVector& outDevices __unused)
1276{
1277 ALOGE("%s should only be called in RecordThread", __func__);
1278}
1279
Andy Hungee58e4a2023-07-07 13:47:37 -07001280void ThreadBase::resizeInputBuffer_l(int32_t /* maxSharedAudioHistoryMs */)
Eric Laurentec376dc2021-04-08 20:41:22 +02001281{
1282 ALOGE("%s should only be called in RecordThread", __func__);
1283}
1284
Andy Hungee58e4a2023-07-07 13:47:37 -07001285void ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& /* who */)
Eric Laurent81784c32012-11-19 14:55:58 -08001286{
1287 sp<ThreadBase> thread = mThread.promote();
1288 if (thread != 0) {
1289 thread->clearPowerManager();
1290 }
1291 ALOGW("power manager service died !!!");
1292}
1293
Andy Hungee58e4a2023-07-07 13:47:37 -07001294void ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001295 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001296{
Andy Hung116bc262023-06-20 18:56:17 -07001297 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001298 if (chain != 0) {
1299 if (type != NULL) {
1300 chain->setEffectSuspended_l(type, suspend);
1301 } else {
1302 chain->setEffectSuspendedAll_l(suspend);
1303 }
1304 }
1305
1306 updateSuspendedSessions_l(type, suspend, sessionId);
1307}
1308
Andy Hungee58e4a2023-07-07 13:47:37 -07001309void ThreadBase::checkSuspendOnAddEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08001310{
1311 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1312 if (index < 0) {
1313 return;
1314 }
1315
1316 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1317 mSuspendedSessions.valueAt(index);
1318
1319 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001320 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001321 for (int j = 0; j < desc->mRefCount; j++) {
Andy Hung116bc262023-06-20 18:56:17 -07001322 if (sessionEffects.keyAt(i) == IAfEffectChain::kKeyForSuspendAll) {
Eric Laurent81784c32012-11-19 14:55:58 -08001323 chain->setEffectSuspendedAll_l(true);
1324 } else {
1325 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1326 desc->mType.timeLow);
1327 chain->setEffectSuspended_l(&desc->mType, true);
1328 }
1329 }
1330 }
1331}
1332
Andy Hungee58e4a2023-07-07 13:47:37 -07001333void ThreadBase::updateSuspendedSessions_l(const effect_uuid_t* type,
Eric Laurent81784c32012-11-19 14:55:58 -08001334 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001335 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001336{
1337 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1338
1339 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1340
1341 if (suspend) {
1342 if (index >= 0) {
1343 sessionEffects = mSuspendedSessions.valueAt(index);
1344 } else {
1345 mSuspendedSessions.add(sessionId, sessionEffects);
1346 }
1347 } else {
1348 if (index < 0) {
1349 return;
1350 }
1351 sessionEffects = mSuspendedSessions.valueAt(index);
1352 }
1353
1354
Andy Hung116bc262023-06-20 18:56:17 -07001355 int key = IAfEffectChain::kKeyForSuspendAll;
Eric Laurent81784c32012-11-19 14:55:58 -08001356 if (type != NULL) {
1357 key = type->timeLow;
1358 }
1359 index = sessionEffects.indexOfKey(key);
1360
1361 sp<SuspendedSessionDesc> desc;
1362 if (suspend) {
1363 if (index >= 0) {
1364 desc = sessionEffects.valueAt(index);
1365 } else {
1366 desc = new SuspendedSessionDesc();
1367 if (type != NULL) {
1368 desc->mType = *type;
1369 }
1370 sessionEffects.add(key, desc);
1371 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1372 }
1373 desc->mRefCount++;
1374 } else {
1375 if (index < 0) {
1376 return;
1377 }
1378 desc = sessionEffects.valueAt(index);
1379 if (--desc->mRefCount == 0) {
1380 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1381 sessionEffects.removeItemsAt(index);
1382 if (sessionEffects.isEmpty()) {
1383 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1384 sessionId);
1385 mSuspendedSessions.removeItem(sessionId);
1386 }
1387 }
1388 }
1389 if (!sessionEffects.isEmpty()) {
1390 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1391 }
1392}
1393
Andy Hungee58e4a2023-07-07 13:47:37 -07001394void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001395 audio_session_t sessionId,
Andy Hung920f6572022-10-06 12:09:49 -07001396 bool threadLocked)
1397NO_THREAD_SAFETY_ANALYSIS // manual locking
1398{
Eric Laurent6b446ce2019-12-13 10:56:31 -08001399 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001400 mutex().lock();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001401 }
Eric Laurent81784c32012-11-19 14:55:58 -08001402
Eric Laurent81784c32012-11-19 14:55:58 -08001403 if (mType != RECORD) {
1404 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1405 // another session. This gives the priority to well behaved effect control panels
1406 // and applications not using global effects.
1407 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1408 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001409 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001410 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1411 }
1412 }
1413
Eric Laurent6b446ce2019-12-13 10:56:31 -08001414 if (!threadLocked) {
Andy Hungc5007f82023-08-29 14:26:09 -07001415 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001416 }
1417}
1418
Andy Hungc5007f82023-08-29 14:26:09 -07001419// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001420status_t RecordThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001421 const effect_descriptor_t *desc, audio_session_t sessionId)
1422{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001423 // No global output effect sessions on record threads
1424 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1425 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001426 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1427 desc->name, mThreadName);
1428 return BAD_VALUE;
1429 }
1430 // only pre processing effects on record thread
1431 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1432 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1433 desc->name, mThreadName);
1434 return BAD_VALUE;
1435 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001436
1437 // always allow effects without processing load or latency
1438 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1439 return NO_ERROR;
1440 }
1441
Eric Laurent4c415062016-06-17 16:14:16 -07001442 audio_input_flags_t flags = mInput->flags;
1443 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1444 if (flags & AUDIO_INPUT_FLAG_RAW) {
1445 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1446 desc->name, mThreadName);
1447 return BAD_VALUE;
1448 }
1449 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1450 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1451 desc->name, mThreadName);
1452 return BAD_VALUE;
1453 }
1454 }
jiabineb3bda02020-06-30 14:07:03 -07001455
Andy Hung116bc262023-06-20 18:56:17 -07001456 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -07001457 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1458 return BAD_VALUE;
1459 }
Eric Laurent4c415062016-06-17 16:14:16 -07001460 return NO_ERROR;
1461}
1462
Andy Hungc5007f82023-08-29 14:26:09 -07001463// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001464status_t PlaybackThread::checkEffectCompatibility_l(
Eric Laurent4c415062016-06-17 16:14:16 -07001465 const effect_descriptor_t *desc, audio_session_t sessionId)
1466{
1467 // no preprocessing on playback threads
1468 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001469 ALOGW("%s: pre processing effect %s created on playback"
1470 " thread %s", __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001471 return BAD_VALUE;
1472 }
1473
Eric Laurent3e4de772017-07-16 16:55:08 -07001474 // always allow effects without processing load or latency
1475 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1476 return NO_ERROR;
1477 }
1478
Andy Hung116bc262023-06-20 18:56:17 -07001479 if (IAfEffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
jiabineb3bda02020-06-30 14:07:03 -07001480 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1481 __func__);
1482 return BAD_VALUE;
1483 }
1484
Eric Laurentf690c462021-09-17 14:47:03 +02001485 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1486 && mType != SPATIALIZER) {
1487 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1488 __func__, mType);
1489 return BAD_VALUE;
1490 }
1491
Eric Laurent4c415062016-06-17 16:14:16 -07001492 switch (mType) {
1493 case MIXER: {
Eric Laurent4c415062016-06-17 16:14:16 -07001494 audio_output_flags_t flags = mOutput->flags;
1495 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1496 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1497 // global effects are applied only to non fast tracks if they are SW
1498 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1499 break;
1500 }
1501 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1502 // only post processing on output stage session
1503 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001504 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1505 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001506 return BAD_VALUE;
1507 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001508 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1509 // only post processing on output stage session
1510 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001511 ALOGW("%s: non post processing effect %s not allowed on device session",
1512 __func__, desc->name);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001513 return BAD_VALUE;
1514 }
Eric Laurent4c415062016-06-17 16:14:16 -07001515 } else {
1516 // no restriction on effects applied on non fast tracks
1517 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1518 break;
1519 }
1520 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001521
Eric Laurent4c415062016-06-17 16:14:16 -07001522 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001523 ALOGW("%s: effect %s on playback thread in raw mode", __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001524 return BAD_VALUE;
1525 }
1526 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001527 ALOGW("%s: non HW effect %s on playback thread in fast mode",
1528 __func__, desc->name);
Eric Laurent4c415062016-06-17 16:14:16 -07001529 return BAD_VALUE;
1530 }
1531 }
1532 } break;
1533 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001534 // nothing actionable on offload threads, if the effect:
1535 // - is offloadable: the effect can be created
1536 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1537 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001538 break;
1539 case DIRECT:
1540 // Reject any effect on Direct output threads for now, since the format of
1541 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
Eric Laurentb62d0362021-10-26 17:40:18 +02001542 ALOGW("%s: effect %s on DIRECT output thread %s",
1543 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001544 return BAD_VALUE;
1545 case DUPLICATING:
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001546 if (audio_is_global_session(sessionId)) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001547 ALOGW("%s: global effect %s on DUPLICATING thread %s",
1548 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001549 return BAD_VALUE;
1550 }
1551 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001552 ALOGW("%s: post processing effect %s on DUPLICATING thread %s",
1553 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001554 return BAD_VALUE;
1555 }
1556 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
Eric Laurentb62d0362021-10-26 17:40:18 +02001557 ALOGW("%s: HW tunneled effect %s on DUPLICATING thread %s",
1558 __func__, desc->name, mThreadName);
Eric Laurent4c415062016-06-17 16:14:16 -07001559 return BAD_VALUE;
1560 }
1561 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001562 case SPATIALIZER:
Eric Laurentb62d0362021-10-26 17:40:18 +02001563 // Global effects (AUDIO_SESSION_OUTPUT_MIX) are not supported on spatializer mixer
1564 // as there is no common accumulation buffer for sptialized and non sptialized tracks.
1565 // Post processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE)
1566 // are supported and added after the spatializer.
1567 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1568 ALOGW("%s: global effect %s not supported on spatializer thread %s",
1569 __func__, desc->name, mThreadName);
Eric Laurentb3f315a2021-07-13 15:09:05 +02001570 return BAD_VALUE;
Eric Laurentb62d0362021-10-26 17:40:18 +02001571 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1572 // only post processing , downmixer or spatializer effects on output stage session
1573 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1574 || memcmp(&desc->type, EFFECT_UIID_DOWNMIX, sizeof(effect_uuid_t)) == 0) {
1575 break;
1576 }
1577 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1578 ALOGW("%s: non post processing effect %s not allowed on output stage session",
1579 __func__, desc->name);
1580 return BAD_VALUE;
1581 }
1582 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1583 // only post processing on output stage session
1584 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1585 ALOGW("%s: non post processing effect %s not allowed on device session",
1586 __func__, desc->name);
1587 return BAD_VALUE;
1588 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001589 }
1590 break;
jiabinc658e452022-10-21 20:52:21 +00001591 case BIT_PERFECT:
1592 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1593 // Allow HW accelerated effects of tunnel type
1594 break;
1595 }
1596 // As bit-perfect tracks will not be allowed to apply audio effect that will touch the audio
1597 // data, effects will not be allowed on 1) global effects (AUDIO_SESSION_OUTPUT_MIX),
1598 // 2) post-processing effects (AUDIO_SESSION_OUTPUT_STAGE or AUDIO_SESSION_DEVICE) and
1599 // 3) there is any bit-perfect track with the given session id.
1600 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE ||
1601 sessionId == AUDIO_SESSION_DEVICE) {
1602 ALOGW("%s: effect %s not supported on bit-perfect thread %s",
1603 __func__, desc->name, mThreadName);
1604 return BAD_VALUE;
1605 } else if ((hasAudioSession_l(sessionId) & ThreadBase::BIT_PERFECT_SESSION) != 0) {
1606 ALOGW("%s: effect %s not supported as there is a bit-perfect track with session as %d",
1607 __func__, desc->name, sessionId);
1608 return BAD_VALUE;
1609 }
1610 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001611 default:
1612 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1613 }
1614
1615 return NO_ERROR;
1616}
1617
Andy Hungc5007f82023-08-29 14:26:09 -07001618// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07001619sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hung88035ac2023-06-27 17:05:02 -07001620 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08001621 const sp<IEffectClient>& effectClient,
1622 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001623 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001624 effect_descriptor_t *desc,
1625 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001626 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001627 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001628 bool probe,
1629 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001630{
Andy Hung116bc262023-06-20 18:56:17 -07001631 sp<IAfEffectModule> effect;
1632 sp<IAfEffectHandle> handle;
Eric Laurent81784c32012-11-19 14:55:58 -08001633 status_t lStatus;
Andy Hung116bc262023-06-20 18:56:17 -07001634 sp<IAfEffectChain> chain;
Eric Laurent81784c32012-11-19 14:55:58 -08001635 bool chainCreated = false;
1636 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001637 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001638
1639 lStatus = initCheck();
1640 if (lStatus != NO_ERROR) {
1641 ALOGW("createEffect_l() Audio driver not initialized.");
1642 goto Exit;
1643 }
1644
Eric Laurent81784c32012-11-19 14:55:58 -08001645 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1646
Andy Hungc5007f82023-08-29 14:26:09 -07001647 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07001648 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001649
Eric Laurent4c415062016-06-17 16:14:16 -07001650 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001651 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001652 goto Exit;
1653 }
1654
Eric Laurent81784c32012-11-19 14:55:58 -08001655 // check for existing effect chain with the requested audio session
1656 chain = getEffectChain_l(sessionId);
1657 if (chain == 0) {
1658 // create a new chain for this session
1659 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001660 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001661 addEffectChain_l(chain);
1662 chain->setStrategy(getStrategyForSession_l(sessionId));
1663 chainCreated = true;
1664 } else {
1665 effect = chain->getEffectFromDesc_l(desc);
1666 }
1667
1668 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1669
1670 if (effect == 0) {
Andy Hung583043b2023-07-17 17:05:00 -07001671 effectId = mAfThreadCallback->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001672 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001673 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001674 if (lStatus != NO_ERROR) {
1675 goto Exit;
1676 }
1677 effectCreated = true;
1678
jiabinc52b1ff2019-10-31 17:20:42 -07001679 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001680 effect->setDevices(outDeviceTypeAddrs());
1681 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001682 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001683 effect->setAudioSource(mAudioSource);
1684 }
jiabin1319f5a2021-03-30 22:21:24 +00001685 if (effect->isHapticGenerator()) {
1686 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1687 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001688 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
Andy Hung583043b2023-07-17 17:05:00 -07001689 std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01001690 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001691 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001692 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001693 }
1694 }
Eric Laurent81784c32012-11-19 14:55:58 -08001695 // create effect handle and connect it to effect module
Andy Hung116bc262023-06-20 18:56:17 -07001696 handle = IAfEffectHandle::create(
1697 effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001698 lStatus = handle->initCheck();
1699 if (lStatus == OK) {
1700 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001701 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001702 }
Eric Laurent81784c32012-11-19 14:55:58 -08001703 if (enabled != NULL) {
1704 *enabled = (int)effect->isEnabled();
1705 }
1706 }
1707
1708Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001709 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Andy Hung972bec12023-08-31 16:13:39 -07001710 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001711 if (effectCreated) {
1712 chain->removeEffect_l(effect);
1713 }
Eric Laurent81784c32012-11-19 14:55:58 -08001714 if (chainCreated) {
1715 removeEffectChain_l(chain);
1716 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001717 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001718 }
1719
Glenn Kasten9156ef32013-08-06 15:39:08 -07001720 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001721 return handle;
1722}
1723
Andy Hungee58e4a2023-07-07 13:47:37 -07001724void ThreadBase::disconnectEffectHandle(IAfEffectHandle* handle,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001725 bool unpinIfLast)
1726{
1727 bool remove = false;
Andy Hung116bc262023-06-20 18:56:17 -07001728 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001729 {
Andy Hung972bec12023-08-31 16:13:39 -07001730 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07001731 sp<IAfEffectBase> effectBase = handle->effect().promote();
Eric Laurent41709552019-12-16 19:34:05 -08001732 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001733 return;
1734 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001735 effect = effectBase->asEffectModule();
1736 if (effect == nullptr) {
1737 return;
1738 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001739 // restore suspended effects if the disconnected handle was enabled and the last one.
1740 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1741 if (remove) {
1742 removeEffect_l(effect, true);
1743 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001744 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001745 }
1746 if (remove) {
Andy Hung583043b2023-07-17 17:05:00 -07001747 mAfThreadCallback->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001748 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001749 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001750 }
1751 }
1752}
1753
Andy Hungee58e4a2023-07-07 13:47:37 -07001754void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001755 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001756 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001757 broadcast_l();
1758 }
1759 if (!effect->isOffloadable()) {
1760 if (mType == ThreadBase::OFFLOAD) {
1761 PlaybackThread *t = (PlaybackThread *)this;
1762 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1763 }
1764 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
Andy Hung583043b2023-07-17 17:05:00 -07001765 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001766 }
1767 }
1768}
1769
Andy Hungee58e4a2023-07-07 13:47:37 -07001770void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001771 if (isOffloadOrMmap()) {
Andy Hung972bec12023-08-31 16:13:39 -07001772 audio_utils::lock_guard _l(mutex());
Eric Laurent6b446ce2019-12-13 10:56:31 -08001773 broadcast_l();
1774 }
1775}
1776
Andy Hungee58e4a2023-07-07 13:47:37 -07001777sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001778 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001779{
Andy Hung972bec12023-08-31 16:13:39 -07001780 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001781 return getEffect_l(sessionId, effectId);
1782}
1783
Andy Hungee58e4a2023-07-07 13:47:37 -07001784sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung440901d2023-06-29 21:19:25 -07001785 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
Andy Hung116bc262023-06-20 18:56:17 -07001787 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001788 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1789}
1790
Andy Hungee58e4a2023-07-07 13:47:37 -07001791std::vector<int> ThreadBase::getEffectIds_l(audio_session_t sessionId) const
Eric Laurent6c796322019-04-09 14:13:17 -07001792{
Andy Hung116bc262023-06-20 18:56:17 -07001793 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent6c796322019-04-09 14:13:17 -07001794 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1795}
1796
Andy Hung972bec12023-08-31 16:13:39 -07001797// PlaybackThread::addEffect_ll() must be called with AudioFlinger::mutex() and
1798// ThreadBase::mutex() held
1799status_t ThreadBase::addEffect_ll(const sp<IAfEffectModule>& effect)
Eric Laurent81784c32012-11-19 14:55:58 -08001800{
1801 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001802 audio_session_t sessionId = effect->sessionId();
Andy Hung116bc262023-06-20 18:56:17 -07001803 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001804 bool chainCreated = false;
1805
Eric Laurent5baf2af2013-09-12 17:37:00 -07001806 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Andy Hung972bec12023-08-31 16:13:39 -07001807 "%s: on offloaded thread %p: effect %s does not support offload flags %#x",
1808 __func__, this, effect->desc().name, effect->desc().flags);
Eric Laurent5baf2af2013-09-12 17:37:00 -07001809
Eric Laurent81784c32012-11-19 14:55:58 -08001810 if (chain == 0) {
1811 // create a new chain for this session
Andy Hung972bec12023-08-31 16:13:39 -07001812 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hung116bc262023-06-20 18:56:17 -07001813 chain = IAfEffectChain::create(this, sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08001814 addEffectChain_l(chain);
1815 chain->setStrategy(getStrategyForSession_l(sessionId));
1816 chainCreated = true;
1817 }
Andy Hung972bec12023-08-31 16:13:39 -07001818 ALOGV("%s: %p chain %p effect %p", __func__, this, chain.get(), effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001819
1820 if (chain->getEffectFromId_l(effect->id()) != 0) {
Andy Hung972bec12023-08-31 16:13:39 -07001821 ALOGW("%s: %p effect %s already present in chain %p",
1822 __func__, this, effect->desc().name, chain.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001823 return BAD_VALUE;
1824 }
1825
Eric Laurent5baf2af2013-09-12 17:37:00 -07001826 effect->setOffloaded(mType == OFFLOAD, mId);
1827
Eric Laurent81784c32012-11-19 14:55:58 -08001828 status_t status = chain->addEffect_l(effect);
1829 if (status != NO_ERROR) {
1830 if (chainCreated) {
1831 removeEffectChain_l(chain);
1832 }
1833 return status;
1834 }
1835
jiabin8f278ee2019-11-11 12:16:27 -08001836 effect->setDevices(outDeviceTypeAddrs());
1837 effect->setInputDevice(inDeviceTypeAddr());
Andy Hung583043b2023-07-17 17:05:00 -07001838 effect->setMode(mAfThreadCallback->getMode());
Eric Laurent81784c32012-11-19 14:55:58 -08001839 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001840
Eric Laurent81784c32012-11-19 14:55:58 -08001841 return NO_ERROR;
1842}
1843
Andy Hungee58e4a2023-07-07 13:47:37 -07001844void ThreadBase::removeEffect_l(const sp<IAfEffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001845
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001846 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001847 effect_descriptor_t desc = effect->desc();
1848 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1849 detachAuxEffect_l(effect->id());
1850 }
1851
Andy Hung116bc262023-06-20 18:56:17 -07001852 sp<IAfEffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001853 if (chain != 0) {
1854 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001855 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001856 removeEffectChain_l(chain);
1857 }
1858 } else {
1859 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1860 }
1861}
1862
Andy Hungee58e4a2023-07-07 13:47:37 -07001863void ThreadBase::lockEffectChains_l(
Andy Hung116bc262023-06-20 18:56:17 -07001864 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001865NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::lock()
Eric Laurent81784c32012-11-19 14:55:58 -08001866{
1867 effectChains = mEffectChains;
1868 for (size_t i = 0; i < mEffectChains.size(); i++) {
Andy Hungf65f5a72023-08-29 12:19:17 -07001869 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001870 }
1871}
1872
Andy Hungee58e4a2023-07-07 13:47:37 -07001873void ThreadBase::unlockEffectChains(
Andy Hung116bc262023-06-20 18:56:17 -07001874 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung920f6572022-10-06 12:09:49 -07001875NO_THREAD_SAFETY_ANALYSIS // calls EffectChain::unlock()
Eric Laurent81784c32012-11-19 14:55:58 -08001876{
1877 for (size_t i = 0; i < effectChains.size(); i++) {
Andy Hungf65f5a72023-08-29 12:19:17 -07001878 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001879 }
1880}
1881
Andy Hungee58e4a2023-07-07 13:47:37 -07001882sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
Andy Hung972bec12023-08-31 16:13:39 -07001884 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001885 return getEffectChain_l(sessionId);
1886}
1887
Andy Hungee58e4a2023-07-07 13:47:37 -07001888sp<IAfEffectChain> ThreadBase::getEffectChain_l(audio_session_t sessionId)
Glenn Kastend848eb42016-03-08 13:42:11 -08001889 const
Eric Laurent81784c32012-11-19 14:55:58 -08001890{
1891 size_t size = mEffectChains.size();
1892 for (size_t i = 0; i < size; i++) {
1893 if (mEffectChains[i]->sessionId() == sessionId) {
1894 return mEffectChains[i];
1895 }
1896 }
1897 return 0;
1898}
1899
Andy Hungee58e4a2023-07-07 13:47:37 -07001900void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001901{
Andy Hung972bec12023-08-31 16:13:39 -07001902 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08001903 size_t size = mEffectChains.size();
1904 for (size_t i = 0; i < size; i++) {
1905 mEffectChains[i]->setMode_l(mode);
1906 }
1907}
1908
Andy Hungee58e4a2023-07-07 13:47:37 -07001909void ThreadBase::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07001910{
1911 config->type = AUDIO_PORT_TYPE_MIX;
1912 config->ext.mix.handle = mId;
1913 config->sample_rate = mSampleRate;
Mikhail Naganov88d54da2023-09-11 11:53:50 -07001914 config->format = mHALFormat;
Eric Laurent83b88082014-06-20 18:31:16 -07001915 config->channel_mask = mChannelMask;
1916 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1917 AUDIO_PORT_CONFIG_FORMAT;
1918}
1919
Andy Hungee58e4a2023-07-07 13:47:37 -07001920void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001921{
Andy Hung972bec12023-08-31 16:13:39 -07001922 audio_utils::lock_guard _l(mutex());
Eric Laurent72e3f392015-05-20 14:43:50 -07001923 if (mSystemReady) {
1924 return;
1925 }
1926 mSystemReady = true;
1927
1928 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1929 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1930 }
1931 mPendingConfigEvents.clear();
1932}
1933
Andy Hungdae27702016-10-31 14:01:16 -07001934template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001935ssize_t ThreadBase::ActiveTracks<T>::add(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001936 ssize_t index = mActiveTracks.indexOf(track);
1937 if (index >= 0) {
1938 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1939 return index;
1940 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001941 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001942 mActiveTracksGeneration++;
1943 mLatestActiveTrack = track;
Atneya Nair166663a2023-06-27 19:16:24 -07001944 track->beginBatteryAttribution();
Kevin Rocard069c2712018-03-29 19:09:14 -07001945 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001946 return mActiveTracks.add(track);
1947}
1948
1949template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001950ssize_t ThreadBase::ActiveTracks<T>::remove(const sp<T>& track) {
Andy Hungdae27702016-10-31 14:01:16 -07001951 ssize_t index = mActiveTracks.remove(track);
1952 if (index < 0) {
1953 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1954 return index;
1955 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001956 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001957 mActiveTracksGeneration++;
Atneya Nair166663a2023-06-27 19:16:24 -07001958 track->endBatteryAttribution();
Andy Hungdae27702016-10-31 14:01:16 -07001959 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001960 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001961#ifdef TEE_SINK
1962 track->dumpTee(-1 /* fd */, "_REMOVE");
1963#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001964 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001965 return index;
1966}
1967
1968template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001969void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001970 for (const sp<T> &track : mActiveTracks) {
Atneya Nair166663a2023-06-27 19:16:24 -07001971 track->endBatteryAttribution();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001972 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001973 }
1974 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001975 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001976 mActiveTracks.clear();
1977 mLatestActiveTrack.clear();
Andy Hungdae27702016-10-31 14:01:16 -07001978}
1979
1980template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001981void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung920f6572022-10-06 12:09:49 -07001982 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001983 // Updates ActiveTracks client uids to the thread wakelock.
1984 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1985 thread->updateWakeLockUids_l(getWakeLockUids());
1986 mLastActiveTracksGeneration = mActiveTracksGeneration;
1987 }
Andy Hungdae27702016-10-31 14:01:16 -07001988}
Eric Laurent83b88082014-06-20 18:31:16 -07001989
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001990template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07001991bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001992 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001993 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001994
1995 for (const sp<T> &track : mActiveTracks) {
1996 // Do not short-circuit as all hasChanged states must be reset
1997 // as all the metadata are going to be sent
1998 hasChanged |= track->readAndClearHasChanged();
1999 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002000 return hasChanged;
2001}
2002
2003template <typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002004void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002005 const char *funcName, const sp<T> &track) const {
2006 if (mLocalLog != nullptr) {
2007 String8 result;
2008 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002009 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002010 }
2011}
2012
Andy Hungee58e4a2023-07-07 13:47:37 -07002013void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002014{
2015 // Thread could be blocked waiting for async
2016 // so signal it to handle state changes immediately
2017 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2018 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2019 mSignalPending = true;
Andy Hungc5007f82023-08-29 14:26:09 -07002020 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002021}
2022
Andy Hungd0979812019-02-21 15:51:44 -08002023// Call only from threadLoop() or when it is idle.
2024// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hungee58e4a2023-07-07 13:47:37 -07002025void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08002026{
2027 // Do not log if we have no stats.
2028 // We choose the timestamp verifier because it is the most likely item to be present.
2029 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2030 if (nstats == 0) {
2031 return;
2032 }
2033
2034 // Don't log more frequently than once per 12 hours.
2035 // We use BOOTTIME to include suspend time.
2036 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2037 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2038 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2039 return;
2040 }
2041
2042 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2043 mLastRecordedTimeNs = timeNs;
2044
Ray Essickf27e9872019-12-07 06:28:46 -08002045 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002046
2047#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2048
2049 // thread configuration
2050 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2051 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2052 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2053 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2054 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2055 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2056 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002057 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2058 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002059
2060 // thread statistics
2061 if (mIoJitterMs.getN() > 0) {
2062 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2063 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2064 }
2065 if (mProcessTimeMs.getN() > 0) {
2066 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2067 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2068 }
2069 const auto tsjitter = mTimestampVerifier.getJitterMs();
2070 if (tsjitter.getN() > 0) {
2071 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2072 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2073 }
2074 if (mLatencyMs.getN() > 0) {
2075 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2076 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2077 }
Robert Wu06db0a32021-08-10 19:05:34 +00002078 if (mMonopipePipeDepthStats.getN() > 0) {
2079 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2080 mMonopipePipeDepthStats.getMean());
2081 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2082 mMonopipePipeDepthStats.getStdDev());
2083 }
Andy Hungd0979812019-02-21 15:51:44 -08002084
2085 item->selfrecord();
2086}
2087
Andy Hungee58e4a2023-07-07 13:47:37 -07002088product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002089{
Andy Hung583043b2023-07-17 17:05:00 -07002090 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002091 return PRODUCT_STRATEGY_NONE;
2092 }
2093 return AudioSystem::getStrategyForStream(stream);
2094}
2095
Andy Hungc5007f82023-08-29 14:26:09 -07002096// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002097void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002098 const sp<audio_utils::MelProcessor>& /*processor*/)
2099{
2100 // Do nothing
2101 ALOGW("%s: ThreadBase does not support CSD", __func__);
2102}
2103
Andy Hungc5007f82023-08-29 14:26:09 -07002104// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002105void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002106{
2107 // Do nothing
2108 ALOGW("%s: ThreadBase does not support CSD", __func__);
2109}
2110
Eric Laurent81784c32012-11-19 14:55:58 -08002111// ----------------------------------------------------------------------------
2112// Playback
2113// ----------------------------------------------------------------------------
2114
Andy Hung583043b2023-07-17 17:05:00 -07002115PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002116 AudioStreamOut* output,
2117 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002118 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002119 bool systemReady,
2120 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07002121 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002122 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung81994d62023-07-20 21:44:14 -07002123 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002124 mMixerBuffer(NULL),
2125 mMixerBufferSize(0),
2126 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2127 mMixerBufferValid(false),
Andy Hung81994d62023-07-20 21:44:14 -07002128 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002129 mEffectBuffer(NULL),
2130 mEffectBufferSize(0),
2131 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2132 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002133 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002134 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002135 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002136 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002137 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002138 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002139 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002140 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002141 mMixerStatus(MIXER_IDLE),
2142 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung8fe87eb2023-07-20 21:31:38 -07002143 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002144 mBytesRemaining(0),
2145 mCurrentWriteLength(0),
2146 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002147 mWriteAckSequence(0),
2148 mDrainSequence(0),
Andy Hung1d2d2aea2023-07-19 16:22:58 -07002149 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002150 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002151 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002152 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002153 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl65e90012022-07-27 18:01:07 +02002154 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002155 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002156{
Glenn Kastend7dca052015-03-05 16:05:54 -08002157 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07002158 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002159
Andy Hungc5007f82023-08-29 14:26:09 -07002160 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002161 // it would be safer to explicitly pass initial masterVolume/masterMute as
2162 // parameter.
2163 //
2164 // If the HAL we are using has support for master volume or master mute,
2165 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2166 // and the mute set to false).
Andy Hung583043b2023-07-17 17:05:00 -07002167 mMasterVolume = afThreadCallback->masterVolume_l();
2168 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002169 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002170 if (mOutput->audioHwDev->canSetMasterVolume()) {
2171 mMasterVolume = 1.0;
2172 }
2173
2174 if (mOutput->audioHwDev->canSetMasterMute()) {
2175 mMasterMute = false;
2176 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002177 mIsMsdDevice = strcmp(
2178 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002179 }
2180
Eric Laurentf1f22e72021-07-13 14:04:14 +02002181 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2182 mMixerChannelMask = mixerConfig->channel_mask;
2183 }
2184
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002185 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002186
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002187 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002188 && mMixerChannelMask != mChannelMask) {
2189 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2190 mChannelMask, mMixerChannelMask);
2191 }
2192
Andy Hungc8fddf32018-08-08 18:32:37 -07002193 // TODO: We may also match on address as well as device type for
2194 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002195 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002196 // TODO: This property should be ensure that only contains one single device type.
2197 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2198 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002199 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2200 : AUDIO_DEVICE_NONE));
2201 }
2202
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002203 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2204 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002205 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -07002206 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002207 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002208 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002209 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2210 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002211 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2212 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002213}
2214
Andy Hungee58e4a2023-07-07 13:47:37 -07002215PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002216{
Andy Hung583043b2023-07-17 17:05:00 -07002217 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002218 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002219 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002220 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002221 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002222}
2223
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002224// Thread virtuals
2225
Andy Hungee58e4a2023-07-07 13:47:37 -07002226void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002227{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002228 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002229 ALOGE("The stream is not open yet"); // This should not happen.
2230 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002231 // Callbacks take strong or weak pointers as a parameter.
2232 // Since PlaybackThread passes itself as a callback handler, it can only
2233 // be done outside of the constructor. Creating weak and especially strong
2234 // pointers to a refcounted object in its own constructor is strongly
2235 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2236 // Even if a function takes a weak pointer, it is possible that it will
2237 // need to convert it to a strong pointer down the line.
2238 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2239 mOutput->stream->setCallback(this) == OK) {
2240 mUseAsyncWrite = true;
Andy Hungee58e4a2023-07-07 13:47:37 -07002241 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002242 }
2243
jiabinf6eb4c32020-02-25 14:06:25 -08002244 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002245 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002246 }
2247 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002248 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002249 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002250}
2251
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002252// ThreadBase virtuals
Andy Hungee58e4a2023-07-07 13:47:37 -07002253void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002254{
2255 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002256 status_t result = mOutput->stream->exit();
2257 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002258}
2259
Andy Hungee58e4a2023-07-07 13:47:37 -07002260void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002261{
Eric Laurent81784c32012-11-19 14:55:58 -08002262 String8 result;
2263
Marco Nelissenb2208842014-02-07 14:00:50 -08002264 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002265 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2266 const stream_type_t *st = &mStreamTypes[i];
2267 if (i > 0) {
2268 result.appendFormat(", ");
2269 }
2270 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2271 if (st->mute) {
2272 result.append("M");
2273 }
2274 }
2275 result.append("\n");
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002276 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002277 result.clear();
2278
Eric Laurent81784c32012-11-19 14:55:58 -08002279 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2280 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002281 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002282 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002283
2284 size_t numtracks = mTracks.size();
2285 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002286 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002287 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002288 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002289 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002290 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002291 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002292 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002293 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002294 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002295 if (track != 0) {
2296 bool active = mActiveTracks.indexOf(track) >= 0;
2297 if (active) {
2298 numactiveseen++;
2299 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002300 result.append(prefix);
2301 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002302 }
2303 }
2304 } else {
2305 result.append("\n");
2306 }
2307 if (numactiveseen != numactive) {
2308 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002309 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002310 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002311 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002312 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002313 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002314 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002315 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002316 result.append(prefix);
2317 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002318 }
2319 }
2320 }
2321
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002322 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002323}
2324
Andy Hungee58e4a2023-07-07 13:47:37 -07002325void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002326{
Andy Hung04cb8f72020-03-20 13:44:33 -07002327 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002328 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002329 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2330 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002331 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2332 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2333 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2334 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002335 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002336 dprintf(fd, " Total writes: %d\n", mNumWrites);
2337 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2338 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2339 dprintf(fd, " Suspend count: %d\n", mSuspended);
2340 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2341 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2342 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2343 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002344 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002345 AudioStreamOut *output = mOutput;
2346 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002347 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002348 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002349 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2350 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2351 if (mPipeSink.get() != nullptr) {
2352 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2353 }
2354 if (output != nullptr) {
2355 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002356 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358}
2359
Andy Hungc5007f82023-08-29 14:26:09 -07002360// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002361sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07002362 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002363 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002364 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002365 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002366 audio_format_t format,
2367 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002368 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002369 size_t *pNotificationFrameCount,
2370 uint32_t notificationsPerBuffer,
2371 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002372 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002373 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002374 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002375 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002376 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002377 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002378 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002379 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002380 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002381 bool isSpatialized,
jiabin94ed47c2023-07-27 23:34:20 +00002382 bool isBitPerfect,
2383 audio_output_flags_t *afTrackFlags)
Eric Laurent81784c32012-11-19 14:55:58 -08002384{
Glenn Kasten74935e42013-12-19 08:56:45 -08002385 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002386 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07002387 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002388 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002389 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002390 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002391 uint32_t sampleRate;
2392
2393 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2394 lStatus = BAD_VALUE;
2395 goto Exit;
2396 }
Eric Laurent21da6472017-11-09 16:29:26 -08002397
2398 if (*pSampleRate == 0) {
2399 *pSampleRate = mSampleRate;
2400 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002401 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002402
2403 // special case for FAST flag considered OK if fast mixer is present
2404 if (hasFastMixer()) {
2405 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2406 }
2407
2408 // Check if requested flags are compatible with output stream flags
2409 if ((*flags & outputFlags) != *flags) {
2410 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2411 *flags, outputFlags);
2412 *flags = (audio_output_flags_t)(*flags & outputFlags);
2413 }
Eric Laurent81784c32012-11-19 14:55:58 -08002414
jiabinc658e452022-10-21 20:52:21 +00002415 if (isBitPerfect) {
Andy Hung116bc262023-06-20 18:56:17 -07002416 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002417 if (chain.get() != nullptr) {
2418 // Bit-perfect is required according to the configuration and preferred mixer
2419 // attributes, but it is not in the output flag from the client's request. Explicitly
2420 // adding bit-perfect flag to check the compatibility
2421 audio_output_flags_t flagsToCheck =
2422 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2423 chain->checkOutputFlagCompatibility(&flagsToCheck);
2424 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2425 ALOGE("%s cannot create track as there is data-processing effect attached to "
2426 "given session id(%d)", __func__, sessionId);
2427 lStatus = BAD_VALUE;
2428 goto Exit;
2429 }
2430 *flags = flagsToCheck;
2431 }
2432 }
2433
Eric Laurent81784c32012-11-19 14:55:58 -08002434 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002435 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002436 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002437 // PCM data
2438 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002439 // TODO: extract as a data library function that checks that a computationally
2440 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002441 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002442 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2443 (channelMask == AUDIO_CHANNEL_OUT_MONO
2444 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002445 // hardware sample rate
2446 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002447 // normal mixer has an associated fast mixer
2448 hasFastMixer() &&
2449 // there are sufficient fast track slots available
2450 (mFastTrackAvailMask != 0)
2451 // FIXME test that MixerThread for this fast track has a capable output HAL
2452 // FIXME add a permission test also?
2453 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002454 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2455 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002456 // read the fast track multiplier property the first time it is needed
2457 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2458 if (ok != 0) {
2459 ALOGE("%s pthread_once failed: %d", __func__, ok);
2460 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002461 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002462 }
Eric Laurent4c415062016-06-17 16:14:16 -07002463
2464 // check compatibility with audio effects.
Andy Hungc5007f82023-08-29 14:26:09 -07002465 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002466 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002467 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002468 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002469 AUDIO_SESSION_OUTPUT_STAGE,
2470 AUDIO_SESSION_OUTPUT_MIX,
2471 sessionId,
2472 }) {
Andy Hung116bc262023-06-20 18:56:17 -07002473 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002474 if (chain.get() != nullptr) {
2475 audio_output_flags_t old = *flags;
2476 chain->checkOutputFlagCompatibility(flags);
2477 if (old != *flags) {
2478 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2479 (int)session, (int)old, (int)*flags);
2480 }
Eric Laurent4c415062016-06-17 16:14:16 -07002481 }
2482 }
2483 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002484 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002485 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2486 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002487 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002488 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002489 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002490 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002491 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002492 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002493 audio_is_linear_pcm(format), channelMask, sampleRate,
2494 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002495 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002496 }
2497 }
Eric Laurent21da6472017-11-09 16:29:26 -08002498
2499 if (!audio_has_proportional_frames(format)) {
2500 if (sharedBuffer != 0) {
2501 // Same comment as below about ignoring frameCount parameter for set()
2502 frameCount = sharedBuffer->size();
2503 } else if (frameCount == 0) {
2504 frameCount = mNormalFrameCount;
2505 }
2506 if (notificationFrameCount != frameCount) {
2507 notificationFrameCount = frameCount;
2508 }
2509 } else if (sharedBuffer != 0) {
2510 // FIXME: Ensure client side memory buffers need
2511 // not have additional alignment beyond sample
2512 // (e.g. 16 bit stereo accessed as 32 bit frame).
2513 size_t alignment = audio_bytes_per_sample(format);
2514 if (alignment & 1) {
2515 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2516 alignment = 1;
2517 }
2518 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2519 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2520 if (channelCount > 1) {
2521 // More than 2 channels does not require stronger alignment than stereo
2522 alignment <<= 1;
2523 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002524 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002525 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002526 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002527 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002528 goto Exit;
2529 }
Eric Laurent21da6472017-11-09 16:29:26 -08002530
2531 // When initializing a shared buffer AudioTrack via constructors,
2532 // there's no frameCount parameter.
2533 // But when initializing a shared buffer AudioTrack via set(),
2534 // there _is_ a frameCount parameter. We silently ignore it.
2535 frameCount = sharedBuffer->size() / frameSize;
2536 } else {
2537 size_t minFrameCount = 0;
2538 // For fast tracks we try to respect the application's request for notifications per buffer.
2539 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2540 if (notificationsPerBuffer > 0) {
2541 // Avoid possible arithmetic overflow during multiplication.
2542 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2543 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2544 notificationsPerBuffer, mFrameCount);
2545 } else {
2546 minFrameCount = mFrameCount * notificationsPerBuffer;
2547 }
2548 }
2549 } else {
2550 // For normal PCM streaming tracks, update minimum frame count.
2551 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2552 // cover audio hardware latency.
2553 // This is probably too conservative, but legacy application code may depend on it.
2554 // If you change this calculation, also review the start threshold which is related.
2555 uint32_t latencyMs = latency_l();
2556 if (latencyMs == 0) {
2557 ALOGE("Error when retrieving output stream latency");
2558 lStatus = UNKNOWN_ERROR;
2559 goto Exit;
2560 }
2561
2562 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2563 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2564
Eric Laurent81784c32012-11-19 14:55:58 -08002565 }
Eric Laurent21da6472017-11-09 16:29:26 -08002566 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002567 frameCount = minFrameCount;
2568 }
Eric Laurent81784c32012-11-19 14:55:58 -08002569 }
Eric Laurent21da6472017-11-09 16:29:26 -08002570
2571 // Make sure that application is notified with sufficient margin before underrun.
2572 // The client can divide the AudioTrack buffer into sub-buffers,
2573 // and expresses its desire to server as the notification frame count.
2574 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2575 size_t maxNotificationFrames;
2576 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2577 // notify every HAL buffer, regardless of the size of the track buffer
2578 maxNotificationFrames = mFrameCount;
2579 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002580 // Triple buffer the notification period for a triple buffered mixer period;
2581 // otherwise, double buffering for the notification period is fine.
2582 //
2583 // TODO: This should be moved to AudioTrack to modify the notification period
2584 // on AudioTrack::setBufferSizeInFrames() changes.
2585 const int nBuffering =
2586 (uint64_t{frameCount} * mSampleRate)
2587 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2588
Eric Laurent21da6472017-11-09 16:29:26 -08002589 maxNotificationFrames = frameCount / nBuffering;
2590 // If client requested a fast track but this was denied, then use the smaller maximum.
2591 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2592 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2593 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2594 maxNotificationFrames = maxNotificationFramesFastDenied;
2595 }
2596 }
2597 }
2598 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2599 if (notificationFrameCount == 0) {
2600 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2601 maxNotificationFrames, frameCount);
2602 } else {
2603 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2604 notificationFrameCount, maxNotificationFrames, frameCount);
2605 }
2606 notificationFrameCount = maxNotificationFrames;
2607 }
2608 }
2609
Glenn Kasten74935e42013-12-19 08:56:45 -08002610 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002611 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002612
Glenn Kastenc3df8382014-03-13 15:05:25 -07002613 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002614 case BIT_PERFECT:
2615 if (isBitPerfect) {
2616 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2617 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2618 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2619 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2620 mChannelMask);
2621 lStatus = BAD_VALUE;
2622 goto Exit;
2623 }
2624 }
2625 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002626
2627 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002628 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002629 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002630 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2631 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002632 sampleRate, format, channelMask, mOutput, mFormat);
2633 lStatus = BAD_VALUE;
2634 goto Exit;
2635 }
2636 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002637 break;
2638
2639 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002640 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002641 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2642 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002643 sampleRate, format, channelMask, mOutput, mFormat);
2644 lStatus = BAD_VALUE;
2645 goto Exit;
2646 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002647 break;
2648
2649 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002650 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002651 ALOGE("createTrack_l() Bad parameter: format %#x \""
2652 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002653 format, mOutput, mFormat);
2654 lStatus = BAD_VALUE;
2655 goto Exit;
2656 }
Andy Hungcd044842014-08-07 11:04:34 -07002657 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002658 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2659 lStatus = BAD_VALUE;
2660 goto Exit;
2661 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002662 break;
2663
Eric Laurent81784c32012-11-19 14:55:58 -08002664 }
2665
2666 lStatus = initCheck();
2667 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002668 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002669 goto Exit;
2670 }
2671
Andy Hungc5007f82023-08-29 14:26:09 -07002672 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07002673 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002674
2675 // all tracks in same audio session must share the same routing strategy otherwise
2676 // conflicts will happen when tracks are moved from one output to another by audio policy
2677 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002678 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002679 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002680 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002681 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002682 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002683 if (sessionId == t->sessionId() && strategy != actual) {
2684 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2685 strategy, actual);
2686 lStatus = BAD_VALUE;
2687 goto Exit;
2688 }
2689 }
2690 }
2691
yucliuc9c49cd2020-07-13 16:25:21 -07002692 // Set DIRECT flag if current thread is DirectOutputThread. This can
2693 // happen when the playback is rerouted to direct output thread by
2694 // dynamic audio policy.
2695 // Do NOT report the flag changes back to client, since the client
2696 // doesn't explicitly request a direct flag.
2697 audio_output_flags_t trackFlags = *flags;
2698 if (mType == DIRECT) {
2699 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2700 }
jiabin94ed47c2023-07-27 23:34:20 +00002701 *afTrackFlags = trackFlags;
yucliuc9c49cd2020-07-13 16:25:21 -07002702
Andy Hung8d31fd22023-06-26 19:20:57 -07002703 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002704 channelMask, frameCount,
2705 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002706 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung8d31fd22023-06-26 19:20:57 -07002707 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002708 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002709
Glenn Kasten03003332013-08-06 15:40:54 -07002710 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2711 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002712 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002713 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002714 goto Exit;
2715 }
2716 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002717 {
Andy Hung972bec12023-08-31 16:13:39 -07002718 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002719 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002720 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002721 }
2722 }
Eric Laurent81784c32012-11-19 14:55:58 -08002723
Andy Hung116bc262023-06-20 18:56:17 -07002724 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002725 if (chain != 0) {
2726 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2727 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002728 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002729 chain->incTrackCnt();
2730 }
2731
Eric Laurent05067782016-06-01 18:27:28 -07002732 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002733 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2734 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2735 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002736 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002737 }
2738 }
2739
2740 lStatus = NO_ERROR;
2741
2742Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002743 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002744 return track;
2745}
2746
Andy Hung1bc088a2018-02-09 15:57:31 -08002747template<typename T>
Andy Hungee58e4a2023-07-07 13:47:37 -07002748ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002749{
Andy Hungc0691382018-09-12 18:01:57 -07002750 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002751 const ssize_t index = mTracks.remove(track);
2752 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002753 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002754 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002755 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002756 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002757 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002758 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002759 }
2760 return index;
2761}
2762
Andy Hungee58e4a2023-07-07 13:47:37 -07002763uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002764{
2765 return latency;
2766}
2767
Andy Hungee58e4a2023-07-07 13:47:37 -07002768uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002769{
Andy Hung972bec12023-08-31 16:13:39 -07002770 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002771 return latency_l();
2772}
Andy Hungee58e4a2023-07-07 13:47:37 -07002773uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002774{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002775 uint32_t latency;
2776 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2777 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002778 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002779 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002780}
2781
Andy Hungee58e4a2023-07-07 13:47:37 -07002782void PlaybackThread::setMasterVolume(float value)
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 // Don't apply master volume in SW if our HAL can do it for us.
2786 if (mOutput && mOutput->audioHwDev &&
2787 mOutput->audioHwDev->canSetMasterVolume()) {
2788 mMasterVolume = 1.0;
2789 } else {
2790 mMasterVolume = value;
2791 }
2792}
2793
Andy Hungee58e4a2023-07-07 13:47:37 -07002794void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002795{
2796 mMasterBalance.store(balance);
2797}
2798
Andy Hungee58e4a2023-07-07 13:47:37 -07002799void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002800{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002801 if (isDuplicating()) {
2802 return;
2803 }
Andy Hung972bec12023-08-31 16:13:39 -07002804 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002805 // Don't apply master mute in SW if our HAL can do it for us.
2806 if (mOutput && mOutput->audioHwDev &&
2807 mOutput->audioHwDev->canSetMasterMute()) {
2808 mMasterMute = false;
2809 } else {
2810 mMasterMute = muted;
2811 }
2812}
2813
Andy Hungee58e4a2023-07-07 13:47:37 -07002814void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002815{
Andy Hung972bec12023-08-31 16:13:39 -07002816 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002817 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002818 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002819}
2820
Andy Hungee58e4a2023-07-07 13:47:37 -07002821void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002822{
Andy Hung972bec12023-08-31 16:13:39 -07002823 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002824 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002825 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002826}
2827
Andy Hungee58e4a2023-07-07 13:47:37 -07002828float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002829{
Andy Hung972bec12023-08-31 16:13:39 -07002830 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002831 return mStreamTypes[stream].volume;
2832}
2833
Andy Hungee58e4a2023-07-07 13:47:37 -07002834void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002835{
2836 mOutput->stream->setVolume(left, right);
2837}
2838
Andy Hungc5007f82023-08-29 14:26:09 -07002839// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07002840status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hungc5007f82023-08-29 14:26:09 -07002841NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08002842{
2843 status_t status = ALREADY_EXISTS;
2844
Eric Laurent81784c32012-11-19 14:55:58 -08002845 if (mActiveTracks.indexOf(track) < 0) {
2846 // the track is newly added, make sure it fills up all its
2847 // buffers before playing. This is to ensure the client will
2848 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002849 if (track->isExternalTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002850 IAfTrackBase::track_state state = track->state();
Andy Hungc5007f82023-08-29 14:26:09 -07002851 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002852 status = AudioSystem::startOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002853 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002854 // abort track was stopped/paused while we released the lock
Andy Hung8d31fd22023-06-26 19:20:57 -07002855 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002856 if (status == NO_ERROR) {
Andy Hungc5007f82023-08-29 14:26:09 -07002857 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002858 AudioSystem::stopOutput(track->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07002859 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002860 }
2861 return INVALID_OPERATION;
2862 }
2863 // abort if start is rejected by audio policy manager
2864 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002865 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2866 // current playback thread is reopened, which may happen when clients set preferred
2867 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2868 // immediately.
2869 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002870 }
2871#ifdef ADD_BATTERY_DATA
2872 // to track the speaker usage
2873 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2874#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002875 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876 }
2877
Eric Laurent51716182016-02-29 18:00:56 -08002878 // set retry count for buffer fill
2879 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002880 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002881 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002882 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002883 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002884 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002885 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002886 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07002887 track->retryCount() = kMaxTrackStartupRetries;
2888 track->fillingStatus() =
2889 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002890 }
2891
Andy Hung116bc262023-06-20 18:56:17 -07002892 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002893 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2894 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2895 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002896 // Unlock due to VibratorService will lock for this call and will
2897 // call Tracks.mute/unmute which also require thread's lock.
Andy Hungc5007f82023-08-29 14:26:09 -07002898 mutex().unlock();
Andy Hung7fb97e12023-07-20 21:23:42 -07002899 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002900 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002901 std::optional<media::AudioVibratorInfo> vibratorInfo;
2902 {
2903 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2904 // used to play this track.
Andy Hung972bec12023-08-31 16:13:39 -07002905 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung583043b2023-07-17 17:05:00 -07002906 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002907 }
Andy Hungc5007f82023-08-29 14:26:09 -07002908 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002909 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002910 if (vibratorInfo) {
2911 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2912 }
2913
jiabin57303cc2018-12-18 15:45:57 -08002914 // Haptic playback should be enabled by vibrator service.
2915 if (track->getHapticPlaybackEnabled()) {
2916 // Disable haptic playback of all active track to ensure only
2917 // one track playing haptic if current track should play haptic.
2918 for (const auto &t : mActiveTracks) {
2919 t->setHapticPlaybackEnabled(false);
2920 }
jiabin245cdd92018-12-07 17:55:15 -08002921 }
jiabine70bc7f2020-06-30 22:07:55 -07002922
2923 // Set haptic intensity for effect
2924 if (chain != nullptr) {
2925 chain->setHapticIntensity_l(track->id(), intensity);
2926 }
jiabin245cdd92018-12-07 17:55:15 -08002927 }
2928
Andy Hung8d31fd22023-06-26 19:20:57 -07002929 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002930 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002931 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002932 if (chain != 0) {
2933 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2934 track->sessionId());
2935 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002936 }
2937
Andy Hungc2b11cb2020-04-22 09:04:01 -07002938 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002939 status = NO_ERROR;
2940 }
2941
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002942 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002943 return status;
2944}
2945
Andy Hungee58e4a2023-07-07 13:47:37 -07002946bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002947{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002948 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002949 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002950 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung8d31fd22023-06-26 19:20:57 -07002951 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002952 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002953 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002954 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002955 if (track->isPausePending()) {
2956 track->pauseAck();
2957 }
Andy Hung8d31fd22023-06-26 19:20:57 -07002958 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002959 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002960
2961 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002962}
2963
Andy Hungee58e4a2023-07-07 13:47:37 -07002964void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002965{
2966 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002967
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002968 String8 result;
2969 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002970 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002971
Eric Laurent81784c32012-11-19 14:55:58 -08002972 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002973 {
Andy Hung972bec12023-08-31 16:13:39 -07002974 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002975 mAudioTrackCallbacks.erase(track);
2976 }
Eric Laurent81784c32012-11-19 14:55:58 -08002977 if (track->isFastTrack()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07002978 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002979 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002980 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2981 mFastTrackAvailMask |= 1 << index;
2982 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung8d31fd22023-06-26 19:20:57 -07002983 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08002984 }
Andy Hung116bc262023-06-20 18:56:17 -07002985 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08002986 if (chain != 0) {
2987 chain->decTrackCnt();
2988 }
2989}
2990
Andy Hungee58e4a2023-07-07 13:47:37 -07002991String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08002992{
Andy Hung972bec12023-08-31 16:13:39 -07002993 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002994 String8 out_s8;
2995 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2996 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002997 }
Andy Hung920f6572022-10-06 12:09:49 -07002998 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08002999}
3000
Andy Hungee58e4a2023-07-07 13:47:37 -07003001status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hung972bec12023-08-31 16:13:39 -07003002 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003003 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003004 return NO_INIT;
3005 }
3006 return mOutput->stream->selectPresentation(presentationId, programId);
3007}
3008
Andy Hungee58e4a2023-07-07 13:47:37 -07003009void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003010 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003011 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003012 sp<AudioIoDescriptor> desc;
3013 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003014 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003015 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003016 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003017 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003018 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3019 mSampleRate, mFormat, mChannelMask,
3020 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3021 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003022 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003023 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003024 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003025 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003026 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003027 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003028 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003029 break;
3030 }
Andy Hung583043b2023-07-17 17:05:00 -07003031 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003032}
3033
Andy Hungee58e4a2023-07-07 13:47:37 -07003034void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003035{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003036 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003037}
3038
Andy Hungee58e4a2023-07-07 13:47:37 -07003039void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003040{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003041 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003042}
3043
Andy Hungee58e4a2023-07-07 13:47:37 -07003044void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003045{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003046 mCallbackThread->setAsyncError();
3047}
3048
Andy Hungee58e4a2023-07-07 13:47:37 -07003049void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003050 const std::basic_string<uint8_t>& metadataBs)
3051{
Andy Hungee58e4a2023-07-07 13:47:37 -07003052 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003053 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hungee58e4a2023-07-07 13:47:37 -07003054 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003055 if (playbackThread == nullptr) {
3056 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3057 return;
3058 }
3059
jiabinf6eb4c32020-02-25 14:06:25 -08003060 audio_utils::metadata::Data metadata =
3061 audio_utils::metadata::dataFromByteString(metadataBs);
3062 if (metadata.empty()) {
3063 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3064 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3065 (int)metadataBs.size());
3066 return;
3067 }
3068
3069 audio_utils::metadata::ByteString metaDataStr =
3070 audio_utils::metadata::byteStringFromData(metadata);
3071 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hung972bec12023-08-31 16:13:39 -07003072 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003073 for (const auto& callbackPair : mAudioTrackCallbacks) {
3074 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003075 }
3076 }).detach();
3077}
3078
Andy Hungee58e4a2023-07-07 13:47:37 -07003079void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003080{
Andy Hung972bec12023-08-31 16:13:39 -07003081 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003082 // reject out of sequence requests
3083 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3084 mWriteAckSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003085 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003086 }
3087}
3088
Andy Hungee58e4a2023-07-07 13:47:37 -07003089void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003090{
Andy Hung972bec12023-08-31 16:13:39 -07003091 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003092 // reject out of sequence requests
3093 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003094 // Register discontinuity when HW drain is completed because that can cause
3095 // the timestamp frame position to reset to 0 for direct and offload threads.
3096 // (Out of sequence requests are ignored, since the discontinuity would be handled
3097 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003098 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003099 mDrainSequence &= ~1;
Andy Hungc5007f82023-08-29 14:26:09 -07003100 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003101 }
3102}
3103
Andy Hungee58e4a2023-07-07 13:47:37 -07003104void PlaybackThread::readOutputParameters_l()
Andy Hung972bec12023-08-31 16:13:39 -07003105NO_THREAD_SAFETY_ANALYSIS
3106// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003107{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003108 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003109 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3110 mSampleRate = audioConfig.sample_rate;
3111 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003112 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003113 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003114 }
Andy Hung81994d62023-07-20 21:44:14 -07003115 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003116 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3117 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003118 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003119
3120 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3121 mMixerChannelMask = mChannelMask;
3122 }
3123
Andy Hunge5412692014-05-16 11:25:07 -07003124 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003125 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003126
Eric Laurentf1f22e72021-07-13 14:04:14 +02003127 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3128
Phil Burkca5e6142015-07-14 09:42:29 -07003129 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003130 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003131 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003132 // Get format from the shim, which will be different than the HAL format
3133 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003134 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003135 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003136 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003137 }
Andy Hung81994d62023-07-20 21:44:14 -07003138 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003139 LOG_FATAL("HAL format %#x not supported for mixed output",
3140 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003141 }
Phil Burk062e67a2015-02-11 13:40:50 -08003142 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003143 result = mOutput->stream->getBufferSize(&mBufferSize);
3144 LOG_ALWAYS_FATAL_IF(result != OK,
3145 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003146 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003147 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003148 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003149 mFrameCount);
3150 }
3151
Eric Laurentd1f69b02014-12-15 14:33:13 -08003152 mHwSupportsPause = false;
3153 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003154 bool supportsPause = false, supportsResume = false;
3155 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3156 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003157 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003158 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003159 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003160 } else if (supportsResume) {
3161 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003162 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003163 }
3164 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003165 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3166 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3167 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003168
Andy Hungfbfc3952015-01-15 13:33:51 -08003169 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3170 // For best precision, we use float instead of the associated output
3171 // device format (typically PCM 16 bit).
3172
3173 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3174 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3175 mBufferSize = mFrameSize * mFrameCount;
3176
3177 // TODO: We currently use the associated output device channel mask and sample rate.
3178 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3179 // (if a valid mask) to avoid premature downmix.
3180 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3181 // instead of the output device sample rate to avoid loss of high frequency information.
3182 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3183 }
3184
Andy Hung09a50072014-02-27 14:30:47 -08003185 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003186 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003187 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003188 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3189 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003190 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3191 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003192
Eric Laurent81784c32012-11-19 14:55:58 -08003193 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3194 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3195 maxNormalFrameCount = maxNormalFrameCount & ~15;
3196 if (maxNormalFrameCount < minNormalFrameCount) {
3197 maxNormalFrameCount = minNormalFrameCount;
3198 }
3199 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3200 if (multiplier <= 1.0) {
3201 multiplier = 1.0;
3202 } else if (multiplier <= 2.0) {
3203 if (2 * mFrameCount <= maxNormalFrameCount) {
3204 multiplier = 2.0;
3205 } else {
3206 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3207 }
3208 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003209 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003210 }
3211 }
3212 mNormalFrameCount = multiplier * mFrameCount;
3213 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003214 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003215 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3216 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003217 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003218 mNormalFrameCount);
3219
Andy Hung08fb1742015-05-31 23:22:10 -07003220 // Check if we want to throttle the processing to no more than 2x normal rate
3221 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003222 mThreadThrottleTimeMs = 0;
3223 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003224 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3225
Andy Hung010a1a12014-03-13 13:57:33 -07003226 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3227 // Originally this was int16_t[] array, need to remove legacy implications.
3228 free(mSinkBuffer);
3229 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003230
Andy Hung5b10a202014-03-13 13:59:29 -07003231 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3232 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3233 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003234 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003235
Andy Hung69aed5f2014-02-25 17:24:40 -08003236 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3237 // drives the output.
3238 free(mMixerBuffer);
3239 mMixerBuffer = NULL;
3240 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003241 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003242 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003243 * audio_bytes_per_sample(mMixerBufferFormat);
3244 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3245 }
Andy Hung98ef9782014-03-04 14:46:50 -08003246 free(mEffectBuffer);
3247 mEffectBuffer = NULL;
3248 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003249 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003250 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003251 * audio_bytes_per_sample(mEffectBufferFormat);
3252 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3253 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003254
Eric Laurentb62d0362021-10-26 17:40:18 +02003255 if (mType == SPATIALIZER) {
3256 free(mPostSpatializerBuffer);
3257 mPostSpatializerBuffer = nullptr;
3258 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3259 * audio_bytes_per_sample(mEffectBufferFormat);
3260 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3261 }
3262
Mikhail Naganov55773032020-10-01 15:08:13 -07003263 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3264 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003265 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3266 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003267 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003268
Eric Laurent81784c32012-11-19 14:55:58 -08003269 // force reconfiguration of effect chains and engines to take new buffer size and audio
3270 // parameters into account
Andy Hungc5007f82023-08-29 14:26:09 -07003271 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003272 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3273 // matter.
Andy Hung972bec12023-08-31 16:13:39 -07003274 // create a copy of mEffectChains as calling moveEffectChain_ll()
3275 // can reorder some effect chains
Andy Hung116bc262023-06-20 18:56:17 -07003276 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003277 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung972bec12023-08-31 16:13:39 -07003278 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003279 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003280 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003281
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003282 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003283 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003284 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07003285 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003286 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3287 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3288 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3289 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3290 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3291 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3292 (int32_t)mHapticChannelMask)
3293 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3294 (int32_t)mHapticChannelCount)
3295 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -07003296 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003297 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3298 (int32_t)mFrameCount) // sic - added HAL
3299 ;
3300 uint32_t latencyMs;
3301 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3302 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3303 }
3304 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003305}
3306
Andy Hungee58e4a2023-07-07 13:47:37 -07003307ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003308{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003309 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003310 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003311 }
3312 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003313 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07003314 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003315 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003316 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003317 }
Kevin Rocard12381092018-04-11 09:19:59 -07003318 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003319 MetadataUpdate change;
3320 change.playbackMetadataUpdate = metadata.tracks;
3321 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003322}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003323
Andy Hungee58e4a2023-07-07 13:47:37 -07003324void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003325 const StreamOutHalInterface::SourceMetadata& metadata)
3326{
3327 mOutput->stream->updateSourceMetadata(metadata);
3328};
3329
Andy Hungee58e4a2023-07-07 13:47:37 -07003330status_t PlaybackThread::getRenderPosition(
Andy Hung440901d2023-06-29 21:19:25 -07003331 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003332{
3333 if (halFrames == NULL || dspFrames == NULL) {
3334 return BAD_VALUE;
3335 }
Andy Hung972bec12023-08-31 16:13:39 -07003336 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003337 if (initCheck() != NO_ERROR) {
3338 return INVALID_OPERATION;
3339 }
Andy Hung818e7a32016-02-16 18:08:07 -08003340 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003341 *halFrames = framesWritten;
3342
3343 if (isSuspended()) {
3344 // return an estimation of rendered frames when the output is suspended
3345 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003346 *dspFrames = (uint32_t)
3347 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003348 return NO_ERROR;
3349 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003350 status_t status;
3351 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003352 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003353 *dspFrames = (size_t)frames;
3354 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003355 }
3356}
3357
Andy Hungee58e4a2023-07-07 13:47:37 -07003358product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003359{
3360 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3361 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3362 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003363 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003364 }
3365 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003366 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003367 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003368 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003369 }
3370 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003371 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003372}
3373
3374
Andy Hungee58e4a2023-07-07 13:47:37 -07003375AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003376{
Andy Hung972bec12023-08-31 16:13:39 -07003377 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003378 return mOutput;
3379}
3380
Andy Hungee58e4a2023-07-07 13:47:37 -07003381AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003382{
Andy Hung972bec12023-08-31 16:13:39 -07003383 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003384 AudioStreamOut *output = mOutput;
3385 mOutput = NULL;
3386 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3387 // must push a NULL and wait for ack
3388 mOutputSink.clear();
3389 mPipeSink.clear();
3390 mNormalSink.clear();
3391 return output;
3392}
3393
Andy Hungc5007f82023-08-29 14:26:09 -07003394// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07003395sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003396{
3397 if (mOutput == NULL) {
3398 return NULL;
3399 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003400 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003401}
3402
Andy Hungee58e4a2023-07-07 13:47:37 -07003403uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003404{
3405 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3406}
3407
Andy Hungee58e4a2023-07-07 13:47:37 -07003408status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003409{
3410 if (!isValidSyncEvent(event)) {
3411 return BAD_VALUE;
3412 }
3413
Andy Hung972bec12023-08-31 16:13:39 -07003414 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003415
3416 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003417 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003418 if (event->triggerSession() == track->sessionId()) {
3419 (void) track->setSyncEvent(event);
3420 return NO_ERROR;
3421 }
3422 }
3423
3424 return NAME_NOT_FOUND;
3425}
3426
Andy Hungee58e4a2023-07-07 13:47:37 -07003427bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003428{
3429 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3430}
3431
Andy Hungee58e4a2023-07-07 13:47:37 -07003432void PlaybackThread::threadLoop_removeTracks(
Andy Hung8d31fd22023-06-26 19:20:57 -07003433 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003434{
Andy Hungfe726a62018-09-27 15:17:25 -07003435 // Miscellaneous track cleanup when removed from the active list,
3436 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003437#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003438 for (const auto& track : tracksToRemove) {
3439 if (track->isExternalTrack()) {
3440 // to track the speaker usage
3441 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003442 }
3443 }
Andy Hungfe726a62018-09-27 15:17:25 -07003444#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003445}
3446
Andy Hungee58e4a2023-07-07 13:47:37 -07003447void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003448{
3449 if (!mMasterMute) {
3450 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003451 if (mOutDeviceTypeAddrs.empty()) {
3452 ALOGD("ro.audio.silent is ignored since no output device is set");
3453 return;
3454 }
jiabinc52b1ff2019-10-31 17:20:42 -07003455 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003456 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3457 return;
3458 }
Eric Laurent81784c32012-11-19 14:55:58 -08003459 if (property_get("ro.audio.silent", value, "0") > 0) {
3460 char *endptr;
3461 unsigned long ul = strtoul(value, &endptr, 0);
3462 if (*endptr == '\0' && ul != 0) {
3463 ALOGD("Silence is golden");
3464 // The setprop command will not allow a property to be changed after
3465 // the first time it is set, so we don't have to worry about un-muting.
3466 setMasterMute_l(true);
3467 }
3468 }
3469 }
3470}
3471
3472// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07003473ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003474{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003475 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003476 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003477 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003478 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003479
3480 // If an NBAIO sink is present, use it to write the normal mixer's submix
3481 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003482
Andy Hung010a1a12014-03-13 13:57:33 -07003483 const size_t count = mBytesRemaining / mFrameSize;
3484
Simon Wilson2d590962012-11-29 15:18:50 -08003485 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003486 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung1d2d2aea2023-07-19 16:22:58 -07003487 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003488 if (screenState != mScreenState) {
3489 mScreenState = screenState;
3490 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3491 if (pipe != NULL) {
3492 pipe->setAvgFrames((mScreenState & 1) ?
3493 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3494 }
3495 }
Andy Hung010a1a12014-03-13 13:57:33 -07003496 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003497 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003498
Eric Laurent81784c32012-11-19 14:55:58 -08003499 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003500 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003501
Andy Hung8946a282018-04-19 20:04:56 -07003502#ifdef TEE_SINK
3503 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3504#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003505 } else {
3506 bytesWritten = framesWritten;
3507 }
3508 // otherwise use the HAL / AudioStreamOut directly
3509 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003510 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003511
Eric Laurentbfb1b832013-01-07 09:53:42 -08003512 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003513 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3514 mWriteAckSequence += 2;
3515 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003517 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003518 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003519 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003520 // FIXME We should have an implementation of timestamps for direct output threads.
3521 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003522 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003523 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003524
Eric Laurentbfb1b832013-01-07 09:53:42 -08003525 if (mUseAsyncWrite &&
3526 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3527 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003528 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003529 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003530 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003531 }
Eric Laurent81784c32012-11-19 14:55:58 -08003532 }
3533
Eric Laurent81784c32012-11-19 14:55:58 -08003534 mNumWrites++;
3535 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003536 if (mStandby) {
3537 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003538 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003539 mStandby = false;
3540 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003541 return bytesWritten;
3542}
3543
Andy Hungc5007f82023-08-29 14:26:09 -07003544// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003545void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003546 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003547{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003548 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003549 if (outputSink != nullptr) {
3550 outputSink->startMelComputation(processor);
3551 }
Vlad Popab042ee62022-10-20 18:05:00 +02003552}
3553
Andy Hungc5007f82023-08-29 14:26:09 -07003554// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07003555void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003556{
3557 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003558 if (outputSink != nullptr) {
3559 outputSink->stopMelComputation();
3560 }
Vlad Popab042ee62022-10-20 18:05:00 +02003561}
3562
Andy Hungee58e4a2023-07-07 13:47:37 -07003563void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003564{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003565 bool supportsDrain = false;
3566 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003567 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3568 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003569 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3570 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003571 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003572 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003573 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003574 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003575 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003576 }
3577}
3578
Andy Hungee58e4a2023-07-07 13:47:37 -07003579void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003580{
Eric Laurent275e8e92014-11-30 15:14:47 -08003581 {
Andy Hung972bec12023-08-31 16:13:39 -07003582 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003583 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003584 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003585 track->invalidate();
3586 }
Andy Hungdae27702016-10-31 14:01:16 -07003587 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3588 // After we exit there are no more track changes sent to BatteryNotifier
3589 // because that requires an active threadLoop.
3590 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3591 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003592 }
Eric Laurent81784c32012-11-19 14:55:58 -08003593}
3594
3595/*
3596The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003597 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003598 - mActiveSleepTimeUs from activeSleepTimeUs()
3599 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003600 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3601 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003602 - maxPeriod from frame count and sample rate (MIXER only)
3603
3604The parameters that affect these derived values are:
3605 - frame count
3606 - frame size
3607 - sample rate
3608 - device type: A2DP or not
3609 - device latency
3610 - format: PCM or not
3611 - active sleep time
3612 - idle sleep time
3613*/
3614
Andy Hungee58e4a2023-07-07 13:47:37 -07003615void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003616{
Andy Hung25c2dac2014-02-27 14:56:00 -08003617 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003618 mActiveSleepTimeUs = activeSleepTimeUs();
3619 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003620
Andy Hung8fe87eb2023-07-20 21:31:38 -07003621 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003622
Eric Laurent42537be2016-01-08 17:16:42 -08003623 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3624 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003625 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003626 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3627 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3628 }
3629 }
Eric Laurent81784c32012-11-19 14:55:58 -08003630}
3631
Andy Hungee58e4a2023-07-07 13:47:37 -07003632bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003633{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003634 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003635 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003636 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003637 size_t size = mTracks.size();
3638 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003639 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003640 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003641 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003642 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003643 }
3644 }
Eric Laurent13084622016-05-17 10:51:49 -07003645 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003646}
3647
Andy Hungee58e4a2023-07-07 13:47:37 -07003648void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003649{
Andy Hung972bec12023-08-31 16:13:39 -07003650 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003651 invalidateTracks_l(streamType);
3652}
3653
Andy Hungee58e4a2023-07-07 13:47:37 -07003654void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07003655 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003656 invalidateTracks_l(portIds);
3657}
3658
Andy Hungee58e4a2023-07-07 13:47:37 -07003659bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003660 bool trackMatch = false;
3661 const size_t size = mTracks.size();
3662 for (size_t i = 0; i < size; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003663 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003664 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3665 t->invalidate();
3666 portIds.erase(t->portId());
3667 trackMatch = true;
3668 }
3669 if (portIds.empty()) {
3670 break;
3671 }
3672 }
3673 return trackMatch;
3674}
3675
jiabinf042b9b2021-05-07 23:46:28 +00003676// getTrackById_l must be called with holding thread lock
Andy Hungee58e4a2023-07-07 13:47:37 -07003677IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003678 audio_port_handle_t trackPortId) {
3679 for (size_t i = 0; i < mTracks.size(); i++) {
3680 if (mTracks[i]->portId() == trackPortId) {
3681 return mTracks[i].get();
3682 }
3683 }
3684 return nullptr;
3685}
3686
Andy Hungee58e4a2023-07-07 13:47:37 -07003687status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003688{
Glenn Kastend848eb42016-03-08 13:42:11 -08003689 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003690 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003691 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003692
Andy Hungd3639922022-04-28 18:00:49 -07003693 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003694 if (!audio_is_global_session(session)) {
3695 // player sessions on a spatializer output will use a dedicated input buffer and
3696 // will either output multi channel to mEffectBuffer if the track is spatilaized
3697 // or stereo to mPostSpatializerBuffer if not spatialized.
3698 uint32_t channelMask;
3699 bool isSessionSpatialized =
3700 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3701 if (isSessionSpatialized) {
3702 channelMask = mMixerChannelMask;
3703 } else {
3704 channelMask = mChannelMask;
3705 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003706 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003707 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003708 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003709 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003710 &halInBuffer);
3711 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003712
Andy Hung583043b2023-07-17 17:05:00 -07003713 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003714 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3715 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3716 &halOutBuffer);
3717 if (result != OK) return result;
3718
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003719 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003720
Mikhail Naganov022b9952017-01-04 16:36:51 -08003721 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3722 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003723 } else {
3724 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3725 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3726 // mPostSpatializerBuffer as output buffer
3727 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung583043b2023-07-17 17:05:00 -07003728 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003729 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3730 if (result != OK) return result;
Andy Hung583043b2023-07-17 17:05:00 -07003731 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003732 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3733 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003734
Eric Laurentb62d0362021-10-26 17:40:18 +02003735 if (session == AUDIO_SESSION_DEVICE) {
3736 halInBuffer = halOutBuffer;
3737 }
3738 }
3739 } else {
Andy Hung583043b2023-07-17 17:05:00 -07003740 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003741 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3742 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3743 &halInBuffer);
3744 if (result != OK) return result;
3745 halOutBuffer = halInBuffer;
3746 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3747 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003748 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003749 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003750 // Only one effect chain can be present in direct output thread and it uses
3751 // the sink buffer as input
3752 if (mType != DIRECT) {
3753 size_t numSamples = mNormalFrameCount
3754 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3755 + mHapticChannelCount);
Andy Hung583043b2023-07-17 17:05:00 -07003756 const status_t allocateStatus =
3757 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003758 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003759 &halInBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07003760 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003761
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003762 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003763 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3764 buffer, session);
3765 }
3766 }
3767 }
3768
3769 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003770 // Attach all tracks with same session ID to this chain.
3771 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003772 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003773 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003774 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3775 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003776 track->setMainBuffer(buffer);
3777 chain->incTrackCnt();
3778 }
3779 }
3780
3781 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003782 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003783 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003784 ALOGV("addEffectChain_l() activating track %p on session %d",
3785 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003786 chain->incActiveTrackCnt();
3787 }
3788 }
3789 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003790
Eric Laurentaaa44472014-09-12 17:41:50 -07003791 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003792 chain->setInBuffer(halInBuffer);
3793 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003794 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3795 // chains list in order to be processed last as it contains output device effects.
3796 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3797 // processing effects specific to an output stream before effects applied to all streams
3798 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003799 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3800 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003801 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003802 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003803 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003804 // Effect chain for other sessions are inserted at beginning of effect
3805 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003806 // sessions is not important.
3807 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003808 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3809 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003810 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003811 size_t size = mEffectChains.size();
3812 size_t i = 0;
3813 for (i = 0; i < size; i++) {
3814 if (mEffectChains[i]->sessionId() < session) {
3815 break;
3816 }
3817 }
3818 mEffectChains.insertAt(chain, i);
3819 checkSuspendOnAddEffectChain_l(chain);
3820
3821 return NO_ERROR;
3822}
3823
Andy Hungee58e4a2023-07-07 13:47:37 -07003824size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003825{
Glenn Kastend848eb42016-03-08 13:42:11 -08003826 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003827
3828 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3829
3830 for (size_t i = 0; i < mEffectChains.size(); i++) {
3831 if (chain == mEffectChains[i]) {
3832 mEffectChains.removeAt(i);
3833 // detach all active tracks from the chain
Andy Hung8d31fd22023-06-26 19:20:57 -07003834 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003835 if (session == track->sessionId()) {
3836 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3837 chain.get(), session);
3838 chain->decActiveTrackCnt();
3839 }
3840 }
3841
3842 // detach all tracks with same session ID from this chain
Andy Hung920f6572022-10-06 12:09:49 -07003843 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003844 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003845 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003846 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003847 chain->decTrackCnt();
3848 }
3849 }
3850 break;
3851 }
3852 }
3853 return mEffectChains.size();
3854}
3855
Andy Hungee58e4a2023-07-07 13:47:37 -07003856status_t PlaybackThread::attachAuxEffect(
Andy Hung8d31fd22023-06-26 19:20:57 -07003857 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003858{
Andy Hung972bec12023-08-31 16:13:39 -07003859 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003860 return attachAuxEffect_l(track, EffectId);
3861}
3862
Andy Hungee58e4a2023-07-07 13:47:37 -07003863status_t PlaybackThread::attachAuxEffect_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07003864 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003865{
3866 status_t status = NO_ERROR;
3867
3868 if (EffectId == 0) {
3869 track->setAuxBuffer(0, NULL);
3870 } else {
3871 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hung116bc262023-06-20 18:56:17 -07003872 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003873 if (effect != 0) {
3874 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3875 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3876 } else {
3877 status = INVALID_OPERATION;
3878 }
3879 } else {
3880 status = BAD_VALUE;
3881 }
3882 }
3883 return status;
3884}
3885
Andy Hungee58e4a2023-07-07 13:47:37 -07003886void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003887{
3888 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07003889 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003890 if (track->auxEffectId() == effectId) {
3891 attachAuxEffect_l(track, 0);
3892 }
3893 }
3894}
3895
Andy Hungee58e4a2023-07-07 13:47:37 -07003896bool PlaybackThread::threadLoop()
Andy Hung920f6572022-10-06 12:09:49 -07003897NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003898{
Andy Hung78d8d952023-05-30 18:10:23 -07003899 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003900
Andy Hung8d31fd22023-06-26 19:20:57 -07003901 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003902
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003903 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003904 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003905
3906 // MIXER
3907 nsecs_t lastWarning = 0;
3908
3909 // DUPLICATING
3910 // FIXME could this be made local to while loop?
3911 writeFrames = 0;
3912
3913 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003914 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003915
Andy Hungd3639922022-04-28 18:00:49 -07003916 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003917 sleepTimeShift = 0;
3918 }
3919
3920 CpuStats cpuStats;
3921 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3922
3923 acquireWakeLock();
3924
Glenn Kasteneef598c2017-04-03 14:41:13 -07003925 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3926 // thread associated with this PlaybackThread.
3927 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3928 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003929 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3930 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003931 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003932 const char *logString = NULL;
3933
rago1bb90822017-05-02 18:31:48 -07003934 // Estimated time for next buffer to be written to hal. This is used only on
3935 // suspended mode (for now) to help schedule the wait time until next iteration.
3936 nsecs_t timeLoopNextNs = 0;
3937
Eric Laurent664539d2013-09-23 18:24:31 -07003938 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003939
Andy Hung2dbffc22018-08-08 18:50:41 -07003940 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003941
Eric Laurentb3f315a2021-07-13 15:09:05 +02003942 sendCheckOutputStageEffectsEvent();
3943
Andy Hung446f4df2019-02-21 12:26:41 -08003944 // loopCount is used for statistics and diagnostics.
3945 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003946 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003947 // Log merge requests are performed during AudioFlinger binder transactions, but
3948 // that does not cover audio playback. It's requested here for that reason.
Andy Hung583043b2023-07-17 17:05:00 -07003949 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003950
Eric Laurent81784c32012-11-19 14:55:58 -08003951 cpuStats.sample(myName);
3952
Andy Hung116bc262023-06-20 18:56:17 -07003953 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003954 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003955 bool isHapticSessionSpatialized = false;
Andy Hung8d31fd22023-06-26 19:20:57 -07003956 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003957
Andy Hung2dbffc22018-08-08 18:50:41 -07003958 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3959 //
Andy Hungc5007f82023-08-29 14:26:09 -07003960 // Note: we access outDeviceTypes() outside of mutex().
jiabinc52b1ff2019-10-31 17:20:42 -07003961 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003962 // Here, we try for the AF lock, but do not block on it as the latency
3963 // is more informational.
Andy Hung954b9712023-08-28 18:36:53 -07003964 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungb6692eb2023-07-13 16:52:46 -07003965 std::vector<SoftwarePatch> swPatches;
Andy Hung920f6572022-10-06 12:09:49 -07003966 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003967 status_t status = INVALID_OPERATION;
3968 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung583043b2023-07-17 17:05:00 -07003969 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungb6692eb2023-07-13 16:52:46 -07003970 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07003971 && swPatches.size() > 0) {
3972 status = swPatches[0].getLatencyMs_l(&latencyMs);
3973 downstreamPatchHandle = swPatches[0].getPatchHandle();
3974 }
3975 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003976 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003977 lastDownstreamPatchHandle = downstreamPatchHandle;
3978 }
3979 if (status == OK) {
3980 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003981 // latency of 5 seconds).
3982 const double minLatency = 0., maxLatency = 5000.;
3983 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003984 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003985 } else {
3986 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung920f6572022-10-06 12:09:49 -07003987 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07003988 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003989 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003990 }
Andy Hung583043b2023-07-17 17:05:00 -07003991 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07003992 }
3993 } else {
3994 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3995 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003996 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003997 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3998 }
3999 }
4000
Eric Laurentb3f315a2021-07-13 15:09:05 +02004001 if (mCheckOutputStageEffects.exchange(false)) {
4002 checkOutputStageEffects();
4003 }
4004
Vlad Popa7e81cea2023-01-19 16:34:16 +01004005 MetadataUpdate metadataUpdate;
Andy Hungc5007f82023-08-29 14:26:09 -07004006 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004007
Andy Hungc5007f82023-08-29 14:26:09 -07004008 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004009
Eric Laurent021cf962014-05-13 10:18:14 -07004010 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004011 if (mCheckOutputStageEffects.load()) {
4012 continue;
4013 }
Eric Laurent10351942014-05-08 18:49:52 -07004014
Andy Hungc5007f82023-08-29 14:26:09 -07004015 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004016 if (logString != NULL) {
4017 mNBLogWriter->logTimestamp();
4018 mNBLogWriter->log(logString);
4019 logString = NULL;
4020 }
4021
Dean Wheatley12473e92021-03-18 23:00:55 +11004022 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004023
Eric Laurent81784c32012-11-19 14:55:58 -08004024 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004025 if (mSignalPending) {
4026 // A signal was raised while we were unlocked
4027 mSignalPending = false;
4028 } else if (waitingAsyncCallback_l()) {
4029 if (exitPending()) {
4030 break;
4031 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004032 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004033 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004034 releaseWakeLock_l();
4035 released = true;
4036 }
Andy Hung10cbff12017-02-21 17:30:14 -08004037
4038 const int64_t waitNs = computeWaitTimeNs_l();
4039 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hungc5007f82023-08-29 14:26:09 -07004040 std::cv_status cvstatus =
4041 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4042 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004043 mSignalPending = true; // if timeout recheck everything
4044 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004045 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004046 if (released) {
4047 acquireWakeLock_l();
4048 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004049 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4050 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004051
4052 continue;
4053 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004054 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004055 isSuspended()) {
4056 // put audio hardware into standby after short delay
4057 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004058
4059 threadLoop_standby();
4060
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004061 // This is where we go into standby
4062 if (!mStandby) {
4063 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004064 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004065 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004066 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004067 }
Andy Hungd0979812019-02-21 15:51:44 -08004068 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004069 }
4070
Eric Tan39ec8d62018-07-24 09:49:29 -07004071 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004072 // we're about to wait, flush the binder command buffer
4073 IPCThreadState::self()->flushCommands();
4074
4075 clearOutputTracks();
4076
4077 if (exitPending()) {
4078 break;
4079 }
4080
4081 releaseWakeLock_l();
4082 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004083 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -07004084 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004085 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004086 acquireWakeLock_l();
4087
4088 mMixerStatus = MIXER_IDLE;
4089 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4090 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004091 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004092 checkSilentMode_l();
4093
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004094 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4095 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004096 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004097 sleepTimeShift = 0;
4098 }
4099
4100 continue;
4101 }
4102 }
Eric Laurent81784c32012-11-19 14:55:58 -08004103 // mMixerStatusIgnoringFastTracks is also updated internally
4104 mMixerStatus = prepareTracks_l(&tracksToRemove);
4105
Andy Hungdae27702016-10-31 14:01:16 -07004106 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004107
Vlad Popa7e81cea2023-01-19 16:34:16 +01004108 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004109
Eric Laurent81784c32012-11-19 14:55:58 -08004110 // prevent any changes in effect chain list and in each effect chain
4111 // during mixing and effect process as the audio buffers could be deleted
4112 // or modified if an effect is created or deleted
4113 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004114
4115 // Determine which session to pick up haptic data.
4116 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004117 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004118 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004119 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004120 for (const auto& track : mActiveTracks) {
Andy Hung116bc262023-06-20 18:56:17 -07004121 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004122 if (effectChain != nullptr
4123 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004124 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004125 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004126 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004127 break;
4128 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004129 if (activeHapticSessionId == AUDIO_SESSION_NONE
4130 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004131 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004132 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004133 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004134 }
4135 }
4136 }
4137
Andy Hungc1646382019-04-30 16:12:10 -07004138 // Acquire a local copy of active tracks with lock (release w/o lock).
4139 //
4140 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4141 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4142 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4143 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent68a40a82022-05-03 18:15:04 +02004144
4145 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004146
Jiabin Huangfb476842022-12-06 03:18:10 +00004147 for (const auto &track : mActiveTracks ) {
jiabin7434e812023-06-27 18:22:35 +00004148 track->updateTeePatches_l();
Jiabin Huangfb476842022-12-06 03:18:10 +00004149 }
4150
Eric Laurent19952e12023-04-20 10:08:29 +02004151 // signal actual start of output stream when the render position reported by the kernel
4152 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004153 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4154 && (mKernelPositionOnStandby
4155 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004156 mHalStarted = true;
Andy Hungc5007f82023-08-29 14:26:09 -07004157 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004158 }
Andy Hungc5007f82023-08-29 14:26:09 -07004159 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004160
Eric Laurentbfb1b832013-01-07 09:53:42 -08004161 if (mBytesRemaining == 0) {
4162 mCurrentWriteLength = 0;
4163 if (mMixerStatus == MIXER_TRACKS_READY) {
4164 // threadLoop_mix() sets mCurrentWriteLength
4165 threadLoop_mix();
4166 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4167 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004168 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004169 // must be written to HAL
4170 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004171 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004172 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004173
4174 // Tally underrun frames as we are inserting 0s here.
4175 for (const auto& track : activeTracks) {
Andy Hung8d31fd22023-06-26 19:20:57 -07004176 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004177 && !track->isStopped()
4178 && !track->isPaused()
4179 && !track->isTerminated()) {
4180 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4181 __func__, track->id(), track->getTrackStateAsString(),
4182 mNormalFrameCount);
Andy Hung8d31fd22023-06-26 19:20:57 -07004183 track->audioTrackServerProxy()->tallyUnderrunFrames(
4184 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004185 }
4186 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004187 }
4188 }
Andy Hung98ef9782014-03-04 14:46:50 -08004189 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004190 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004191 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004192 // or mSinkBuffer (if there are no effects and there is no data already copied to
4193 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004194 //
4195 // This is done pre-effects computation; if effects change to
4196 // support higher precision, this needs to move.
4197 //
4198 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004199 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004200 uint32_t mixerChannelCount = mEffectBufferValid ?
4201 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004202 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004203 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4204 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4205
David Li88ee0902022-06-22 10:01:21 +08004206 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4207 // do these processes after effects are applied.
4208 if (!mEffectBufferValid) {
4209 // mono blend occurs for mixer threads only (not direct or offloaded)
4210 // and is handled here if we're going directly to the sink.
4211 if (requireMonoBlend()) {
4212 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4213 mNormalFrameCount, true /*limit*/);
4214 }
Andy Hung2ddee192015-12-18 17:34:44 -08004215
David Li88ee0902022-06-22 10:01:21 +08004216 if (!hasFastMixer()) {
4217 // Balance must take effect after mono conversion.
4218 // We do it here if there is no FastMixer.
4219 // mBalance detects zero balance within the class for speed
4220 // (not needed here).
4221 mBalance.setBalance(mMasterBalance.load());
4222 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4223 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004224 }
4225
Andy Hung98ef9782014-03-04 14:46:50 -08004226 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004227 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004228
4229 // If we're going directly to the sink and there are haptic channels,
4230 // we should adjust channels as the sample data is partially interleaved
4231 // in this case.
4232 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4233 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4234 mChannelCount + mHapticChannelCount,
4235 audio_bytes_per_sample(format),
4236 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4237 }
Andy Hung98ef9782014-03-04 14:46:50 -08004238 }
4239
Eric Laurentbfb1b832013-01-07 09:53:42 -08004240 mBytesRemaining = mCurrentWriteLength;
4241 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004242 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4243 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4244 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4245 mBytesWritten += mBytesRemaining;
4246 mFramesWritten += framesRemaining;
4247 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004248 mBytesRemaining = 0;
4249 }
Eric Laurent81784c32012-11-19 14:55:58 -08004250
Eric Laurentbfb1b832013-01-07 09:53:42 -08004251 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004252 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004253 for (size_t i = 0; i < effectChains.size(); i ++) {
4254 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004255 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004256 if (activeHapticSessionId != AUDIO_SESSION_NONE
4257 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004258 // Haptic data is active in this case, copy it directly from
4259 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004260 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4261 audio_channel_count_from_out_mask(mMixerChannelMask) :
4262 mChannelCount;
4263 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4264 hapticSessionChannelCount = mChannelCount;
4265 }
4266
jiabin47affe52019-04-04 18:02:07 -07004267 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004268 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004269 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004270 memcpy_by_audio_format(
4271 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004272 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004273 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004274 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004275 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004276 }
Eric Laurent81784c32012-11-19 14:55:58 -08004277 }
4278 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004279 // Process effect chains for offloaded thread even if no audio
4280 // was read from audio track: process only updates effect state
4281 // and thus does have to be synchronized with audio writes but may have
4282 // to be called while waiting for async write callback
4283 if (mType == OFFLOAD) {
4284 for (size_t i = 0; i < effectChains.size(); i ++) {
4285 effectChains[i]->process_l();
4286 }
4287 }
Eric Laurent81784c32012-11-19 14:55:58 -08004288
Andy Hung98ef9782014-03-04 14:46:50 -08004289 // Only if the Effects buffer is enabled and there is data in the
4290 // Effects buffer (buffer valid), we need to
4291 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004292 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004293 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004294 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004295 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004296 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004297 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004298 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004299 }
4300
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004301 if (!hasFastMixer()) {
4302 // Balance must take effect after mono conversion.
4303 // We do it here if there is no FastMixer.
4304 // mBalance detects zero balance within the class for speed (not needed here).
4305 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004306 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004307 }
4308
Eric Laurentb62d0362021-10-26 17:40:18 +02004309 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4310 // mPostSpatializerBuffer if the haptics track is spatialized.
4311 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4312 // For other thread types, the haptics channels are already in mEffectBuffer.
4313 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4314 const size_t srcBufferSize = mNormalFrameCount *
4315 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4316 mEffectBufferFormat);
4317 const size_t dstBufferSize = mNormalFrameCount
4318 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4319
4320 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4321 mEffectBufferFormat,
4322 (uint8_t*)mEffectBuffer + srcBufferSize,
4323 mEffectBufferFormat,
4324 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004325 }
Atneya Nairba9a1072022-09-19 17:51:37 -07004326 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4327 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4328 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4329 // Clamp PCM float values more than this distance from 0 to insulate
4330 // a HAL which doesn't handle NaN correctly.
4331 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4332 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4333 static_cast<const float*>(effectBuffer),
4334 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4335 } else {
4336 memcpy_by_audio_format(mSinkBuffer, mFormat,
4337 effectBuffer, mEffectBufferFormat, framesToCopy);
4338 }
jiabin245cdd92018-12-07 17:55:15 -08004339 // The sample data is partially interleaved when haptic channels exist,
4340 // we need to adjust channels here.
4341 if (mHapticChannelCount > 0) {
4342 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4343 mChannelCount + mHapticChannelCount,
4344 audio_bytes_per_sample(mFormat),
4345 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4346 }
Andy Hung98ef9782014-03-04 14:46:50 -08004347 }
4348
Eric Laurent81784c32012-11-19 14:55:58 -08004349 // enable changes in effect chain
4350 unlockEffectChains(effectChains);
4351
Vlad Popafce10862023-02-03 10:37:07 +01004352 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung583043b2023-07-17 17:05:00 -07004353 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004354 metadataUpdate.playbackMetadataUpdate);
4355 }
4356
Eric Laurentbfb1b832013-01-07 09:53:42 -08004357 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004358 // mSleepTimeUs == 0 means we must write to audio hardware
4359 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004360 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004361 // writePeriodNs is updated >= 0 when ret > 0.
4362 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004363 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004364 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004365 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004366 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004367 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004368 if (ret < 0) {
4369 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004370 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004371 mBytesWritten += ret;
4372 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004373 const int64_t frames = ret / mFrameSize;
4374 mFramesWritten += frames;
4375
4376 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4377 // process information relating to write time.
4378 if (audio_has_proportional_frames(mFormat)) {
4379 // we are in a continuous mixing cycle
4380 if (mMixerStatus == MIXER_TRACKS_READY &&
4381 loopCount == lastLoopCountWritten + 1) {
4382
4383 const double jitterMs =
4384 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4385 {frames, writePeriodNs},
4386 {0, 0} /* lastTimestamp */, mSampleRate);
4387 const double processMs =
4388 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4389
Andy Hung972bec12023-08-31 16:13:39 -07004390 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004391 mIoJitterMs.add(jitterMs);
4392 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004393
4394 if (mPipeSink.get() != nullptr) {
4395 // Using the Monopipe availableToWrite, we estimate the current
4396 // buffer size.
4397 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4398 const ssize_t
4399 availableToWrite = mPipeSink->availableToWrite();
4400 const size_t pipeFrames = monoPipe->maxFrames();
4401 const size_t
4402 remainingFrames = pipeFrames - max(availableToWrite, 0);
4403 mMonopipePipeDepthStats.add(remainingFrames);
4404 }
Andy Hung446f4df2019-02-21 12:26:41 -08004405 }
4406
4407 // write blocked detection
4408 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004409 if ((mType == MIXER || mType == SPATIALIZER)
4410 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004411 mNumDelayedWrites++;
4412 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4413 ATRACE_NAME("underrun");
4414 ALOGW("write blocked for %lld msecs, "
4415 "%d delayed writes, thread %d",
4416 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4417 mNumDelayedWrites, mId);
4418 lastWarning = lastIoEndNs;
4419 }
4420 }
4421 }
4422 // update timing info.
4423 mLastIoBeginNs = lastIoBeginNs;
4424 mLastIoEndNs = lastIoEndNs;
4425 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004426 }
4427 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4428 (mMixerStatus == MIXER_DRAIN_ALL)) {
4429 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004430 }
Andy Hungd3639922022-04-28 18:00:49 -07004431 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004432
4433 if (mThreadThrottle
4434 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004435 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004436 // Limit MixerThread data processing to no more than twice the
4437 // expected processing rate.
4438 //
4439 // This helps prevent underruns with NuPlayer and other applications
4440 // which may set up buffers that are close to the minimum size, or use
4441 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4442 //
4443 // The throttle smooths out sudden large data drains from the device,
4444 // e.g. when it comes out of standby, which often causes problems with
4445 // (1) mixer threads without a fast mixer (which has its own warm-up)
4446 // (2) minimum buffer sized tracks (even if the track is full,
4447 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004448 //
4449 // Total time spent in last processing cycle equals time spent in
4450 // 1. threadLoop_write, as well as time spent in
4451 // 2. threadLoop_mix (significant for heavy mixing, especially
4452 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004453
Andy Hung446f4df2019-02-21 12:26:41 -08004454 // it's OK if deltaMs is an overestimate.
4455
4456 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004457
Ivan Lozanoea04d392017-11-07 14:37:07 -08004458 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004459 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004460 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004461
Andy Hung08fb1742015-05-31 23:22:10 -07004462 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004463 // notify of throttle start on verbose log
4464 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4465 "mixer(%p) throttle begin:"
4466 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004467 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004468 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004469 // Throttle must be attributed to the previous mixer loop's write time
4470 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004471 // This also ensures proper timing statistics.
4472 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004473 } else {
4474 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4475 if (diff > 0) {
4476 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004477 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004478 ALOGD_IF(!isSingleDeviceType(
4479 outDeviceTypes(), audio_is_a2dp_out_device) &&
4480 !isSingleDeviceType(
4481 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004482 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004483 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4484 }
Andy Hung08fb1742015-05-31 23:22:10 -07004485 }
4486 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004487 }
Eric Laurent81784c32012-11-19 14:55:58 -08004488
Eric Laurentbfb1b832013-01-07 09:53:42 -08004489 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004490 ATRACE_BEGIN("sleep");
Andy Hungc5007f82023-08-29 14:26:09 -07004491 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004492 // suspended requires accurate metering of sleep time.
4493 if (isSuspended()) {
4494 // advance by expected sleepTime
4495 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4496 const nsecs_t nowNs = systemTime();
4497
4498 // compute expected next time vs current time.
4499 // (negative deltas are treated as delays).
4500 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4501 if (deltaNs < -kMaxNextBufferDelayNs) {
4502 // Delays longer than the max allowed trigger a reset.
4503 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4504 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4505 timeLoopNextNs = nowNs + deltaNs;
4506 } else if (deltaNs < 0) {
4507 // Delays within the max delay allowed: zero the delta/sleepTime
4508 // to help the system catch up in the next iteration(s)
4509 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4510 deltaNs = 0;
4511 }
4512 // update sleep time (which is >= 0)
4513 mSleepTimeUs = deltaNs / 1000;
4514 }
Eric Laurente93cc032016-05-05 10:15:10 -07004515 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hungc5007f82023-08-29 14:26:09 -07004516 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004517 }
Glenn Kastene7754022014-10-31 12:11:26 -07004518 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004519 }
Eric Laurent81784c32012-11-19 14:55:58 -08004520 }
4521
4522 // Finally let go of removed track(s), without the lock held
4523 // since we can't guarantee the destructors won't acquire that
4524 // same lock. This will also mutate and push a new fast mixer state.
4525 threadLoop_removeTracks(tracksToRemove);
4526 tracksToRemove.clear();
4527
4528 // FIXME I don't understand the need for this here;
4529 // it was in the original code but maybe the
4530 // assignment in saveOutputTracks() makes this unnecessary?
4531 clearOutputTracks();
4532
4533 // Effect chains will be actually deleted here if they were removed from
4534 // mEffectChains list during mixing or effects processing
4535 effectChains.clear();
4536
4537 // FIXME Note that the above .clear() is no longer necessary since effectChains
4538 // is now local to this block, but will keep it for now (at least until merge done).
4539 }
4540
Eric Laurentbfb1b832013-01-07 09:53:42 -08004541 threadLoop_exit();
4542
Eric Laurentcf817a22014-08-04 20:36:31 -07004543 if (!mStandby) {
4544 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004545 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004546 }
4547
4548 releaseWakeLock();
4549
4550 ALOGV("Thread %p type %d exiting", this, mType);
4551 return false;
4552}
4553
Andy Hungee58e4a2023-07-07 13:47:37 -07004554void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004555{
Dean Wheatley12473e92021-03-18 23:00:55 +11004556 if (mStandby) {
4557 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4558 return;
4559 } else if (mHwPaused) {
4560 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4561 return;
4562 }
4563
4564 // Gather the framesReleased counters for all active tracks,
4565 // and associate with the sink frames written out. We need
4566 // this to convert the sink timestamp to the track timestamp.
4567 bool kernelLocationUpdate = false;
4568 ExtendedTimestamp timestamp; // use private copy to fetch
4569
4570 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4571 // HAL may be draining some small duration buffered data for fade out.
4572 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4573 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4574 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4575 mSampleRate);
4576
4577 if (isTimestampCorrectionEnabled()) {
4578 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4579 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4580 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4581 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4582 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4583 = correctedTimestamp.mFrames;
4584 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4585 = correctedTimestamp.mTimeNs;
4586 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4587 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4588 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4589
4590 // Note: Downstream latency only added if timestamp correction enabled.
4591 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4592 const int64_t newPosition =
4593 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4594 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4595 // prevent retrograde
4596 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4597 newPosition,
4598 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4599 - mSuspendedFrames));
4600 }
4601 }
4602
4603 // We always fetch the timestamp here because often the downstream
4604 // sink will block while writing.
4605
4606 // We keep track of the last valid kernel position in case we are in underrun
4607 // and the normal mixer period is the same as the fast mixer period, or there
4608 // is some error from the HAL.
4609 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4610 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4611 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4612 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4613 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4614
4615 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4616 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4617 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4618 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4619 }
4620
4621 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4622 kernelLocationUpdate = true;
4623 } else {
4624 ALOGVV("getTimestamp error - no valid kernel position");
4625 }
4626
4627 // copy over kernel info
4628 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4629 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4630 + mSuspendedFrames; // add frames discarded when suspended
4631 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4632 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4633 } else {
4634 mTimestampVerifier.error();
4635 }
4636
4637 // mFramesWritten for non-offloaded tracks are contiguous
4638 // even after standby() is called. This is useful for the track frame
4639 // to sink frame mapping.
4640 bool serverLocationUpdate = false;
4641 if (mFramesWritten != mLastFramesWritten) {
4642 serverLocationUpdate = true;
4643 mLastFramesWritten = mFramesWritten;
4644 }
4645 // Only update timestamps if there is a meaningful change.
4646 // Either the kernel timestamp must be valid or we have written something.
4647 if (kernelLocationUpdate || serverLocationUpdate) {
4648 if (serverLocationUpdate) {
4649 // use the time before we called the HAL write - it is a bit more accurate
4650 // to when the server last read data than the current time here.
4651 //
4652 // If we haven't written anything, mLastIoBeginNs will be -1
4653 // and we use systemTime().
4654 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4655 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4656 ? systemTime() : mLastIoBeginNs;
4657 }
4658
Andy Hung8d31fd22023-06-26 19:20:57 -07004659 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004660 if (!t->isFastTrack()) {
4661 t->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07004662 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004663 mFramesWritten,
4664 mSampleRate,
4665 mTimestamp);
4666 }
4667 }
4668 }
4669
4670 if (audio_has_proportional_frames(mFormat)) {
4671 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4672 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4673 mLatencyMs.add(latencyMs);
4674 }
4675 }
4676#if 0
4677 // logFormat example
4678 if (z % 100 == 0) {
4679 timespec ts;
4680 clock_gettime(CLOCK_MONOTONIC, &ts);
4681 LOGT("This is an integer %d, this is a float %f, this is my "
4682 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4683 LOGT("A deceptive null-terminated string %\0");
4684 }
4685 ++z;
4686#endif
4687}
4688
Andy Hungc5007f82023-08-29 14:26:09 -07004689// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07004690void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hungc5007f82023-08-29 14:26:09 -07004691NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004692{
Andy Hungfe726a62018-09-27 15:17:25 -07004693 for (const auto& track : tracksToRemove) {
4694 mActiveTracks.remove(track);
4695 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hung116bc262023-06-20 18:56:17 -07004696 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004697 if (chain != 0) {
4698 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4699 __func__, track->id(), chain.get(), track->sessionId());
4700 chain->decActiveTrackCnt();
4701 }
4702 // If an external client track, inform APM we're no longer active, and remove if needed.
4703 // We do this under lock so that the state is consistent if the Track is destroyed.
4704 if (track->isExternalTrack()) {
4705 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004706 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004707 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004708 }
4709 }
Andy Hungfe726a62018-09-27 15:17:25 -07004710 if (track->isTerminated()) {
4711 // remove from our tracks vector
4712 removeTrack_l(track);
4713 }
jiabineb3bda02020-06-30 14:07:03 -07004714 if (mHapticChannelCount > 0 &&
4715 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4716 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hungc5007f82023-08-29 14:26:09 -07004717 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004718 // Unlock due to VibratorService will lock for this call and will
4719 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung7fb97e12023-07-20 21:23:42 -07004720 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hungc5007f82023-08-29 14:26:09 -07004721 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004722
4723 // When the track is stop, set the haptic intensity as MUTE
4724 // for the HapticGenerator effect.
4725 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004726 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004727 }
jiabin245cdd92018-12-07 17:55:15 -08004728 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004729 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004730}
Eric Laurent81784c32012-11-19 14:55:58 -08004731
Andy Hungee58e4a2023-07-07 13:47:37 -07004732status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004733{
4734 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004735 ExtendedTimestamp ets;
4736 status_t status = mNormalSink->getTimestamp(ets);
4737 if (status == NO_ERROR) {
4738 status = ets.getBestTimestamp(&timestamp);
4739 }
4740 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004741 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004742 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004743 collectTimestamps_l();
4744 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4745 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004746 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004747 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4748 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4749 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4750 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4751 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004752 }
4753 return INVALID_OPERATION;
4754}
Eric Laurent1c333e22014-05-20 10:48:17 -07004755
Eric Laurenteab90452019-06-24 15:17:46 -07004756// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4757// still applied by the mixer.
4758// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4759// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4760// if more than one track are active
Andy Hungee58e4a2023-07-07 13:47:37 -07004761status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004762{
4763 status_t result = NO_ERROR;
4764 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4765 if (*volume != mLeftVolFloat) {
4766 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004767 // HAL can return INVALID_OPERATION if operation is not supported.
4768 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004769 "Error when setting output stream volume: %d", result);
4770 if (result == NO_ERROR) {
4771 mLeftVolFloat = *volume;
4772 }
4773 }
4774 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4775 // remove stream volume contribution from software volume.
4776 if (mLeftVolFloat == *volume) {
4777 *volume = 1.0f;
4778 }
4779 }
4780 return result;
4781}
4782
Andy Hungee58e4a2023-07-07 13:47:37 -07004783status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004784 audio_patch_handle_t *handle)
4785{
Andy Hungf60abce2016-08-26 11:37:54 -07004786 status_t status;
4787 if (property_get_bool("af.patch_park", false /* default_value */)) {
4788 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4789 // or if HAL does not properly lock against access.
4790 AutoPark<FastMixer> park(mFastMixer);
4791 status = PlaybackThread::createAudioPatch_l(patch, handle);
4792 } else {
4793 status = PlaybackThread::createAudioPatch_l(patch, handle);
4794 }
Eric Laurentb0463942022-12-20 16:31:10 +01004795
4796 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004797 return status;
4798}
4799
Andy Hungee58e4a2023-07-07 13:47:37 -07004800status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004801 audio_patch_handle_t *handle)
4802{
4803 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004804
4805 // store new device and send to effects
4806 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004807 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004808 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004809 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4810 && !mOutput->audioHwDev->supportsAudioPatches(),
4811 "Enumerated device type(%#x) must not be used "
4812 "as it does not support audio patches",
4813 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004814 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -07004815 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4816 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004817 }
4818
François Gaffie0c280aa2018-07-25 10:02:15 +02004819 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004820#ifdef ADD_BATTERY_DATA
4821 // when changing the audio output device, call addBatteryData to notify
4822 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004823 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004824 uint32_t params = 0;
4825 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004826 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004827 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004828 }
4829
Eric Laurent054d9d32015-04-24 08:48:48 -07004830 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004831 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004832 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4833 }
4834
4835 if (params != 0) {
4836 addBatteryData(params);
4837 }
4838 }
4839#endif
4840
4841 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004842 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004843 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004844
jiabinc52b1ff2019-10-31 17:20:42 -07004845 // mPatch.num_sinks is not set when the thread is created so that
4846 // the first patch creation triggers an ioConfigChanged callback
4847 bool configChanged = (mPatch.num_sinks == 0) ||
4848 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004849 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004850 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004851 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004852
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004853 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004854 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4855 status = hwDevice->createAudioPatch(patch->num_sources,
4856 patch->sources,
4857 patch->num_sinks,
4858 patch->sinks,
4859 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004860 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004861 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004862 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004863 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004864 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004865
4866 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004867 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004868 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004869 // also dispatch to active AudioTracks for MediaMetrics
4870 for (const auto &track : mActiveTracks) {
4871 track->logEndInterval();
4872 track->logBeginInterval(patchSinksAsString);
4873 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004874
Eric Laurente8726fe2015-06-26 09:39:24 -07004875 if (configChanged) {
4876 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4877 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004878 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004879 mActiveTracks.setHasChanged();
4880
Eric Laurent1c333e22014-05-20 10:48:17 -07004881 return status;
4882}
4883
Andy Hungee58e4a2023-07-07 13:47:37 -07004884status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004885{
Andy Hungf60abce2016-08-26 11:37:54 -07004886 status_t status;
4887 if (property_get_bool("af.patch_park", false /* default_value */)) {
4888 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4889 // or if HAL does not properly lock against access.
4890 AutoPark<FastMixer> park(mFastMixer);
4891 status = PlaybackThread::releaseAudioPatch_l(handle);
4892 } else {
4893 status = PlaybackThread::releaseAudioPatch_l(handle);
4894 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004895 return status;
4896}
4897
Andy Hungee58e4a2023-07-07 13:47:37 -07004898status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004899{
4900 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004901
jiabinc52b1ff2019-10-31 17:20:42 -07004902 mPatch = audio_patch{};
4903 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004904
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004905 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004906 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4907 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004908 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004909 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004910 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004911 // Force meteadata update after a route change
4912 mActiveTracks.setHasChanged();
4913
Eric Laurent1c333e22014-05-20 10:48:17 -07004914 return status;
4915}
4916
Andy Hungee58e4a2023-07-07 13:47:37 -07004917void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004918{
Andy Hung972bec12023-08-31 16:13:39 -07004919 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004920 mTracks.add(track);
4921}
4922
Andy Hungee58e4a2023-07-07 13:47:37 -07004923void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004924{
Andy Hung972bec12023-08-31 16:13:39 -07004925 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004926 destroyTrack_l(track);
4927}
4928
Andy Hungee58e4a2023-07-07 13:47:37 -07004929void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004930{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004931 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004932 config->role = AUDIO_PORT_ROLE_SOURCE;
4933 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4934 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004935 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4936 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4937 config->flags.output = mOutput->flags;
4938 }
Eric Laurent83b88082014-06-20 18:31:16 -07004939}
4940
Eric Laurent81784c32012-11-19 14:55:58 -08004941// ----------------------------------------------------------------------------
4942
Andy Hungee58e4a2023-07-07 13:47:37 -07004943/* static */
4944sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung583043b2023-07-17 17:05:00 -07004945 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hungee58e4a2023-07-07 13:47:37 -07004946 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07004947 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07004948}
4949
Andy Hung583043b2023-07-17 17:05:00 -07004950MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004951 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07004952 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004953 // mAudioMixer below
4954 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004955 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004956 mFastMixerFutex(0),
4957 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004958 // mOutputSink below
4959 // mPipeSink below
4960 // mNormalSink below
4961{
Andy Hung583043b2023-07-17 17:05:00 -07004962 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004963 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004964 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004965 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004966 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4967 mNormalFrameCount);
4968 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4969
Andy Hungfbfc3952015-01-15 13:33:51 -08004970 if (type == DUPLICATING) {
4971 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4972 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4973 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4974 return;
4975 }
Eric Laurent81784c32012-11-19 14:55:58 -08004976 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004977 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004978 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004979 const NBAIO_Format offers[1] = {Format_from_SR_C(
4980 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004981#if !LOG_NDEBUG
4982 ssize_t index =
4983#else
4984 (void)
4985#endif
4986 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004987 ALOG_ASSERT(index == 0);
4988
4989 // initialize fast mixer depending on configuration
4990 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00004991 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08004992 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02004993 } else {
4994 switch (kUseFastMixer) {
4995 case FastMixer_Never:
4996 initFastMixer = false;
4997 break;
4998 case FastMixer_Always:
4999 initFastMixer = true;
5000 break;
5001 case FastMixer_Static:
5002 case FastMixer_Dynamic:
5003 initFastMixer = mFrameCount < mNormalFrameCount;
5004 break;
5005 }
5006 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5007 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5008 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005009 }
5010 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005011 audio_format_t fastMixerFormat;
5012 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5013 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5014 } else {
5015 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5016 }
5017 if (mFormat != fastMixerFormat) {
5018 // change our Sink format to accept our intermediate precision
5019 mFormat = fastMixerFormat;
5020 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005021 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005022 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5023 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5024 }
Eric Laurent81784c32012-11-19 14:55:58 -08005025
5026 // create a MonoPipe to connect our submix to FastMixer
5027 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005028
Andy Hung1258c1a2014-05-23 21:22:17 -07005029 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005030 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005031 format.mFormat = fastMixerFormat;
5032 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5033
Eric Laurent81784c32012-11-19 14:55:58 -08005034 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5035 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5036 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5037 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung920f6572022-10-06 12:09:49 -07005038 const NBAIO_Format offersFast[1] = {format};
5039 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005040#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005041 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005042#else
5043 (void)
5044#endif
Andy Hung920f6572022-10-06 12:09:49 -07005045 monoPipe->negotiate(offersFast, std::size(offersFast),
5046 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005047 ALOG_ASSERT(index == 0);
5048 monoPipe->setAvgFrames((mScreenState & 1) ?
5049 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5050 mPipeSink = monoPipe;
5051
Eric Laurent81784c32012-11-19 14:55:58 -08005052 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005053 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005054 FastMixerStateQueue *sq = mFastMixer->sq();
5055#ifdef STATE_QUEUE_DUMP
5056 sq->setObserverDump(&mStateQueueObserverDump);
5057 sq->setMutatorDump(&mStateQueueMutatorDump);
5058#endif
5059 FastMixerState *state = sq->begin();
5060 FastTrack *fastTrack = &state->mFastTracks[0];
5061 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5062 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5063 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005064 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5065 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5066 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005067 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005068 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005069 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005070 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005071 fastTrack->mGeneration++;
5072 state->mFastTracksGen++;
5073 state->mTrackMask = 1;
5074 // fast mixer will use the HAL output sink
5075 state->mOutputSink = mOutputSink.get();
5076 state->mOutputSinkGen++;
5077 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005078 // specify sink channel mask when haptic channel mask present as it can not
5079 // be calculated directly from channel count
5080 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005081 ? AUDIO_CHANNEL_NONE
5082 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005083 state->mCommand = FastMixerState::COLD_IDLE;
5084 // already done in constructor initialization list
5085 //mFastMixerFutex = 0;
5086 state->mColdFutexAddr = &mFastMixerFutex;
5087 state->mColdGen++;
5088 state->mDumpState = &mFastMixerDumpState;
Andy Hung583043b2023-07-17 17:05:00 -07005089 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005090 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005091 sq->end();
5092 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5093
Eric Tan0513b5d2018-09-17 10:32:48 -07005094 NBLog::thread_info_t info;
5095 info.id = mId;
5096 info.type = NBLog::FASTMIXER;
5097 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5098
Eric Laurent81784c32012-11-19 14:55:58 -08005099 // start the fast mixer
5100 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5101 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005102 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005103 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005104
5105#ifdef AUDIO_WATCHDOG
5106 // create and start the watchdog
5107 mAudioWatchdog = new AudioWatchdog();
5108 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5109 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5110 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005111 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005112#endif
Andy Hung8946a282018-04-19 20:04:56 -07005113 } else {
5114#ifdef TEE_SINK
5115 // Only use the MixerThread tee if there is no FastMixer.
5116 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5117 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5118#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005119 }
5120
5121 switch (kUseFastMixer) {
5122 case FastMixer_Never:
5123 case FastMixer_Dynamic:
5124 mNormalSink = mOutputSink;
5125 break;
5126 case FastMixer_Always:
5127 mNormalSink = mPipeSink;
5128 break;
5129 case FastMixer_Static:
5130 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5131 break;
5132 }
5133}
5134
Andy Hungee58e4a2023-07-07 13:47:37 -07005135MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005136{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005137 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005138 FastMixerStateQueue *sq = mFastMixer->sq();
5139 FastMixerState *state = sq->begin();
5140 if (state->mCommand == FastMixerState::COLD_IDLE) {
5141 int32_t old = android_atomic_inc(&mFastMixerFutex);
5142 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005143 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005144 }
5145 }
5146 state->mCommand = FastMixerState::EXIT;
5147 sq->end();
5148 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5149 mFastMixer->join();
5150 // Though the fast mixer thread has exited, it's state queue is still valid.
5151 // We'll use that extract the final state which contains one remaining fast track
5152 // corresponding to our sub-mix.
5153 state = sq->begin();
5154 ALOG_ASSERT(state->mTrackMask == 1);
5155 FastTrack *fastTrack = &state->mFastTracks[0];
5156 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5157 delete fastTrack->mBufferProvider;
5158 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005159 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005160#ifdef AUDIO_WATCHDOG
5161 if (mAudioWatchdog != 0) {
5162 mAudioWatchdog->requestExit();
5163 mAudioWatchdog->requestExitAndWait();
5164 mAudioWatchdog.clear();
5165 }
5166#endif
5167 }
Andy Hung583043b2023-07-17 17:05:00 -07005168 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005169 delete mAudioMixer;
5170}
5171
Andy Hungee58e4a2023-07-07 13:47:37 -07005172void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005173 PlaybackThread::onFirstRef();
5174
Andy Hung972bec12023-08-31 16:13:39 -07005175 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005176 if (mOutput != nullptr && mOutput->stream != nullptr) {
5177 status_t status = mOutput->stream->setLatencyModeCallback(this);
5178 if (status != INVALID_OPERATION) {
5179 updateHalSupportedLatencyModes_l();
5180 }
5181 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5182 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5183 mBluetoothLatencyModesEnabled.store(
5184 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5185 }
5186}
Eric Laurent81784c32012-11-19 14:55:58 -08005187
Andy Hungee58e4a2023-07-07 13:47:37 -07005188uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005189{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005190 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005191 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5192 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5193 }
5194 return latency;
5195}
5196
Andy Hungee58e4a2023-07-07 13:47:37 -07005197ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005198{
5199 // FIXME we should only do one push per cycle; confirm this is true
5200 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005201 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005202 FastMixerStateQueue *sq = mFastMixer->sq();
5203 FastMixerState *state = sq->begin();
5204 if (state->mCommand != FastMixerState::MIX_WRITE &&
5205 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5206 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005207
5208 // FIXME workaround for first HAL write being CPU bound on some devices
5209 ATRACE_BEGIN("write");
5210 mOutput->write((char *)mSinkBuffer, 0);
5211 ATRACE_END();
5212
Eric Laurent81784c32012-11-19 14:55:58 -08005213 int32_t old = android_atomic_inc(&mFastMixerFutex);
5214 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005215 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005216 }
5217#ifdef AUDIO_WATCHDOG
5218 if (mAudioWatchdog != 0) {
5219 mAudioWatchdog->resume();
5220 }
5221#endif
5222 }
5223 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005224#ifdef FAST_THREAD_STATISTICS
Andy Hung583043b2023-07-17 17:05:00 -07005225 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005226 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005227#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005228 sq->end();
5229 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5230 if (kUseFastMixer == FastMixer_Dynamic) {
5231 mNormalSink = mPipeSink;
5232 }
5233 } else {
5234 sq->end(false /*didModify*/);
5235 }
5236 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005237 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005238}
5239
Andy Hungee58e4a2023-07-07 13:47:37 -07005240void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005241{
5242 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005243 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005244 FastMixerStateQueue *sq = mFastMixer->sq();
5245 FastMixerState *state = sq->begin();
5246 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005247 // Report any frames trapped in the Monopipe
5248 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5249 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5250 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5251 "monoPipeWritten:%lld monoPipeLeft:%lld",
5252 (long long)mFramesWritten, (long long)mSuspendedFrames,
5253 (long long)mPipeSink->framesWritten(), pipeFrames);
5254 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5255
Eric Laurent81784c32012-11-19 14:55:58 -08005256 state->mCommand = FastMixerState::COLD_IDLE;
5257 state->mColdFutexAddr = &mFastMixerFutex;
5258 state->mColdGen++;
5259 mFastMixerFutex = 0;
5260 sq->end();
5261 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5262 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5263 if (kUseFastMixer == FastMixer_Dynamic) {
5264 mNormalSink = mOutputSink;
5265 }
5266#ifdef AUDIO_WATCHDOG
5267 if (mAudioWatchdog != 0) {
5268 mAudioWatchdog->pause();
5269 }
5270#endif
5271 } else {
5272 sq->end(false /*didModify*/);
5273 }
5274 }
5275 PlaybackThread::threadLoop_standby();
5276}
5277
Andy Hungee58e4a2023-07-07 13:47:37 -07005278bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279{
5280 return false;
5281}
5282
Andy Hungee58e4a2023-07-07 13:47:37 -07005283bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005284{
5285 return !mStandby;
5286}
5287
Andy Hungee58e4a2023-07-07 13:47:37 -07005288bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005289{
Andy Hung972bec12023-08-31 16:13:39 -07005290 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005291 return waitingAsyncCallback_l();
5292}
5293
Eric Laurent81784c32012-11-19 14:55:58 -08005294// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hungee58e4a2023-07-07 13:47:37 -07005295void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005296{
5297 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005298 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005299 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005300 // discard any pending drain or write ack by incrementing sequence
5301 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5302 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005303 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005304 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5305 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005306 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005307 mHwPaused = false;
Eric Laurent68a40a82022-05-03 18:15:04 +02005308 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005309}
5310
Andy Hungee58e4a2023-07-07 13:47:37 -07005311void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005312{
5313 ALOGV("signal playback thread");
5314 broadcast_l();
5315}
5316
Andy Hungee58e4a2023-07-07 13:47:37 -07005317void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005318{
5319 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5320 invalidateTracks((audio_stream_type_t)i);
5321 }
5322}
5323
Andy Hungee58e4a2023-07-07 13:47:37 -07005324void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005325{
Eric Laurent81784c32012-11-19 14:55:58 -08005326 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005327 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005328 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005329 // increase sleep time progressively when application underrun condition clears.
5330 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5331 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5332 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005333 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005334 sleepTimeShift--;
5335 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005336 mSleepTimeUs = 0;
5337 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005338 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005339
Eric Laurent81784c32012-11-19 14:55:58 -08005340}
5341
Andy Hungee58e4a2023-07-07 13:47:37 -07005342void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005343{
5344 // If no tracks are ready, sleep once for the duration of an output
5345 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005346 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005347 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005348 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5349 // Using the Monopipe availableToWrite, we estimate the
5350 // sleep time to retry for more data (before we underrun).
5351 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5352 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5353 const size_t pipeFrames = monoPipe->maxFrames();
5354 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5355 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5356 const size_t framesDelay = std::min(
5357 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5358 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5359 pipeFrames, framesLeft, framesDelay);
5360 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5361 } else {
5362 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5363 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5364 mSleepTimeUs = kMinThreadSleepTimeUs;
5365 }
5366 // reduce sleep time in case of consecutive application underruns to avoid
5367 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5368 // duration we would end up writing less data than needed by the audio HAL if
5369 // the condition persists.
5370 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5371 sleepTimeShift++;
5372 }
Eric Laurent81784c32012-11-19 14:55:58 -08005373 }
5374 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005375 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005376 }
5377 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005378 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5379 // before effects processing or output.
5380 if (mMixerBufferValid) {
5381 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005382 if (mType == SPATIALIZER) {
5383 memset(mSinkBuffer, 0, mSinkBufferSize);
5384 }
Andy Hung98ef9782014-03-04 14:46:50 -08005385 } else {
5386 memset(mSinkBuffer, 0, mSinkBufferSize);
5387 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005388 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005389 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5390 "anticipated start");
5391 }
5392 // TODO add standby time extension fct of effect tail
5393}
5394
Andy Hungc5007f82023-08-29 14:26:09 -07005395// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07005396PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07005397 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005398{
Andy Hungc0691382018-09-12 18:01:57 -07005399 // clean up deleted track ids in AudioMixer before allocating new tracks
5400 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5401 // for each trackId, destroy it in the AudioMixer
5402 if (mAudioMixer->exists(trackId)) {
5403 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005404 }
5405 });
Andy Hungc0691382018-09-12 18:01:57 -07005406 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005407
5408 mixer_state mixerStatus = MIXER_IDLE;
5409 // find out which tracks need to be processed
5410 size_t count = mActiveTracks.size();
5411 size_t mixedTracks = 0;
5412 size_t tracksWithEffect = 0;
5413 // counts only _active_ fast tracks
5414 size_t fastTracks = 0;
5415 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5416
5417 float masterVolume = mMasterVolume;
5418 bool masterMute = mMasterMute;
5419
5420 if (masterMute) {
5421 masterVolume = 0;
5422 }
5423 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hung116bc262023-06-20 18:56:17 -07005424 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005425 if (chain != 0) {
5426 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5427 chain->setVolume_l(&v, &v);
5428 masterVolume = (float)((v + (1 << 23)) >> 24);
5429 chain.clear();
5430 }
5431
5432 // prepare a new state to push
5433 FastMixerStateQueue *sq = NULL;
5434 FastMixerState *state = NULL;
5435 bool didModify = false;
5436 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005437 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005438 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005439 sq = mFastMixer->sq();
5440 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005441 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005442 }
5443
Andy Hung69aed5f2014-02-25 17:24:40 -08005444 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005445 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005446
Andy Hungbd3b2b02018-05-21 10:53:11 -07005447 // DeferredOperations handles statistics after setting mixerStatus.
5448 class DeferredOperations {
5449 public:
Andy Hungea840382020-05-05 21:50:17 -07005450 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5451 : mMixerStatus(mixerStatus)
5452 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005453
5454 // when leaving scope, tally frames properly.
5455 ~DeferredOperations() {
5456 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5457 // because that is when the underrun occurs.
5458 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005459 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005460 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005461 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005462 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005463 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005464 }
5465 }
Andy Hungea840382020-05-05 21:50:17 -07005466 // send the max underrun frames for this mixer period
5467 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005468 }
5469
5470 // tallyUnderrunFrames() is called to update the track counters
5471 // with the number of underrun frames for a particular mixer period.
5472 // We defer tallying until we know the final mixer status.
Andy Hung8d31fd22023-06-26 19:20:57 -07005473 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005474 mUnderrunFrames.emplace_back(track, underrunFrames);
5475 }
5476
5477 private:
5478 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005479 ThreadMetrics * const mThreadMetrics;
Andy Hung8d31fd22023-06-26 19:20:57 -07005480 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005481 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005482 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005483
jiabin245cdd92018-12-07 17:55:15 -08005484 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005485 for (size_t i=0 ; i<count ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005486 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005487
5488 // this const just means the local variable doesn't change
Andy Hung8d31fd22023-06-26 19:20:57 -07005489 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005490
5491 // process fast tracks
5492 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005493 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5494 "%s(%d): FastTrack(%d) present without FastMixer",
5495 __func__, id(), track->id());
5496
jiabin245cdd92018-12-07 17:55:15 -08005497 if (track->getHapticPlaybackEnabled()) {
5498 noFastHapticTrack = false;
5499 }
Eric Laurent81784c32012-11-19 14:55:58 -08005500
5501 // It's theoretically possible (though unlikely) for a fast track to be created
5502 // and then removed within the same normal mix cycle. This is not a problem, as
5503 // the track never becomes active so it's fast mixer slot is never touched.
5504 // The converse, of removing an (active) track and then creating a new track
5505 // at the identical fast mixer slot within the same normal mix cycle,
5506 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung8d31fd22023-06-26 19:20:57 -07005507 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005508 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005509 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5510 FastTrack *fastTrack = &state->mFastTracks[j];
5511
5512 // Determine whether the track is currently in underrun condition,
5513 // and whether it had a recent underrun.
5514 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5515 FastTrackUnderruns underruns = ftDump->mUnderruns;
5516 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung8d31fd22023-06-26 19:20:57 -07005517 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005518 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung8d31fd22023-06-26 19:20:57 -07005519 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005520 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung8d31fd22023-06-26 19:20:57 -07005521 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005522 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung8d31fd22023-06-26 19:20:57 -07005523 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005524 // don't count underruns that occur while stopping or pausing
5525 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005526 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005527 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5528 recentUnderruns > 0) {
5529 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005530 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005531 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005532 // Immediately account for FastTrack underruns.
Andy Hung8d31fd22023-06-26 19:20:57 -07005533 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005534
5535 // This is similar to the state machine for normal tracks,
5536 // with a few modifications for fast tracks.
5537 bool isActive = true;
Andy Hung8d31fd22023-06-26 19:20:57 -07005538 switch (track->state()) {
5539 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005540 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005541 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005542 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005543 }
5544 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005545 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005546 // ramp down is not yet implemented
5547 track->setPaused();
5548 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005549 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005550 // ramp up is not yet implemented
Andy Hung8d31fd22023-06-26 19:20:57 -07005551 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005552 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005553 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005554 if (recentFull > 0 || recentPartial > 0) {
5555 // track has provided at least some frames recently: reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005556 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005557 }
5558 if (recentUnderruns == 0) {
5559 // no recent underruns: stay active
5560 break;
5561 }
5562 // there has recently been an underrun of some kind
5563 if (track->sharedBuffer() == 0) {
5564 // were any of the recent underruns "empty" (no frames available)?
5565 if (recentEmpty == 0) {
5566 // no, then ignore the partial underruns as they are allowed indefinitely
5567 break;
5568 }
5569 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung8d31fd22023-06-26 19:20:57 -07005570 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005571 break;
5572 }
5573 // indicate to client process that the track was disabled because of underrun;
5574 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005575 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005576 // remove from active list, but state remains ACTIVE [confusing but true]
5577 isActive = false;
5578 break;
5579 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005580 FALLTHROUGH_INTENDED;
Andy Hung8d31fd22023-06-26 19:20:57 -07005581 case IAfTrackBase::STOPPING_2:
5582 case IAfTrackBase::PAUSED:
5583 case IAfTrackBase::STOPPED:
5584 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005585 // Check for presentation complete if track is inactive
5586 // We have consumed all the buffers of this track.
5587 // This would be incomplete if we auto-paused on underrun
5588 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005589 uint32_t latency = 0;
5590 status_t result = mOutput->stream->getLatency(&latency);
5591 ALOGE_IF(result != OK,
5592 "Error when retrieving output stream latency: %d", result);
5593 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005594 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005595 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5596 // track stays in active list until presentation is complete
5597 break;
5598 }
5599 }
5600 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005601 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005602 }
5603 if (track->isStopped()) {
5604 // Can't reset directly, as fast mixer is still polling this track
5605 // track->reset();
5606 // So instead mark this track as needing to be reset after push with ack
5607 resetMask |= 1 << i;
5608 }
5609 isActive = false;
5610 break;
Andy Hung8d31fd22023-06-26 19:20:57 -07005611 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005612 default:
Andy Hung8d31fd22023-06-26 19:20:57 -07005613 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005614 }
5615
5616 if (isActive) {
5617 // was it previously inactive?
5618 if (!(state->mTrackMask & (1 << j))) {
Andy Hung8d31fd22023-06-26 19:20:57 -07005619 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5620 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005621 fastTrack->mBufferProvider = eabp;
5622 fastTrack->mVolumeProvider = vp;
Andy Hung8d31fd22023-06-26 19:20:57 -07005623 fastTrack->mChannelMask = track->channelMask();
5624 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005625 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005626 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005627 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005628 fastTrack->mGeneration++;
5629 state->mTrackMask |= 1 << j;
5630 didModify = true;
5631 // no acknowledgement required for newly active tracks
5632 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005633 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005634 float volume;
5635 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5636 volume = 0.f;
5637 } else {
5638 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5639 }
5640
5641 handleVoipVolume_l(&volume);
5642
Eric Laurent81784c32012-11-19 14:55:58 -08005643 // cache the combined master volume and stream type volume for fast mixer; this
5644 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005645 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005646 proxy->framesReleased()).first;
5647 volume *= vh;
Andy Hung8d31fd22023-06-26 19:20:57 -07005648 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005649 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005650 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5651 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
5652
Andy Hung583043b2023-07-17 17:05:00 -07005653 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005654 /*muteState=*/{masterVolume == 0.f,
5655 mStreamTypes[track->streamType()].volume == 0.f,
5656 mStreamTypes[track->streamType()].mute,
5657 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005658 vlf == 0.f && vrf == 0.f,
5659 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005660
5661 vlf *= volume;
5662 vrf *= volume;
Eric Laurenteab90452019-06-24 15:17:46 -07005663
jiabin76d94692022-12-15 21:51:21 +00005664 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005665 ++fastTracks;
5666 } else {
5667 // was it previously active?
5668 if (state->mTrackMask & (1 << j)) {
5669 fastTrack->mBufferProvider = NULL;
5670 fastTrack->mGeneration++;
5671 state->mTrackMask &= ~(1 << j);
5672 didModify = true;
5673 // If any fast tracks were removed, we must wait for acknowledgement
5674 // because we're about to decrement the last sp<> on those tracks.
5675 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5676 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005677 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5678 // AudioTrack may start (which may not be with a start() but with a write()
5679 // after underrun) and immediately paused or released. In that case the
5680 // FastTrack state hasn't had time to update.
5681 // TODO Remove the ALOGW when this theory is confirmed.
5682 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005683 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung8d31fd22023-06-26 19:20:57 -07005684 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005685 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005686 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005687 }
5688 tracksToRemove->add(track);
5689 // Avoids a misleading display in dumpsys
Andy Hung8d31fd22023-06-26 19:20:57 -07005690 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005691 }
jiabin245cdd92018-12-07 17:55:15 -08005692 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5693 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5694 didModify = true;
5695 }
Eric Laurent81784c32012-11-19 14:55:58 -08005696 continue;
5697 }
5698
5699 { // local variable scope to avoid goto warning
5700
5701 audio_track_cblk_t* cblk = track->cblk();
5702
5703 // The first time a track is added we wait
5704 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005705 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005706
5707 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005708 // use the trackId as the AudioMixer name.
5709 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005710 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005711 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005712 track->channelMask(),
5713 track->format(),
5714 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005715 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005716 ALOGW("%s(): AudioMixer cannot create track(%d)"
5717 " mask %#x, format %#x, sessionId %d",
5718 __func__, trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07005719 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005720 tracksToRemove->add(track);
5721 track->invalidate(); // consider it dead.
5722 continue;
5723 }
5724 }
5725
Eric Laurent81784c32012-11-19 14:55:58 -08005726 // make sure that we have enough frames to mix one full buffer.
5727 // enforce this condition only once to enable draining the buffer in case the client
5728 // app does not call stop() and relies on underrun to stop:
5729 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5730 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005731 size_t desiredFrames;
Andy Hung8d31fd22023-06-26 19:20:57 -07005732 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5733 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005734
5735 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005736 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005737 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5738 // add frames already consumed but not yet released by the resampler
5739 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005740 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005741
Eric Laurent81784c32012-11-19 14:55:58 -08005742 uint32_t minFrames = 1;
5743 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5744 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005745 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005746 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005747
5748 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005749 if (ATRACE_ENABLED()) {
5750 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005751 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005752 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005753 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005754 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005755 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005756 !track->isPaused() && !track->isTerminated())
5757 {
Andy Hungc0691382018-09-12 18:01:57 -07005758 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005759
5760 mixedTracks++;
5761
Andy Hung69aed5f2014-02-25 17:24:40 -08005762 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5763 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005764 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005765 if (track->mainBuffer() != mSinkBuffer &&
5766 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005767 if (mEffectBufferEnabled) {
5768 mEffectBufferValid = true; // Later can set directly.
5769 }
Eric Laurent81784c32012-11-19 14:55:58 -08005770 chain = getEffectChain_l(track->sessionId());
5771 // Delegate volume control to effect in track effect chain if needed
5772 if (chain != 0) {
5773 tracksWithEffect++;
5774 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005775 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005776 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005777 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005778 }
5779 }
5780
5781
5782 int param = AudioMixer::VOLUME;
Andy Hung8d31fd22023-06-26 19:20:57 -07005783 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005784 // no ramp for the first volume setting
Andy Hung8d31fd22023-06-26 19:20:57 -07005785 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5786 if (track->state() == IAfTrackBase::RESUMING) {
5787 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005788 // If a new track is paused immediately after start, do not ramp on resume.
5789 if (cblk->mServer != 0) {
5790 param = AudioMixer::RAMP_VOLUME;
5791 }
Eric Laurent81784c32012-11-19 14:55:58 -08005792 }
Andy Hungc0691382018-09-12 18:01:57 -07005793 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005794 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005795 // FIXME should not make a decision based on mServer
5796 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005797 // If the track is stopped before the first frame was mixed,
5798 // do not apply ramp
5799 param = AudioMixer::RAMP_VOLUME;
5800 }
5801
5802 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005803 uint32_t vl, vr; // in U8.24 integer format
5804 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005805 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005806 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005807 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung8d31fd22023-06-26 19:20:57 -07005808 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005809 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung8d31fd22023-06-26 19:20:57 -07005810 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005811
Eric Laurenteab90452019-06-24 15:17:46 -07005812 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5813 v = 0;
5814 }
5815
5816 handleVoipVolume_l(&v);
5817
5818 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005819 vl = vr = 0;
5820 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005821 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005822 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005823 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005824 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5825 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005826 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005827 if (vlf > GAIN_FLOAT_UNITY) {
5828 ALOGV("Track left volume out of range: %.3g", vlf);
5829 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005830 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005831 if (vrf > GAIN_FLOAT_UNITY) {
5832 ALOGV("Track right volume out of range: %.3g", vrf);
5833 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005834 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005835
Andy Hung583043b2023-07-17 17:05:00 -07005836 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005837 /*muteState=*/{masterVolume == 0.f,
5838 mStreamTypes[track->streamType()].volume == 0.f,
5839 mStreamTypes[track->streamType()].mute,
5840 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005841 vlf == 0.f && vrf == 0.f,
5842 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005843
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005844 // now apply the master volume and stream type volume and shaper volume
5845 vlf *= v * vh;
5846 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005847 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005848 // then derive vl and vr as U8.24 versions for the effect chain
5849 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5850 vl = (uint32_t) (scaleto8_24 * vlf);
5851 vr = (uint32_t) (scaleto8_24 * vrf);
5852 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005853 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005854 // send level comes from shared memory and so may be corrupt
5855 if (sendLevel > MAX_GAIN_INT) {
5856 ALOGV("Track send level out of range: %04X", sendLevel);
5857 sendLevel = MAX_GAIN_INT;
5858 }
Andy Hung6be49402014-05-30 10:42:03 -07005859 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5860 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005861 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005862
jiabin76d94692022-12-15 21:51:21 +00005863 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005864
Eric Laurent81784c32012-11-19 14:55:58 -08005865 // Delegate volume control to effect in track effect chain if needed
5866 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5867 // Do not ramp volume if volume is controlled by effect
5868 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005869 // Update remaining floating point volume levels
5870 vlf = (float)vl / (1 << 24);
5871 vrf = (float)vr / (1 << 24);
Andy Hung8d31fd22023-06-26 19:20:57 -07005872 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005873 } else {
5874 // force no volume ramp when volume controller was just disabled or removed
5875 // from effect chain to avoid volume spike
Andy Hung8d31fd22023-06-26 19:20:57 -07005876 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005877 param = AudioMixer::VOLUME;
5878 }
Andy Hung8d31fd22023-06-26 19:20:57 -07005879 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005880 }
5881
Eric Laurent81784c32012-11-19 14:55:58 -08005882 // XXX: these things DON'T need to be done each time
Andy Hung8d31fd22023-06-26 19:20:57 -07005883 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005884 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005885
Andy Hungc0691382018-09-12 18:01:57 -07005886 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5887 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5888 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005889 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005890 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005891 AudioMixer::TRACK,
5892 AudioMixer::FORMAT, (void *)track->format());
5893 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005894 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005895 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005896 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005897
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005898 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005899 mAudioMixer->setParameter(
5900 trackId,
5901 AudioMixer::TRACK,
5902 AudioMixer::MIXER_CHANNEL_MASK,
5903 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5904 } else {
5905 mAudioMixer->setParameter(
5906 trackId,
5907 AudioMixer::TRACK,
5908 AudioMixer::MIXER_CHANNEL_MASK,
5909 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5910 }
5911
Glenn Kastene3aa6592012-12-04 12:22:46 -08005912 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005913 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005914 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005915 if (reqSampleRate == 0) {
5916 reqSampleRate = mSampleRate;
5917 } else if (reqSampleRate > maxSampleRate) {
5918 reqSampleRate = maxSampleRate;
5919 }
Eric Laurent81784c32012-11-19 14:55:58 -08005920 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005921 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005922 AudioMixer::RESAMPLE,
5923 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005924 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005925
Andy Hung8edb8dc2015-03-26 19:13:55 -07005926 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005927 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005928 AudioMixer::TIMESTRETCH,
5929 AudioMixer::PLAYBACK_RATE,
Andy Hung920f6572022-10-06 12:09:49 -07005930 // cast away constness for this generic API.
5931 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005932
Andy Hung69aed5f2014-02-25 17:24:40 -08005933 /*
5934 * Select the appropriate output buffer for the track.
5935 *
Andy Hung98ef9782014-03-04 14:46:50 -08005936 * Tracks with effects go into their own effects chain buffer
5937 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005938 *
5939 * Other tracks can use mMixerBuffer for higher precision
5940 * channel accumulation. If this buffer is enabled
5941 * (mMixerBufferEnabled true), then selected tracks will accumulate
5942 * into it.
5943 *
5944 */
5945 if (mMixerBufferEnabled
5946 && (track->mainBuffer() == mSinkBuffer
5947 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005948 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005949 mAudioMixer->setParameter(
5950 trackId,
5951 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005952 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005953 mAudioMixer->setParameter(
5954 trackId,
5955 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005956 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005957 } else {
5958 mAudioMixer->setParameter(
5959 trackId,
5960 AudioMixer::TRACK,
5961 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5962 mAudioMixer->setParameter(
5963 trackId,
5964 AudioMixer::TRACK,
5965 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5966 // TODO: override track->mainBuffer()?
5967 mMixerBufferValid = true;
5968 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005969 } else {
5970 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005971 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005972 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07005973 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005974 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005975 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005976 AudioMixer::TRACK,
5977 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5978 }
Eric Laurent81784c32012-11-19 14:55:58 -08005979 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005980 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005981 AudioMixer::TRACK,
5982 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005983 mAudioMixer->setParameter(
5984 trackId,
5985 AudioMixer::TRACK,
5986 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005987 mAudioMixer->setParameter(
5988 trackId,
5989 AudioMixer::TRACK,
5990 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung8d31fd22023-06-26 19:20:57 -07005991 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005992 mAudioMixer->setParameter(
5993 trackId,
5994 AudioMixer::TRACK,
Andy Hung8d31fd22023-06-26 19:20:57 -07005995 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08005996
5997 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07005998 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005999
6000 // If one track is ready, set the mixer ready if:
6001 // - the mixer was not ready during previous round OR
6002 // - no other track is not ready
6003 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6004 mixerStatus != MIXER_TRACKS_ENABLED) {
6005 mixerStatus = MIXER_TRACKS_READY;
6006 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006007
6008 // Enable the next few lines to instrument a test for underrun log handling.
6009 // TODO: Remove when we have a better way of testing the underrun log.
6010#if 0
6011 static int i;
6012 if ((++i & 0xf) == 0) {
6013 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6014 }
6015#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006016 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006017 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006018 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006019 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6020 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006021 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006022 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006023 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006024
Eric Laurent81784c32012-11-19 14:55:58 -08006025 // clear effect chain input buffer if an active track underruns to avoid sending
6026 // previous audio buffer again to effects
6027 chain = getEffectChain_l(track->sessionId());
6028 if (chain != 0) {
6029 chain->clearInputBuffer();
6030 }
6031
Andy Hungc0691382018-09-12 18:01:57 -07006032 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006033 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6034 track->isStopped() || track->isPaused()) {
6035 // We have consumed all the buffers of this track.
6036 // Remove it from the list of active tracks.
6037 // TODO: use actual buffer filling status instead of latency when available from
6038 // audio HAL
6039 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006040 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006041 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6042 if (track->isStopped()) {
6043 track->reset();
6044 }
6045 tracksToRemove->add(track);
6046 }
6047 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006048 // No buffers for this track. Give it a few chances to
6049 // fill a buffer, then remove it from active list.
Andy Hung8d31fd22023-06-26 19:20:57 -07006050 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006051 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6052 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006053 tracksToRemove->add(track);
6054 // indicate to client process that the track was disabled because of underrun;
6055 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006056 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006057 // If one track is not ready, mark the mixer also not ready if:
6058 // - the mixer was ready during previous round OR
6059 // - no other track is ready
6060 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6061 mixerStatus != MIXER_TRACKS_READY) {
6062 mixerStatus = MIXER_TRACKS_ENABLED;
6063 }
6064 }
Andy Hungc0691382018-09-12 18:01:57 -07006065 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006066 }
6067
6068 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006069
6070 }
6071
jiabin245cdd92018-12-07 17:55:15 -08006072 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6073 // When there is no fast track playing haptic and FastMixer exists,
6074 // enabling the first FastTrack, which provides mixed data from normal
6075 // tracks, to play haptic data.
6076 FastTrack *fastTrack = &state->mFastTracks[0];
6077 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6078 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6079 didModify = true;
6080 }
6081 }
6082
Eric Laurent81784c32012-11-19 14:55:58 -08006083 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006084 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006085 if (didModify) {
6086 state->mFastTracksGen++;
6087 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6088 if (kUseFastMixer == FastMixer_Dynamic &&
6089 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6090 state->mCommand = FastMixerState::COLD_IDLE;
6091 state->mColdFutexAddr = &mFastMixerFutex;
6092 state->mColdGen++;
6093 mFastMixerFutex = 0;
6094 if (kUseFastMixer == FastMixer_Dynamic) {
6095 mNormalSink = mOutputSink;
6096 }
6097 // If we go into cold idle, need to wait for acknowledgement
6098 // so that fast mixer stops doing I/O.
6099 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6100 pauseAudioWatchdog = true;
6101 }
Eric Laurent81784c32012-11-19 14:55:58 -08006102 }
6103 if (sq != NULL) {
6104 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006105 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6106 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6107 // when bringing the output sink into standby.)
6108 //
6109 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6110 //
6111 // This occurs with BT suspend when we idle the FastMixer with
6112 // active tracks, which may be added or removed.
6113 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006114 }
6115#ifdef AUDIO_WATCHDOG
6116 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6117 mAudioWatchdog->pause();
6118 }
6119#endif
6120
6121 // Now perform the deferred reset on fast tracks that have stopped
6122 while (resetMask != 0) {
6123 size_t i = __builtin_ctz(resetMask);
6124 ALOG_ASSERT(i < count);
6125 resetMask &= ~(1 << i);
Andy Hung8d31fd22023-06-26 19:20:57 -07006126 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006127 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6128 track->reset();
6129 }
6130
Andy Hung80d03d22018-04-10 10:32:11 -07006131 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6132 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6133 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6134 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6135 // See also the implementation of destroyTrack_l().
6136 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006137 const int trackId = track->id();
6138 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6139 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006140 }
6141 }
6142
Eric Laurent81784c32012-11-19 14:55:58 -08006143 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006144 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006145
Eric Laurentb3f315a2021-07-13 15:09:05 +02006146 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6147 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006148 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006149 }
6150
6151 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006152 // as long as there are effects we should clear the effects buffer, to avoid
6153 // passing a non-clean buffer to the effect chain
6154 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006155 if (mType == SPATIALIZER) {
6156 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6157 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006158 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006159 // sink or mix buffer must be cleared if all tracks are connected to an
6160 // effect chain as in this case the mixer will not write to the sink or mix buffer
6161 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006162 // always clear sink buffer for spatializer output as the output of the spatializer
6163 // effect will be accumulated into it
6164 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6165 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006166 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006167 if (mMixerBufferValid) {
6168 memset(mMixerBuffer, 0, mMixerBufferSize);
6169 // TODO: In testing, mSinkBuffer below need not be cleared because
6170 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6171 // after mixing.
6172 //
6173 // To enforce this guarantee:
6174 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6175 // (mixedTracks == 0 && fastTracks > 0))
6176 // must imply MIXER_TRACKS_READY.
6177 // Later, we may clear buffers regardless, and skip much of this logic.
6178 }
Andy Hung98ef9782014-03-04 14:46:50 -08006179 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006180 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006181 }
6182
6183 // if any fast tracks, then status is ready
6184 mMixerStatusIgnoringFastTracks = mixerStatus;
6185 if (fastTracks > 0) {
6186 mixerStatus = MIXER_TRACKS_READY;
6187 }
6188 return mixerStatus;
6189}
6190
Andy Hungc5007f82023-08-29 14:26:09 -07006191// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006192uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006193{
6194 uint32_t trackCount = 0;
6195 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006196 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006197 trackCount++;
6198 }
6199 }
6200 return trackCount;
6201}
6202
Andy Hungee58e4a2023-07-07 13:47:37 -07006203bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006204{
Brian Lindahl65e90012022-07-27 18:01:07 +02006205 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6206 // could falsely detect that the frame position has stalled due to underrun because we haven't
6207 // given the Audio HAL enough time to update.
6208 const nsecs_t nowNs = systemTime();
6209 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6210 return mLatchedValue;
6211 }
6212 mPreviousNs = nowNs;
6213 mLatchedValue = false;
6214 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006215 uint64_t position = 0;
6216 struct timespec unused;
Brian Lindahl65e90012022-07-27 18:01:07 +02006217 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006218 if (ret == NO_ERROR) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006219 if (position != mPreviousPosition) {
6220 mPreviousPosition = position;
6221 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006222 }
6223 }
Brian Lindahl65e90012022-07-27 18:01:07 +02006224 return mLatchedValue;
6225}
6226
Andy Hungee58e4a2023-07-07 13:47:37 -07006227void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl65e90012022-07-27 18:01:07 +02006228{
6229 mLatchedValue = true;
6230 mPreviousPosition = 0;
6231 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006232}
6233
Andy Hungc5007f82023-08-29 14:26:09 -07006234// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006235bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006236 audio_channel_mask_t channelMask, audio_format_t format,
6237 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006238{
Andy Hung1bc088a2018-02-09 15:57:31 -08006239 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6240 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006241 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006242 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006243 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006244 ALOGW("%s: invalid format: %#x", __func__, format);
6245 return false;
6246 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006247 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006248 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6249 return false;
6250 }
6251 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006252}
6253
Andy Hungc5007f82023-08-29 14:26:09 -07006254// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006255bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006256 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006257{
Eric Laurent81784c32012-11-19 14:55:58 -08006258 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006259 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006260
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006261 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006262
Eric Laurent10351942014-05-08 18:49:52 -07006263 AudioParameter param = AudioParameter(keyValuePair);
6264 int value;
6265 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6266 reconfig = true;
6267 }
6268 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006269 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006270 status = BAD_VALUE;
6271 } else {
6272 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006273 reconfig = true;
6274 }
Eric Laurent10351942014-05-08 18:49:52 -07006275 }
6276 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung81994d62023-07-20 21:44:14 -07006277 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006278 status = BAD_VALUE;
6279 } else {
6280 // no need to save value, since it's constant
6281 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006282 }
Eric Laurent10351942014-05-08 18:49:52 -07006283 }
6284 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6285 // do not accept frame count changes if tracks are open as the track buffer
6286 // size depends on frame count and correct behavior would not be guaranteed
6287 // if frame count is changed after track creation
6288 if (!mTracks.isEmpty()) {
6289 status = INVALID_OPERATION;
6290 } else {
6291 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006292 }
Eric Laurent10351942014-05-08 18:49:52 -07006293 }
6294 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006295 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006296 }
Eric Laurent81784c32012-11-19 14:55:58 -08006297
Eric Laurent10351942014-05-08 18:49:52 -07006298 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006299 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006300 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungdda7aed2023-03-27 15:53:06 -07006301 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6302 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006303 mOutput->standby();
Andy Hungdda7aed2023-03-27 15:53:06 -07006304 mThreadMetrics.logEndInterval();
6305 mThreadSnapshot.onEnd();
6306 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006307 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006308 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006309 }
Eric Laurent10351942014-05-08 18:49:52 -07006310 if (status == NO_ERROR && reconfig) {
6311 readOutputParameters_l();
6312 delete mAudioMixer;
6313 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006314 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006315 const int trackId = track->id();
Andy Hung920f6572022-10-06 12:09:49 -07006316 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006317 trackId,
Andy Hung8d31fd22023-06-26 19:20:57 -07006318 track->channelMask(),
6319 track->format(),
6320 track->sessionId());
Andy Hung920f6572022-10-06 12:09:49 -07006321 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006322 "%s(): AudioMixer cannot create track(%d)"
6323 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006324 __func__,
Andy Hung8d31fd22023-06-26 19:20:57 -07006325 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006326 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006327 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006328 }
Eric Laurent81784c32012-11-19 14:55:58 -08006329 }
6330
Dean Wheatley68918102021-03-19 22:09:19 +11006331 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006332}
6333
6334
Andy Hungee58e4a2023-07-07 13:47:37 -07006335void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006336{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006337 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006338 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006339 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006340 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006341 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6342 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6343 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006344 if (hasFastMixer()) {
6345 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6346
6347 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6348 // while we are dumping it. It may be inconsistent, but it won't mutate!
6349 // This is a large object so we place it on the heap.
6350 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006351 const std::unique_ptr<FastMixerDumpState> copy =
6352 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006353 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006354
6355#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006356 // Similar for state queue
6357 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6358 observerCopy.dump(fd);
6359 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6360 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006361#endif
6362
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006363#ifdef AUDIO_WATCHDOG
6364 if (mAudioWatchdog != 0) {
6365 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6366 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6367 wdCopy.dump(fd);
6368 }
6369#endif
6370
6371 } else {
6372 dprintf(fd, " No FastMixer\n");
6373 }
Eric Laurent90cea102023-05-15 15:08:27 +02006374
6375 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6376 mBluetoothLatencyModesEnabled ? "" : "not ");
6377 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6378 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6379 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006380}
6381
Andy Hungee58e4a2023-07-07 13:47:37 -07006382uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006383{
6384 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6385}
6386
Andy Hungee58e4a2023-07-07 13:47:37 -07006387uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006388{
6389 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6390}
6391
Andy Hungee58e4a2023-07-07 13:47:37 -07006392void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006393{
6394 PlaybackThread::cacheParameters_l();
6395
6396 // FIXME: Relaxed timing because of a certain device that can't meet latency
6397 // Should be reduced to 2x after the vendor fixes the driver issue
6398 // increase threshold again due to low power audio mode. The way this warning
6399 // threshold is calculated and its usefulness should be reconsidered anyway.
6400 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6401}
6402
Andy Hungee58e4a2023-07-07 13:47:37 -07006403void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung583043b2023-07-17 17:05:00 -07006404 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006405}
6406
Andy Hungee58e4a2023-07-07 13:47:37 -07006407void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006408 // Only handle latency mode if:
6409 // - mBluetoothLatencyModesEnabled is true
6410 // - the HAL supports latency modes
6411 // - the selected device is Bluetooth LE or A2DP
6412 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6413 return;
6414 }
6415 if (mOutDeviceTypeAddrs.size() != 1
6416 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6417 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6418 return;
6419 }
6420
6421 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6422 if (mSupportedLatencyModes.size() == 1) {
6423 // If the HAL only support one latency mode currently, confirm the choice
6424 latencyMode = mSupportedLatencyModes[0];
6425 } else if (mSupportedLatencyModes.size() > 1) {
6426 // Request low latency if:
6427 // - At least one active track is either:
6428 // - a fast track with gaming usage or
6429 // - a track with acessibility usage
6430 for (const auto& track : mActiveTracks) {
6431 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6432 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6433 latencyMode = AUDIO_LATENCY_MODE_LOW;
6434 break;
6435 }
6436 }
6437 }
6438
6439 if (latencyMode != mSetLatencyMode) {
6440 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6441 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6442 __func__, mId, toString(latencyMode).c_str(), status);
6443 if (status == NO_ERROR) {
6444 mSetLatencyMode = latencyMode;
6445 }
6446 }
6447}
6448
Andy Hungee58e4a2023-07-07 13:47:37 -07006449void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006450
6451 if (mOutput == nullptr || mOutput->stream == nullptr) {
6452 return;
6453 }
6454 std::vector<audio_latency_mode_t> latencyModes;
6455 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6456 if (status != NO_ERROR) {
6457 latencyModes.clear();
6458 }
6459 if (latencyModes != mSupportedLatencyModes) {
6460 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6461 __func__, mId, status, toString(latencyModes).c_str());
6462 mSupportedLatencyModes.swap(latencyModes);
6463 sendHalLatencyModesChangedEvent_l();
6464 }
6465}
6466
Andy Hungee58e4a2023-07-07 13:47:37 -07006467status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006468 std::vector<audio_latency_mode_t>* modes) {
6469 if (modes == nullptr) {
6470 return BAD_VALUE;
6471 }
Andy Hung972bec12023-08-31 16:13:39 -07006472 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006473 *modes = mSupportedLatencyModes;
6474 return NO_ERROR;
6475}
6476
Andy Hungee58e4a2023-07-07 13:47:37 -07006477void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006478 std::vector<audio_latency_mode_t> modes) {
Andy Hung972bec12023-08-31 16:13:39 -07006479 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006480 if (modes != mSupportedLatencyModes) {
6481 ALOGD("%s: thread(%d) supported latency modes: %s",
6482 __func__, mId, toString(modes).c_str());
6483 mSupportedLatencyModes.swap(modes);
6484 sendHalLatencyModesChangedEvent_l();
6485 }
6486}
6487
Andy Hungee58e4a2023-07-07 13:47:37 -07006488status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006489 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6490 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6491 return INVALID_OPERATION;
6492 }
6493 mBluetoothLatencyModesEnabled.store(enabled);
6494 return NO_ERROR;
6495}
6496
Eric Laurent81784c32012-11-19 14:55:58 -08006497// ----------------------------------------------------------------------------
6498
Andy Hungee58e4a2023-07-07 13:47:37 -07006499/* static */
6500sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung583043b2023-07-17 17:05:00 -07006501 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07006502 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6503 const audio_offload_info_t& offloadInfo) {
6504 return sp<DirectOutputThread>::make(
Andy Hung583043b2023-07-17 17:05:00 -07006505 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07006506}
6507
Andy Hung583043b2023-07-17 17:05:00 -07006508DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07006509 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6510 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07006511 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fennb18c1a32022-10-05 13:42:36 -07006512 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006513{
Andy Hung583043b2023-07-17 17:05:00 -07006514 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006515}
6516
Andy Hungee58e4a2023-07-07 13:47:37 -07006517DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006518{
6519}
6520
Andy Hungee58e4a2023-07-07 13:47:37 -07006521void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006522{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006523 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006524 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6525 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6526}
6527
Andy Hungee58e4a2023-07-07 13:47:37 -07006528void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006529{
Andy Hung972bec12023-08-31 16:13:39 -07006530 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006531 if (mMasterBalance != balance) {
6532 mMasterBalance.store(balance);
6533 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6534 broadcast_l();
6535 }
6536}
6537
Andy Hungee58e4a2023-07-07 13:47:37 -07006538void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006539{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006540 float left, right;
6541
Andy Hung333ab962019-05-28 20:23:35 -07006542 // Ensure volumeshaper state always advances even when muted.
Andy Hung8d31fd22023-06-26 19:20:57 -07006543 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung398ffa22022-12-13 19:19:53 -08006544
Andy Hung398ffa22022-12-13 19:19:53 -08006545 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6546 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6547
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006548 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6549 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hung398ffa22022-12-13 19:19:53 -08006550
6551 const int64_t volumeShaperFrames =
6552 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6553 const auto [shaperVolume, shaperActive] =
6554 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006555 mVolumeShaperActive = shaperActive;
6556
Vlad Popae2f5aef2022-07-25 16:00:20 +02006557 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6558 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6559 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6560
6561 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6562
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006563 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006564 left = right = 0;
6565 } else {
6566 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006567 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006568
Glenn Kastenc56f3422014-03-21 17:53:17 -07006569 if (left > GAIN_FLOAT_UNITY) {
6570 left = GAIN_FLOAT_UNITY;
6571 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006572 if (right > GAIN_FLOAT_UNITY) {
6573 right = GAIN_FLOAT_UNITY;
6574 }
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006575 left *= v;
6576 right *= v;
Andy Hung583043b2023-07-17 17:05:00 -07006577 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng86cb3bc2023-01-16 17:17:38 +08006578 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6579 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6580 right *= mMasterBalanceRight;
6581 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006582 }
6583
Andy Hung583043b2023-07-17 17:05:00 -07006584 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006585 /*muteState=*/{mMasterMute,
6586 mStreamTypes[track->streamType()].volume == 0.f,
6587 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006588 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006589 clientVolumeMute,
6590 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006591
Eric Laurentbfb1b832013-01-07 09:53:42 -08006592 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006593 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006594 if (left != mLeftVolFloat || right != mRightVolFloat) {
6595 mLeftVolFloat = left;
6596 mRightVolFloat = right;
6597
Eric Laurentbfb1b832013-01-07 09:53:42 -08006598 // Delegate volume control to effect in track effect chain if needed
6599 // only one effect chain can be present on DirectOutputThread, so if
6600 // there is one, the track is connected to it
6601 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006602 // if effect chain exists, volume is handled by it.
6603 // Convert volumes from float to 8.24
6604 uint32_t vl = (uint32_t)(left * (1 << 24));
6605 uint32_t vr = (uint32_t)(right * (1 << 24));
6606 // Direct/Offload effect chains set output volume in setVolume_l().
6607 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6608 } else {
6609 // otherwise we directly set the volume.
6610 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006611 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006612 }
6613 }
6614}
6615
Andy Hungee58e4a2023-07-07 13:47:37 -07006616void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006617{
Andy Hung8d31fd22023-06-26 19:20:57 -07006618 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6619 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006620
Eric Laurent0f0631e2015-07-06 18:01:25 -07006621 if (previousTrack != 0 && latestTrack != 0) {
6622 if (mType == DIRECT) {
6623 if (previousTrack.get() != latestTrack.get()) {
6624 mFlushPending = true;
6625 }
6626 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006627 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6628 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006629 mFlushPending = true;
6630 }
6631 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006632 } else if (previousTrack == 0) {
6633 // there could be an old track added back during track transition for direct
6634 // output, so always issues flush to flush data of the previous track if it
6635 // was already destroyed with HAL paused, then flush can resume the playback
6636 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006637 }
6638 PlaybackThread::onAddNewTrack_l();
6639}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006640
Andy Hungee58e4a2023-07-07 13:47:37 -07006641PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07006642 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006643)
6644{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006645 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006646 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006647 bool doHwPause = false;
6648 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006649
6650 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07006651 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006652 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006653 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006654 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006655 continue;
6656 }
6657
Andy Hung8d31fd22023-06-26 19:20:57 -07006658 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006659#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006660 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006661#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006662 // Only consider last track started for volume and mixer state control.
6663 // In theory an older track could underrun and restart after the new one starts
6664 // but as we only care about the transition phase between two tracks on a
6665 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07006666 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006667 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006668
Kuowei Li23666472021-01-20 10:23:25 +08006669 if (track->isPausePending()) {
6670 track->pauseAck();
6671 // It is possible a track might have been flushed or stopped.
6672 // Other operations such as flush pending might occur on the next prepare.
6673 if (track->isPausing()) {
6674 track->setPaused();
6675 }
6676 // Always perform pause, as an immediate flush will change
6677 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006678 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006679 doHwPause = true;
6680 mHwPaused = true;
6681 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006682 } else if (track->isFlushPending()) {
6683 track->flushAck();
6684 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006685 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006686 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006687 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006688 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006689 if (last) {
6690 mLeftVolFloat = mRightVolFloat = -1.0;
6691 if (mHwPaused) {
6692 doHwResume = true;
6693 mHwPaused = false;
6694 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006695 }
6696 }
6697
Eric Laurent81784c32012-11-19 14:55:58 -08006698 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006699 // for all its buffers to be filled before processing it.
6700 // Allow draining the buffer in case the client
6701 // app does not call stop() and relies on underrun to stop:
Andy Hung8d31fd22023-06-26 19:20:57 -07006702 // hence the test on (track->retryCount() > 1).
6703 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006704 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6705 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006706 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006707
6708 // target retry count that we will use is based on the time we wait for retries.
6709 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6710 // the retry threshold is when we accept any size for PCM data. This is slightly
6711 // smaller than the retry count so we can push small bits of data without a glitch.
6712 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006713 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006714 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung8d31fd22023-06-26 19:20:57 -07006715 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006716 minFrames = mNormalFrameCount;
6717 } else {
6718 minFrames = 1;
6719 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006720
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006721 const size_t framesReady = track->framesReady();
6722 const int trackId = track->id();
6723 if (ATRACE_ENABLED()) {
6724 std::string traceName("nRdy");
6725 traceName += std::to_string(trackId);
6726 ATRACE_INT(traceName.c_str(), framesReady);
6727 }
6728 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006729 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006730 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006731 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006732
Andy Hung8d31fd22023-06-26 19:20:57 -07006733 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6734 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006735 if (last) {
6736 // make sure processVolume_l() will apply new volume even if 0
6737 mLeftVolFloat = mRightVolFloat = -1.0;
6738 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006739 if (!mHwSupportsPause) {
6740 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006741 }
6742 }
6743
6744 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006745 processVolume_l(track, last);
6746 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006747 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006748 if (previousTrack != 0) {
6749 if (track != previousTrack.get()) {
6750 // Flush any data still being written from last track
6751 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006752 // Invalidate previous track to force a seek when resuming.
6753 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006754 }
6755 }
6756 mPreviousTrack = track;
6757
Eric Laurentd595b7c2013-04-03 17:27:56 -07006758 // reset retry count
Andy Hung8d31fd22023-06-26 19:20:57 -07006759 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006760 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006761 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006762 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006763 doHwResume = true;
6764 mHwPaused = false;
6765 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006766 }
Eric Laurent81784c32012-11-19 14:55:58 -08006767 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006768 // clear effect chain input buffer if the last active track started underruns
6769 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006770 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006771 mEffectChains[0]->clearInputBuffer();
6772 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006773 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006774 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006775 if (last && mHwPaused) {
6776 doHwResume = true;
6777 mHwPaused = false;
6778 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006779 }
6780 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6781 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006782 // We have consumed all the buffers of this track.
6783 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006784 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006785 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006786 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006787 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006788 if (presComplete) {
6789 mOutput->presentationComplete();
6790 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006791 if (track->isStopping_2()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07006792 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006793 }
Eric Laurent81784c32012-11-19 14:55:58 -08006794 if (track->isStopped()) {
6795 track->reset();
6796 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006797 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006798 }
6799 } else {
6800 // No buffers for this track. Give it a few chances to
6801 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006802 // Only consider last track started for mixer state control
Brian Lindahl65e90012022-07-27 18:01:07 +02006803 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07006804 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07006805 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02006806 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07006807 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006808 } else {
6809 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6810 tracksToRemove->add(track);
6811 // indicate to client process that the track was disabled because of
6812 // underrun; it will then automatically call start() when data is available
6813 track->disable();
6814 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6815 // unlike mixerthread, HAL can be paused for direct output
6816 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6817 "minFrames = %u, mFormat = %#x",
6818 framesReady, minFrames, mFormat);
6819 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6820 doHwPause = true;
6821 mHwPaused = true;
6822 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006823 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006824 } else if (last) {
6825 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006826 }
6827 }
6828 }
6829 }
6830
Eric Laurentd1f69b02014-12-15 14:33:13 -08006831 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006832 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006833 for (size_t i = 0; i < mTracks.size(); i++) {
6834 if (mTracks[i]->isFlushPending()) {
6835 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006836 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006837 }
6838 }
6839 }
6840
6841 // make sure the pause/flush/resume sequence is executed in the right order.
6842 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6843 // before flush and then resume HW. This can happen in case of pause/flush/resume
6844 // if resume is received before pause is executed.
6845 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006846 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006847 status_t result = mOutput->stream->pause();
6848 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006849 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006850 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006851 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006852 flushHw_l();
6853 }
6854 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006855 status_t result = mOutput->stream->resume();
6856 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006857 }
Eric Laurent81784c32012-11-19 14:55:58 -08006858 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006859 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006860
6861 return mixerStatus;
6862}
6863
Andy Hungee58e4a2023-07-07 13:47:37 -07006864void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006865{
Eric Laurent81784c32012-11-19 14:55:58 -08006866 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006867 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006868 // output audio to hardware
6869 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006870 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006871 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006872 status_t status = mActiveTrack->getNextBuffer(&buffer);
6873 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006874 // no need to pad with 0 for compressed audio
6875 if (audio_has_proportional_frames(mFormat)) {
6876 memset(curBuf, 0, frameCount * mFrameSize);
6877 }
Eric Laurent81784c32012-11-19 14:55:58 -08006878 break;
6879 }
6880 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6881 frameCount -= buffer.frameCount;
6882 curBuf += buffer.frameCount * mFrameSize;
6883 mActiveTrack->releaseBuffer(&buffer);
6884 }
Andy Hung2098f272014-02-27 14:00:06 -08006885 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006886 mSleepTimeUs = 0;
6887 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006888 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006889}
6890
Andy Hungee58e4a2023-07-07 13:47:37 -07006891void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006892{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006893 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006894 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006895 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006896 return;
6897 }
Andy Hung85ba3332021-04-27 17:40:26 -07006898 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6899 mSleepTimeUs = mActiveSleepTimeUs;
6900 } else {
6901 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006902 }
Andy Hung85ba3332021-04-27 17:40:26 -07006903 // Note: In S or later, we do not write zeroes for
6904 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006905}
6906
Andy Hungee58e4a2023-07-07 13:47:37 -07006907void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006908{
6909 {
Andy Hung972bec12023-08-31 16:13:39 -07006910 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006911 for (size_t i = 0; i < mTracks.size(); i++) {
6912 if (mTracks[i]->isFlushPending()) {
6913 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006914 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006915 }
6916 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006917 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006918 flushHw_l();
6919 }
6920 }
6921 PlaybackThread::threadLoop_exit();
6922}
6923
6924// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07006925bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006926{
6927 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006928 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006929
6930 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6931 // after a timeout and we will enter standby then.
6932 if (mTracks.size() > 0) {
6933 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006934 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung8d31fd22023-06-26 19:20:57 -07006935 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006936 }
6937
Eric Laurent5cff4032015-05-26 13:49:58 -07006938 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006939}
6940
Andy Hungc5007f82023-08-29 14:26:09 -07006941// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07006942bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006943 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006944{
6945 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006946 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006947
Eric Laurent10351942014-05-08 18:49:52 -07006948 AudioParameter param = AudioParameter(keyValuePair);
6949 int value;
6950 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006951 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006952 }
Eric Laurent10351942014-05-08 18:49:52 -07006953 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6954 // do not accept frame count changes if tracks are open as the track buffer
6955 // size depends on frame count and correct behavior would not be garantied
6956 // if frame count is changed after track creation
6957 if (!mTracks.isEmpty()) {
6958 status = INVALID_OPERATION;
6959 } else {
6960 reconfig = true;
6961 }
6962 }
6963 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006964 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006965 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006966 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006967 if (!mStandby) {
6968 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07006969 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02006970 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07006971 }
Eric Laurent10351942014-05-08 18:49:52 -07006972 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006973 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006974 }
6975 if (status == NO_ERROR && reconfig) {
6976 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006977 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006978 }
6979 }
6980
Dean Wheatley68918102021-03-19 22:09:19 +11006981 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006982}
6983
Andy Hungee58e4a2023-07-07 13:47:37 -07006984uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006985{
6986 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006987 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006988 time = PlaybackThread::activeSleepTimeUs();
6989 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006990 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006991 }
6992 return time;
6993}
6994
Andy Hungee58e4a2023-07-07 13:47:37 -07006995uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006996{
6997 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006998 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006999 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7000 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007001 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007002 }
7003 return time;
7004}
7005
Andy Hungee58e4a2023-07-07 13:47:37 -07007006uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007007{
7008 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007009 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007010 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7011 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007012 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007013 }
7014 return time;
7015}
7016
Andy Hungee58e4a2023-07-07 13:47:37 -07007017void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007018{
7019 PlaybackThread::cacheParameters_l();
7020
7021 // use shorter standby delay as on normal output to release
7022 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007023 // no delay on outputs with HW A/V sync
7024 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007025 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007026 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007027 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007028 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007029 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007030 }
Eric Laurent81784c32012-11-19 14:55:58 -08007031}
7032
Andy Hungee58e4a2023-07-07 13:47:37 -07007033void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007034{
ziyangch8f194f12021-12-01 13:48:04 -08007035 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007036 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007037 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007038 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007039 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007040 mTimestamp.clear();
Andy Hung398ffa22022-12-13 19:19:53 -08007041 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007042}
7043
Andy Hungee58e4a2023-07-07 13:47:37 -07007044int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007045 // If a VolumeShaper is active, we must wake up periodically to update volume.
7046 const int64_t NS_PER_MS = 1000000;
7047 return mVolumeShaperActive ?
7048 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7049}
7050
Eric Laurent81784c32012-11-19 14:55:58 -08007051// ----------------------------------------------------------------------------
7052
Andy Hungee58e4a2023-07-07 13:47:37 -07007053AsyncCallbackThread::AsyncCallbackThread(
7054 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007055 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007056 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007057 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007058 mDrainSequence(0),
7059 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007060{
7061}
7062
Andy Hungee58e4a2023-07-07 13:47:37 -07007063void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007064{
7065 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7066}
7067
Andy Hungee58e4a2023-07-07 13:47:37 -07007068bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007069{
7070 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007071 uint32_t writeAckSequence;
7072 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007073 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007074
7075 {
Andy Hungc5007f82023-08-29 14:26:09 -07007076 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007077 while (!((mWriteAckSequence & 1) ||
7078 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007079 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007080 exitPending())) {
Andy Hungc5007f82023-08-29 14:26:09 -07007081 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007082 }
7083
Eric Laurentbfb1b832013-01-07 09:53:42 -08007084 if (exitPending()) {
7085 break;
7086 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007087 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7088 mWriteAckSequence, mDrainSequence);
7089 writeAckSequence = mWriteAckSequence;
7090 mWriteAckSequence &= ~1;
7091 drainSequence = mDrainSequence;
7092 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007093 asyncError = mAsyncError;
7094 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007095 }
7096 {
Andy Hungee58e4a2023-07-07 13:47:37 -07007097 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007098 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007099 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007100 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007101 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007102 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007103 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007104 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007105 if (asyncError) {
7106 playbackThread->onAsyncError();
7107 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007108 }
7109 }
7110 }
7111 return false;
7112}
7113
Andy Hungee58e4a2023-07-07 13:47:37 -07007114void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007115{
7116 ALOGV("AsyncCallbackThread::exit");
Andy Hung972bec12023-08-31 16:13:39 -07007117 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007118 requestExit();
Andy Hungc5007f82023-08-29 14:26:09 -07007119 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007120}
7121
Andy Hungee58e4a2023-07-07 13:47:37 -07007122void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007123{
Andy Hung972bec12023-08-31 16:13:39 -07007124 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007125 // bit 0 is cleared
7126 mWriteAckSequence = sequence << 1;
7127}
7128
Andy Hungee58e4a2023-07-07 13:47:37 -07007129void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007130{
Andy Hung972bec12023-08-31 16:13:39 -07007131 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007132 // ignore unexpected callbacks
7133 if (mWriteAckSequence & 2) {
7134 mWriteAckSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007135 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007136 }
7137}
7138
Andy Hungee58e4a2023-07-07 13:47:37 -07007139void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007140{
Andy Hung972bec12023-08-31 16:13:39 -07007141 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007142 // bit 0 is cleared
7143 mDrainSequence = sequence << 1;
7144}
7145
Andy Hungee58e4a2023-07-07 13:47:37 -07007146void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007147{
Andy Hung972bec12023-08-31 16:13:39 -07007148 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007149 // ignore unexpected callbacks
7150 if (mDrainSequence & 2) {
7151 mDrainSequence |= 1;
Andy Hungc5007f82023-08-29 14:26:09 -07007152 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007153 }
7154}
7155
Andy Hungee58e4a2023-07-07 13:47:37 -07007156void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007157{
Andy Hung972bec12023-08-31 16:13:39 -07007158 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007159 mAsyncError = true;
Andy Hungc5007f82023-08-29 14:26:09 -07007160 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007161}
7162
Eric Laurentbfb1b832013-01-07 09:53:42 -08007163
7164// ----------------------------------------------------------------------------
Andy Hungee58e4a2023-07-07 13:47:37 -07007165
7166/* static */
7167sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung583043b2023-07-17 17:05:00 -07007168 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007169 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7170 const audio_offload_info_t& offloadInfo) {
Andy Hung583043b2023-07-17 17:05:00 -07007171 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hungee58e4a2023-07-07 13:47:37 -07007172}
7173
Andy Hung583043b2023-07-17 17:05:00 -07007174OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fennb18c1a32022-10-05 13:42:36 -07007175 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7176 const audio_offload_info_t& offloadInfo)
Andy Hung583043b2023-07-17 17:05:00 -07007177 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007178 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007179{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007180 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007181 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007182 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007183}
7184
Andy Hungee58e4a2023-07-07 13:47:37 -07007185void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007186{
7187 if (mFlushPending || mHwPaused) {
7188 // If a flush is pending or track was paused, just discard buffered data
7189 flushHw_l();
7190 } else {
7191 mMixerStatus = MIXER_DRAIN_ALL;
7192 threadLoop_drain();
7193 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007194 if (mUseAsyncWrite) {
7195 ALOG_ASSERT(mCallbackThread != 0);
7196 mCallbackThread->exit();
7197 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007198 PlaybackThread::threadLoop_exit();
7199}
7200
Andy Hungee58e4a2023-07-07 13:47:37 -07007201PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -07007202 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007203)
7204{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007205 size_t count = mActiveTracks.size();
7206
7207 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007208 bool doHwPause = false;
7209 bool doHwResume = false;
7210
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007211 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007212
Eric Laurentbfb1b832013-01-07 09:53:42 -08007213 // find out which tracks need to be processed
Andy Hung8d31fd22023-06-26 19:20:57 -07007214 for (const sp<IAfTrack>& t : mActiveTracks) {
7215 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007216#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007217 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007218#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007219 // Only consider last track started for volume and mixer state control.
7220 // In theory an older track could underrun and restart after the new one starts
7221 // but as we only care about the transition phase between two tracks on a
7222 // direct output, it is not a problem to ignore the underrun case.
Andy Hung8d31fd22023-06-26 19:20:57 -07007223 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007224 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007225
Haynes Mathew George7844f672014-01-15 12:32:55 -08007226 if (track->isInvalid()) {
7227 ALOGW("An invalidated track shouldn't be in active list");
7228 tracksToRemove->add(track);
7229 continue;
7230 }
7231
Andy Hung8d31fd22023-06-26 19:20:57 -07007232 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007233 ALOGW("An idle track shouldn't be in active list");
7234 continue;
7235 }
7236
Kuowei Li23666472021-01-20 10:23:25 +08007237 if (track->isPausePending()) {
7238 track->pauseAck();
7239 // It is possible a track might have been flushed or stopped.
7240 // Other operations such as flush pending might occur on the next prepare.
7241 if (track->isPausing()) {
7242 track->setPaused();
7243 }
7244 // Always perform pause if last, as an immediate flush will change
7245 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007246 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007247 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007248 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007249 mHwPaused = true;
7250 }
7251 // If we were part way through writing the mixbuffer to
7252 // the HAL we must save this until we resume
7253 // BUG - this will be wrong if a different track is made active,
7254 // in that case we want to discard the pending data in the
7255 // mixbuffer and tell the client to present it again when the
7256 // track is resumed
7257 mPausedWriteLength = mCurrentWriteLength;
7258 mPausedBytesRemaining = mBytesRemaining;
7259 mBytesRemaining = 0; // stop writing
7260 }
7261 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007262 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007263 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007264 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007265 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007266 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007267 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007268 track->flushAck();
7269 if (last) {
7270 mFlushPending = true;
7271 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007272 } else if (track->isResumePending()){
7273 track->resumeAck();
7274 if (last) {
7275 if (mPausedBytesRemaining) {
7276 // Need to continue write that was interrupted
7277 mCurrentWriteLength = mPausedWriteLength;
7278 mBytesRemaining = mPausedBytesRemaining;
7279 mPausedBytesRemaining = 0;
7280 }
7281 if (mHwPaused) {
7282 doHwResume = true;
7283 mHwPaused = false;
7284 // threadLoop_mix() will handle the case that we need to
7285 // resume an interrupted write
7286 }
7287 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007288 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007289
Eric Laurent3df841a2016-07-15 15:15:40 -07007290 mLeftVolFloat = mRightVolFloat = -1.0;
7291
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007292 // Do not handle new data in this iteration even if track->framesReady()
7293 mixerStatus = MIXER_TRACKS_ENABLED;
7294 }
7295 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007296 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007297 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung8d31fd22023-06-26 19:20:57 -07007298 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7299 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007300 if (last) {
7301 // make sure processVolume_l() will apply new volume even if 0
7302 mLeftVolFloat = mRightVolFloat = -1.0;
7303 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007304 }
7305
7306 if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007307 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007308 if (previousTrack != 0) {
7309 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007310 // Flush any data still being written from last track
7311 mBytesRemaining = 0;
7312 if (mPausedBytesRemaining) {
7313 // Last track was paused so we also need to flush saved
7314 // mixbuffer state and invalidate track so that it will
7315 // re-submit that unwritten data when it is next resumed
7316 mPausedBytesRemaining = 0;
7317 // Invalidate is a bit drastic - would be more efficient
7318 // to have a flag to tell client that some of the
7319 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007320 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007321 }
7322 // flush data already sent to the DSP if changing audio session as audio
7323 // comes from a different source. Also invalidate previous track to force a
7324 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007325 if (previousTrack->sessionId() != track->sessionId()) {
7326 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007327 }
7328 }
7329 }
7330 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007331 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007332 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007333 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007334 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07007335 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007336 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007337 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007338 mixerStatus = MIXER_TRACKS_READY;
7339 }
7340 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007341 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007342 if (track->isStopping_1()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007343 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007344 // Hardware buffer can hold a large amount of audio so we must
7345 // wait for all current track's data to drain before we say
7346 // that the track is stopped.
7347 if (mBytesRemaining == 0) {
7348 // Only start draining when all data in mixbuffer
7349 // has been written
7350 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung8d31fd22023-06-26 19:20:57 -07007351 track->setState(IAfTrackBase::STOPPING_2);
7352 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007353 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7354 if (last && !mStandby) {
7355 // do not modify drain sequence if we are already draining. This happens
7356 // when resuming from pause after drain.
7357 if ((mDrainSequence & 1) == 0) {
7358 mSleepTimeUs = 0;
7359 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7360 mixerStatus = MIXER_DRAIN_TRACK;
7361 mDrainSequence += 2;
7362 }
7363 if (mHwPaused) {
7364 // It is possible to move from PAUSED to STOPPING_1 without
7365 // a resume so we must ensure hardware is running
7366 doHwResume = true;
7367 mHwPaused = false;
7368 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007369 }
7370 }
Eric Laurente93cc032016-05-05 10:15:10 -07007371 } else if (last) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007372 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007373 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007374 }
7375 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007376 // Drain has completed or we are in standby, signal presentation complete
7377 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung8d31fd22023-06-26 19:20:57 -07007378 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007379 mOutput->presentationComplete();
7380 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007381 track->reset();
7382 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007383 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007384 if (!mUseAsyncWrite) {
7385 // If we don't get explicit drain notification we must
7386 // register discontinuity regardless of whether this is
7387 // the previous (!last) or the upcoming (last) track
7388 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007389 mTimestampVerifier.discontinuity(
7390 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007391 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007392 }
7393 } else {
7394 // No buffers for this track. Give it a few chances to
7395 // fill a buffer, then remove it from active list.
Brian Lindahl65e90012022-07-27 18:01:07 +02007396 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fennb18c1a32022-10-05 13:42:36 -07007397 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung8d31fd22023-06-26 19:20:57 -07007398 && --(track->retryCount()) <= 0) {
Brian Lindahl65e90012022-07-27 18:01:07 +02007399 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung8d31fd22023-06-26 19:20:57 -07007400 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007401 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007402 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7403 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007404 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007405 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007406 // it will then automatically call start() when data is available
7407 track->disable();
7408 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007409 } else if (last){
7410 mixerStatus = MIXER_TRACKS_ENABLED;
7411 }
7412 }
7413 }
7414 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007415 if (track->isReady()) { // check ready to prevent premature start.
7416 processVolume_l(track, last);
7417 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007418 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007419
Eric Laurentea0fade2013-10-04 16:23:48 -07007420 // make sure the pause/flush/resume sequence is executed in the right order.
7421 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7422 // before flush and then resume HW. This can happen in case of pause/flush/resume
7423 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007424 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007425 status_t result = mOutput->stream->pause();
7426 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007427 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007428 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007429 if (mFlushPending) {
7430 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007431 }
Eric Laurentfd477972013-10-25 18:10:40 -07007432 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007433 status_t result = mOutput->stream->resume();
7434 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007435 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007436
Eric Laurentbfb1b832013-01-07 09:53:42 -08007437 // remove all the tracks that need to be...
7438 removeTracks_l(*tracksToRemove);
7439
7440 return mixerStatus;
7441}
7442
Eric Laurentbfb1b832013-01-07 09:53:42 -08007443// must be called with thread mutex locked
Andy Hungee58e4a2023-07-07 13:47:37 -07007444bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007445{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007446 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7447 mWriteAckSequence, mDrainSequence);
7448 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007449 return true;
7450 }
7451 return false;
7452}
7453
Andy Hungee58e4a2023-07-07 13:47:37 -07007454bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007455{
Andy Hung972bec12023-08-31 16:13:39 -07007456 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007457 return waitingAsyncCallback_l();
7458}
7459
Andy Hungee58e4a2023-07-07 13:47:37 -07007460void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007461{
Eric Laurente659ef42014-09-29 13:06:46 -07007462 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007463 // Flush anything still waiting in the mixbuffer
7464 mCurrentWriteLength = 0;
7465 mBytesRemaining = 0;
7466 mPausedWriteLength = 0;
7467 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007468 // reset bytes written count to reflect that DSP buffers are empty after flush.
7469 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007470
Eric Laurentbfb1b832013-01-07 09:53:42 -08007471 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007472 // discard any pending drain or write ack by incrementing sequence
7473 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7474 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007475 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007476 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7477 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007478 }
7479}
7480
Andy Hungee58e4a2023-07-07 13:47:37 -07007481void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007482{
Andy Hung972bec12023-08-31 16:13:39 -07007483 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007484 if (PlaybackThread::invalidateTracks_l(streamType)) {
7485 mFlushPending = true;
7486 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007487}
7488
Andy Hungee58e4a2023-07-07 13:47:37 -07007489void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hung972bec12023-08-31 16:13:39 -07007490 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007491 if (PlaybackThread::invalidateTracks_l(portIds)) {
7492 mFlushPending = true;
7493 }
7494}
7495
Eric Laurentbfb1b832013-01-07 09:53:42 -08007496// ----------------------------------------------------------------------------
7497
Andy Hungee58e4a2023-07-07 13:47:37 -07007498/* static */
7499sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung583043b2023-07-17 17:05:00 -07007500 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007501 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007502 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -07007503}
7504
Andy Hung583043b2023-07-17 17:05:00 -07007505DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007506 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -07007507 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007508 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007509 mWaitTimeMs(UINT_MAX)
7510{
7511 addOutputTrack(mainThread);
7512}
7513
Andy Hungee58e4a2023-07-07 13:47:37 -07007514DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007515{
7516 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7517 mOutputTracks[i]->destroy();
7518 }
7519}
7520
Andy Hungee58e4a2023-07-07 13:47:37 -07007521void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007522{
7523 // mix buffers...
Andy Hung920f6572022-10-06 12:09:49 -07007524 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007525 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007526 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007527 if (mMixerBufferValid) {
7528 memset(mMixerBuffer, 0, mMixerBufferSize);
7529 } else {
7530 memset(mSinkBuffer, 0, mSinkBufferSize);
7531 }
Eric Laurent81784c32012-11-19 14:55:58 -08007532 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007533 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007534 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007535 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007536 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007537}
7538
Andy Hungee58e4a2023-07-07 13:47:37 -07007539void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007540{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007541 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007542 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007543 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007544 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007545 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007546 }
7547 } else if (mBytesWritten != 0) {
7548 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7549 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007550 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007551 } else {
7552 // flush remaining overflow buffers in output tracks
7553 writeFrames = 0;
7554 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007555 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007556 }
7557}
7558
Andy Hungee58e4a2023-07-07 13:47:37 -07007559ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007560{
7561 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007562 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7563
7564 // Consider the first OutputTrack for timestamp and frame counting.
7565
7566 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7567 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7568 // we always claim success.
7569 if (i == 0) {
7570 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7571 ALOGD_IF(correction != 0 && writeFrames != 0,
7572 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7573 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7574 mFramesWritten -= correction;
7575 }
7576
7577 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007578 }
Andy Hungcf10d742020-04-28 15:38:24 -07007579 if (mStandby) {
7580 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007581 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007582 mStandby = false;
7583 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007584 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007585}
7586
Andy Hungee58e4a2023-07-07 13:47:37 -07007587void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007588{
7589 // DuplicatingThread implements standby by stopping all tracks
7590 for (size_t i = 0; i < outputTracks.size(); i++) {
7591 outputTracks[i]->stop();
7592 }
7593}
7594
Andy Hungee58e4a2023-07-07 13:47:37 -07007595void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007596{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007597 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007598
7599 std::stringstream ss;
7600 const size_t numTracks = mOutputTracks.size();
7601 ss << " " << numTracks << " OutputTracks";
7602 if (numTracks > 0) {
7603 ss << ":";
7604 for (const auto &track : mOutputTracks) {
Andy Hung87c693c2023-07-06 20:56:16 -07007605 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007606 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007607 if (thread.get() != nullptr) {
7608 ss << thread.get() << ", " << thread->id();
7609 } else {
7610 ss << "null";
7611 }
7612 ss << ")";
7613 }
7614 }
7615 ss << "\n";
7616 std::string result = ss.str();
7617 write(fd, result.c_str(), result.size());
7618}
7619
Andy Hungee58e4a2023-07-07 13:47:37 -07007620void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007621{
7622 outputTracks = mOutputTracks;
7623}
7624
Andy Hungee58e4a2023-07-07 13:47:37 -07007625void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007626{
7627 outputTracks.clear();
7628}
7629
Andy Hungee58e4a2023-07-07 13:47:37 -07007630void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007631{
Andy Hung972bec12023-08-31 16:13:39 -07007632 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007633 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7634 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7635 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7636 const size_t frameCount =
7637 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7638 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7639 // from different OutputTracks and their associated MixerThreads (e.g. one may
7640 // nearly empty and the other may be dropping data).
7641
Svet Ganov33761132021-05-13 22:51:08 +00007642 // TODO b/182392769: use attribution source util, move to server edge
7643 AttributionSourceState attributionSource = AttributionSourceState();
7644 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007645 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007646 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007647 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007648 attributionSource.token = sp<BBinder>::make();
Andy Hung8d31fd22023-06-26 19:20:57 -07007649 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007650 this,
7651 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007652 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007653 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007654 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007655 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007656 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7657 if (status != NO_ERROR) {
7658 ALOGE("addOutputTrack() initCheck failed %d", status);
7659 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007660 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007661 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7662 mOutputTracks.add(outputTrack);
7663 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7664 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007665}
7666
Andy Hungee58e4a2023-07-07 13:47:37 -07007667void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007668{
Andy Hung972bec12023-08-31 16:13:39 -07007669 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007670 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7671 if (mOutputTracks[i]->thread() == thread) {
7672 mOutputTracks[i]->destroy();
7673 mOutputTracks.removeAt(i);
7674 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007675 if (thread->getOutput() == mOutput) {
7676 mOutput = NULL;
7677 }
Eric Laurent81784c32012-11-19 14:55:58 -08007678 return;
7679 }
7680 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007681 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007682}
7683
Andy Hungc5007f82023-08-29 14:26:09 -07007684// caller must hold mutex()
Andy Hungee58e4a2023-07-07 13:47:37 -07007685void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007686{
7687 mWaitTimeMs = UINT_MAX;
7688 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007689 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007690 if (strong != 0) {
7691 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7692 if (waitTimeMs < mWaitTimeMs) {
7693 mWaitTimeMs = waitTimeMs;
7694 }
7695 }
7696 }
7697}
7698
Andy Hungee58e4a2023-07-07 13:47:37 -07007699bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007700{
7701 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung87c693c2023-07-06 20:56:16 -07007702 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007703 if (thread == 0) {
7704 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7705 outputTracks[i].get());
7706 return false;
7707 }
Andy Hung87c693c2023-07-06 20:56:16 -07007708 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007709 // see note at standby() declaration
Andy Hung440901d2023-06-29 21:19:25 -07007710 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007711 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7712 thread.get());
7713 return false;
7714 }
7715 }
7716 return true;
7717}
7718
Andy Hungee58e4a2023-07-07 13:47:37 -07007719void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007720 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007721{
Kevin Rocard12381092018-04-11 09:19:59 -07007722 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7723 outputTrack->setMetadatas(metadata.tracks);
7724 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007725}
7726
Andy Hungee58e4a2023-07-07 13:47:37 -07007727uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007728{
7729 return (mWaitTimeMs * 1000) / 2;
7730}
7731
Andy Hungee58e4a2023-07-07 13:47:37 -07007732void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007733{
7734 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7735 updateWaitTime_l();
7736
7737 MixerThread::cacheParameters_l();
7738}
7739
Eric Laurentb3f315a2021-07-13 15:09:05 +02007740// ----------------------------------------------------------------------------
7741
Andy Hungee58e4a2023-07-07 13:47:37 -07007742/* static */
7743sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung583043b2023-07-17 17:05:00 -07007744 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -07007745 AudioStreamOut* output,
7746 audio_io_handle_t id,
7747 bool systemReady,
7748 audio_config_base_t* mixerConfig) {
Andy Hung583043b2023-07-17 17:05:00 -07007749 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hungee58e4a2023-07-07 13:47:37 -07007750}
7751
Andy Hung583043b2023-07-17 17:05:00 -07007752SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007753 AudioStreamOut* output,
7754 audio_io_handle_t id,
7755 bool systemReady,
7756 audio_config_base_t *mixerConfig)
Andy Hung583043b2023-07-17 17:05:00 -07007757 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007758{
7759}
7760
Andy Hungee58e4a2023-07-07 13:47:37 -07007761void SpatializerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01007762 MixerThread::onFirstRef();
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007763
Andy Hung41ccf7f2022-12-14 14:25:49 -08007764 const pid_t tid = getTid();
7765 if (tid == -1) {
7766 // Unusual: PlaybackThread::onFirstRef() should set the threadLoop running.
7767 ALOGW("%s: Cannot update Spatializer mixer thread priority, not running", __func__);
7768 } else {
7769 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
7770 if (priorityBoost > 0) {
Andy Hungfeb4e5c2022-10-17 19:10:02 -07007771 stream()->setHalThreadPriority(priorityBoost);
7772 }
7773 }
Eric Laurent68a40a82022-05-03 18:15:04 +02007774}
7775
Andy Hungee58e4a2023-07-07 13:47:37 -07007776void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent68a40a82022-05-03 18:15:04 +02007777 // if mSupportedLatencyModes is empty, the HAL stream does not support
7778 // latency mode control and we can exit.
7779 if (mSupportedLatencyModes.empty()) {
7780 return;
7781 }
7782 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7783 if (mSupportedLatencyModes.size() == 1) {
7784 // If the HAL only support one latency mode currently, confirm the choice
7785 latencyMode = mSupportedLatencyModes[0];
7786 } else if (mSupportedLatencyModes.size() > 1) {
7787 // Request low latency if:
7788 // - The low latency mode is requested by the spatializer controller
7789 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7790 // AND
7791 // - At least one active track is spatialized
7792 bool hasSpatializedActiveTrack = false;
7793 for (const auto& track : mActiveTracks) {
7794 if (track->isSpatialized()) {
7795 hasSpatializedActiveTrack = true;
7796 break;
7797 }
7798 }
7799 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7800 latencyMode = AUDIO_LATENCY_MODE_LOW;
7801 }
7802 }
7803
7804 if (latencyMode != mSetLatencyMode) {
7805 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007806 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7807 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent68a40a82022-05-03 18:15:04 +02007808 if (status == NO_ERROR) {
7809 mSetLatencyMode = latencyMode;
7810 }
7811 }
7812}
7813
Andy Hungee58e4a2023-07-07 13:47:37 -07007814status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent68a40a82022-05-03 18:15:04 +02007815 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7816 return BAD_VALUE;
7817 }
Andy Hung972bec12023-08-31 16:13:39 -07007818 audio_utils::lock_guard _l(mutex());
Eric Laurent68a40a82022-05-03 18:15:04 +02007819 mRequestedLatencyMode = mode;
7820 return NO_ERROR;
7821}
7822
Andy Hungee58e4a2023-07-07 13:47:37 -07007823void SpatializerThread::checkOutputStageEffects()
Andy Hung972bec12023-08-31 16:13:39 -07007824NO_THREAD_SAFETY_ANALYSIS
7825// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007826{
7827 bool hasVirtualizer = false;
7828 bool hasDownMixer = false;
Andy Hung116bc262023-06-20 18:56:17 -07007829 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007830 {
Andy Hung972bec12023-08-31 16:13:39 -07007831 audio_utils::lock_guard _l(mutex());
Andy Hung116bc262023-06-20 18:56:17 -07007832 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007833 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007834 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007835 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7836 }
7837
7838 finalDownMixer = mFinalDownMixer;
7839 mFinalDownMixer.clear();
7840 }
7841
7842 if (hasVirtualizer) {
7843 if (finalDownMixer != nullptr) {
7844 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007845 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007846 }
7847 finalDownMixer.clear();
7848 } else if (!hasDownMixer) {
7849 std::vector<effect_descriptor_t> descriptors;
Andy Hung583043b2023-07-17 17:05:00 -07007850 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007851 EFFECT_UIID_DOWNMIX, &descriptors);
7852 if (status != NO_ERROR) {
7853 return;
7854 }
7855 ALOG_ASSERT(!descriptors.empty(),
7856 "%s getDescriptors() returned no error but empty list", __func__);
7857
7858 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7859 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007860 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007861
7862 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7863 ALOGW("%s error creating downmixer %d", __func__, status);
7864 finalDownMixer.clear();
7865 } else {
7866 int32_t ret;
Andy Hung116bc262023-06-20 18:56:17 -07007867 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007868 }
7869 }
7870
7871 {
Andy Hung972bec12023-08-31 16:13:39 -07007872 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007873 mFinalDownMixer = finalDownMixer;
7874 }
7875}
7876
Eric Laurent81784c32012-11-19 14:55:58 -08007877// ----------------------------------------------------------------------------
7878// Record
7879// ----------------------------------------------------------------------------
7880
Andy Hung583043b2023-07-17 17:05:00 -07007881sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung87c693c2023-07-06 20:56:16 -07007882 AudioStreamIn* input,
7883 audio_io_handle_t id,
7884 bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -07007885 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung87c693c2023-07-06 20:56:16 -07007886}
7887
Andy Hung583043b2023-07-17 17:05:00 -07007888RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007889 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007890 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007891 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007892 ) :
Andy Hung583043b2023-07-17 17:05:00 -07007893 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007894 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007895 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007896 mActiveTracks(&this->mLocalLog),
7897 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007898 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007899 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007900 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7901 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007902 // mFastCapture below
7903 , mFastCaptureFutex(0)
7904 // mInputSource
7905 // mPipeSink
7906 // mPipeSource
7907 , mPipeFramesP2(0)
7908 // mPipeMemory
7909 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007910 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007911 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007912{
Glenn Kastend7dca052015-03-05 16:05:54 -08007913 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung583043b2023-07-17 17:05:00 -07007914 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007915
George Burgess IVa8f90c12020-05-14 11:27:19 -07007916 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007917 mIsMsdDevice = strcmp(
7918 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7919 }
7920
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007921 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007922
Andy Hungc8fddf32018-08-08 18:32:37 -07007923 // TODO: We may also match on address as well as device type for
7924 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007925 // TODO: This property should be ensure that only contains one single device type.
7926 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7927 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007928 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7929 : AUDIO_DEVICE_NONE));
7930
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007931 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007932 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007933 size_t numCounterOffers = 0;
7934 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007935#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007936 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007937#else
7938 (void)
7939#endif
7940 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007941 ALOG_ASSERT(index == 0);
7942
7943 // initialize fast capture depending on configuration
7944 bool initFastCapture;
7945 switch (kUseFastCapture) {
7946 case FastCapture_Never:
7947 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007948 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007949 break;
7950 case FastCapture_Always:
7951 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007952 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007953 break;
7954 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007955 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7956 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7957 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7958 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7959 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007960 break;
7961 // case FastCapture_Dynamic:
7962 }
7963
7964 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007965 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007967 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7968 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007969 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007970 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007971 const sp<MemoryDealer> roHeap(readOnlyHeap());
7972 sp<IMemory> pipeMemory;
7973 if ((roHeap == 0) ||
7974 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007975 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007976 ALOGE("not enough memory for pipe buffer size=%zu; "
7977 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7978 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7979 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007980 goto failed;
7981 }
7982 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7983 memset(pipeBuffer, 0, pipeSize);
7984 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung920f6572022-10-06 12:09:49 -07007985 const NBAIO_Format offersFast[1] = {format};
7986 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007987 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007988 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007989 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007990 mPipeSink = pipe;
7991 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung920f6572022-10-06 12:09:49 -07007992 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007993 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung920f6572022-10-06 12:09:49 -07007994 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02007995 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007996 mPipeSource = pipeReader;
7997 mPipeFramesP2 = pipeFramesP2;
7998 mPipeMemory = pipeMemory;
7999
8000 // create fast capture
8001 mFastCapture = new FastCapture();
8002 FastCaptureStateQueue *sq = mFastCapture->sq();
8003#ifdef STATE_QUEUE_DUMP
8004 // FIXME
8005#endif
8006 FastCaptureState *state = sq->begin();
8007 state->mCblk = NULL;
8008 state->mInputSource = mInputSource.get();
8009 state->mInputSourceGen++;
8010 state->mPipeSink = pipe;
8011 state->mPipeSinkGen++;
8012 state->mFrameCount = mFrameCount;
8013 state->mCommand = FastCaptureState::COLD_IDLE;
8014 // already done in constructor initialization list
8015 //mFastCaptureFutex = 0;
8016 state->mColdFutexAddr = &mFastCaptureFutex;
8017 state->mColdGen++;
8018 state->mDumpState = &mFastCaptureDumpState;
8019#ifdef TEE_SINK
8020 // FIXME
8021#endif
Andy Hung583043b2023-07-17 17:05:00 -07008022 mFastCaptureNBLogWriter =
8023 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008024 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8025 sq->end();
8026 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8027
8028 // start the fast capture
8029 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8030 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008031 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008032 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008033#ifdef AUDIO_WATCHDOG
8034 // FIXME
8035#endif
8036
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008037 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008038 }
Andy Hung8946a282018-04-19 20:04:56 -07008039#ifdef TEE_SINK
8040 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8041 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8042#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008043failed: ;
8044
8045 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008046}
8047
Andy Hungee58e4a2023-07-07 13:47:37 -07008048RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008049{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008050 if (mFastCapture != 0) {
8051 FastCaptureStateQueue *sq = mFastCapture->sq();
8052 FastCaptureState *state = sq->begin();
8053 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8054 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8055 if (old == -1) {
8056 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8057 }
8058 }
8059 state->mCommand = FastCaptureState::EXIT;
8060 sq->end();
8061 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8062 mFastCapture->join();
8063 mFastCapture.clear();
8064 }
Andy Hung583043b2023-07-17 17:05:00 -07008065 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8066 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008067 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008068}
8069
Andy Hungee58e4a2023-07-07 13:47:37 -07008070void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008071{
Glenn Kastend7dca052015-03-05 16:05:54 -08008072 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008073}
8074
Andy Hungee58e4a2023-07-07 13:47:37 -07008075void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008076{
8077 ALOGV(" preExit()");
Andy Hung972bec12023-08-31 16:13:39 -07008078 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008079 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008080 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008081 track->invalidate();
8082 }
8083 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008084 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008085}
8086
Andy Hungee58e4a2023-07-07 13:47:37 -07008087bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008088{
Eric Laurent81784c32012-11-19 14:55:58 -08008089 nsecs_t lastWarning = 0;
8090
8091 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008092
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008093reacquire_wakelock:
Andy Hung8d31fd22023-06-26 19:20:57 -07008094 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008095 {
Andy Hung972bec12023-08-31 16:13:39 -07008096 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008097 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008098 }
8099
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008100 // used to request a deferred sleep, to be executed later while mutex is unlocked
8101 uint32_t sleepUs = 0;
8102
Andy Hung446f4df2019-02-21 12:26:41 -08008103 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8104
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008105 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008106 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hung116bc262023-06-20 18:56:17 -07008107 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008108
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008109 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung8d31fd22023-06-26 19:20:57 -07008110 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008111
Glenn Kasten735f45f2014-08-18 15:51:59 -07008112 // reference to the (first and only) active fast track
Andy Hung8d31fd22023-06-26 19:20:57 -07008113 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008114
Glenn Kasten735f45f2014-08-18 15:51:59 -07008115 // reference to a fast track which is about to be removed
Andy Hung8d31fd22023-06-26 19:20:57 -07008116 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008117
Eric Laurent33403f02020-05-29 18:35:06 -07008118 bool silenceFastCapture = false;
8119
Andy Hungc5007f82023-08-29 14:26:09 -07008120 { // scope for mutex()
8121 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008122
Eric Laurent021cf962014-05-13 10:18:14 -07008123 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008124
Eric Laurent000a4192014-01-29 15:17:32 -08008125 // check exitPending here because checkForNewParameters_l() and
Andy Hungc5007f82023-08-29 14:26:09 -07008126 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008127 if (exitPending()) {
8128 break;
8129 }
8130
Eric Laurent5c25d562016-07-13 17:17:45 -07008131 // sleep with mutex unlocked
8132 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008133 ATRACE_BEGIN("sleepC");
Andy Hungc5007f82023-08-29 14:26:09 -07008134 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008135 ATRACE_END();
8136 sleepUs = 0;
8137 continue;
8138 }
8139
Glenn Kasten2b806402013-11-20 16:37:38 -08008140 // if no active track(s), then standby and release wakelock
8141 size_t size = mActiveTracks.size();
8142 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008143 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008144 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008145 releaseWakeLock_l();
8146 ALOGV("RecordThread: loop stopping");
8147 // go to sleep
Andy Hungc5007f82023-08-29 14:26:09 -07008148 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008149 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008150 goto reacquire_wakelock;
8151 }
8152
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008153 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008154 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008155 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008156
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008157 activeTrack = mActiveTracks[i];
8158 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008159 if (activeTrack->isFastTrack()) {
8160 ALOG_ASSERT(fastTrackToRemove == 0);
8161 fastTrackToRemove = activeTrack;
8162 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008163 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008164 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008165 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008166 continue;
8167 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008168
Andy Hung8d31fd22023-06-26 19:20:57 -07008169 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008170 switch (activeTrackState) {
8171
Andy Hung8d31fd22023-06-26 19:20:57 -07008172 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008173 mActiveTracks.remove(activeTrack);
Andy Hung8d31fd22023-06-26 19:20:57 -07008174 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008175 doBroadcast = true;
8176 size--;
8177 continue;
8178
Andy Hung8d31fd22023-06-26 19:20:57 -07008179 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008180 sleepUs = 10000;
8181 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008182 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008183 continue;
8184
Andy Hung8d31fd22023-06-26 19:20:57 -07008185 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008186 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008187 if (mStandby) {
8188 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008189 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008190 mStandby = false;
8191 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008192 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008193 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008194 break;
8195
Andy Hung8d31fd22023-06-26 19:20:57 -07008196 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008197 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008198 break;
8199
Andy Hung8d31fd22023-06-26 19:20:57 -07008200 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8201 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8202 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008203 default:
Andy Hungce685402018-10-05 17:23:27 -07008204 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8205 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008206 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008207
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008208 if (activeTrack->isFastTrack()) {
8209 ALOG_ASSERT(!mFastTrackAvail);
8210 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008211 // if the active fast track is silenced either:
8212 // 1) silence the whole capture from fast capture buffer if this is
8213 // the only active track
8214 // 2) invalidate this track: this will cause the client to reconnect and possibly
8215 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008216 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008217 if (activeTrack->isSilenced()) {
8218 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008219 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008220 } else {
8221 silenceFastCapture = true;
8222 }
8223 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008224 // Invalidate fast tracks if access to audio history is required as this is not
8225 // possible with fast tracks. Once the fast track has been invalidated, no new
8226 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8227 if (mMaxSharedAudioHistoryMs != 0) {
8228 invalidate = true;
8229 }
8230 if (invalidate) {
8231 activeTrack->invalidate();
8232 ALOG_ASSERT(fastTrackToRemove == 0);
8233 fastTrackToRemove = activeTrack;
8234 removeTrack_l(activeTrack);
8235 mActiveTracks.remove(activeTrack);
8236 size--;
8237 continue;
8238 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008239 fastTrack = activeTrack;
8240 }
Eric Laurent33403f02020-05-29 18:35:06 -07008241
8242 activeTracks.add(activeTrack);
8243 i++;
8244
Glenn Kasten9e982352013-08-14 14:39:50 -07008245 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008246
Andy Hungdae27702016-10-31 14:01:16 -07008247 mActiveTracks.updatePowerState(this);
8248
Kevin Rocard069c2712018-03-29 19:09:14 -07008249 updateMetadata_l();
8250
Eric Laurent5c25d562016-07-13 17:17:45 -07008251 if (allStopped) {
8252 standbyIfNotAlreadyInStandby();
8253 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008254 if (doBroadcast) {
Andy Hungc5007f82023-08-29 14:26:09 -07008255 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008256 }
8257
8258 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008259 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008260 if (sleepUs == 0) {
8261 sleepUs = kRecordThreadSleepUs;
8262 }
8263 continue;
8264 }
8265 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008266
Eric Laurent81784c32012-11-19 14:55:58 -08008267 lockEffectChains_l(effectChains);
8268 }
8269
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008270 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008271
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008272 size_t size = effectChains.size();
8273 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008274 // thread mutex is not locked, but effect chain is locked
8275 effectChains[i]->process_l();
8276 }
8277
Glenn Kasten735f45f2014-08-18 15:51:59 -07008278 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008279 if (mFastCapture != 0) {
8280 FastCaptureStateQueue *sq = mFastCapture->sq();
8281 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008282 bool didModify = false;
8283 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008284 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8285 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8286 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8287 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8288 if (old == -1) {
8289 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8290 }
8291 }
8292 state->mCommand = FastCaptureState::READ_WRITE;
8293#if 0 // FIXME
Andy Hung583043b2023-07-17 17:05:00 -07008294 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008295 FastThreadDumpState::kSamplingNforLowRamDevice :
8296 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008297#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008298 didModify = true;
8299 }
8300 audio_track_cblk_t *cblkOld = state->mCblk;
8301 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8302 if (cblkNew != cblkOld) {
8303 state->mCblk = cblkNew;
8304 // block until acked if removing a fast track
8305 if (cblkOld != NULL) {
8306 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8307 }
8308 didModify = true;
8309 }
jiabin01c8f562018-07-19 17:47:28 -07008310 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8311 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8312 if (state->mFastPatchRecordBufferProvider != abp) {
8313 state->mFastPatchRecordBufferProvider = abp;
8314 state->mFastPatchRecordFormat = fastTrack == 0 ?
8315 AUDIO_FORMAT_INVALID : fastTrack->format();
8316 didModify = true;
8317 }
Eric Laurent33403f02020-05-29 18:35:06 -07008318 if (state->mSilenceCapture != silenceFastCapture) {
8319 state->mSilenceCapture = silenceFastCapture;
8320 didModify = true;
8321 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008322 sq->end(didModify);
8323 if (didModify) {
8324 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008325#if 0
8326 if (kUseFastCapture == FastCapture_Dynamic) {
8327 mNormalSource = mPipeSource;
8328 }
8329#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008330 }
8331 }
8332
Glenn Kasten735f45f2014-08-18 15:51:59 -07008333 // now run the fast track destructor with thread mutex unlocked
8334 fastTrackToRemove.clear();
8335
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008336 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8337 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8338 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8339 // If destination is non-contiguous, first read past the nominal end of buffer, then
8340 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008341
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008342 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung920f6572022-10-06 12:09:49 -07008343 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008344 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008345
8346 // If an NBAIO source is present, use it to read the normal capture's data
8347 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008348 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008349
8350 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8351 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8352 // we immediately retry the read() to get data and prevent another overflow.
8353 for (int retries = 0; retries <= 2; ++retries) {
8354 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8355 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8356 framesToRead);
8357 if (framesRead != OVERRUN) break;
8358 }
8359
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008360 const ssize_t availableToRead = mPipeSource->availableToRead();
8361 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008362 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008363 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008364 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8365 "more frames to read than fifo size, %zd > %zu",
8366 availableToRead, mPipeFramesP2);
8367 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8368 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8369 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8370 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008371 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8372 }
8373 if (framesRead < 0) {
8374 status_t status = (status_t) framesRead;
8375 switch (status) {
8376 case OVERRUN:
8377 ALOGW("overrun on read from pipe");
8378 framesRead = 0;
8379 break;
8380 case NEGOTIATE:
8381 ALOGE("re-negotiation is needed");
8382 framesRead = -1; // Will cause an attempt to recover.
8383 break;
8384 default:
8385 ALOGE("unknown error %d on read from pipe", status);
8386 break;
8387 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008388 }
8389 // otherwise use the HAL / AudioStreamIn directly
8390 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008391 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008392 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008393 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008394 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008395 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008396 if (result < 0) {
8397 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008398 } else {
8399 framesRead = bytesRead / mFrameSize;
8400 }
8401 }
8402
Andy Hung446f4df2019-02-21 12:26:41 -08008403 const int64_t lastIoEndNs = systemTime(); // end IO timing
8404
Andy Hung3f0c9022016-01-15 17:49:46 -08008405 // Update server timestamp with server stats
8406 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008407 if (framesRead >= 0) {
8408 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8409 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8410 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008411
8412 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008413 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008414 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008415 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008416 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8417 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8418 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008419 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008420 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8421
8422 mTimestampVerifier.add(position, time, mSampleRate);
8423
8424 // Correct timestamps
8425 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008426 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008427 id(), (long long)time, (long long)position);
8428 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8429 position = correctedTimestamp.mFrames;
8430 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008431 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008432 id(), (long long)time, (long long)position);
8433 }
8434
Andy Hung3f0c9022016-01-15 17:49:46 -08008435 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8436 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8437 // Note: In general record buffers should tend to be empty in
8438 // a properly running pipeline.
8439 //
8440 // Also, it is not advantageous to call get_presentation_position during the read
8441 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008442 } else {
8443 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008444 }
8445 }
Andy Hunge6c37112019-02-26 17:38:10 -08008446
8447 // From the timestamp, input read latency is negative output write latency.
8448 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung8d31fd22023-06-26 19:20:57 -07008449 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008450 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8451 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8452 mLatencyMs.add(latencyMs);
8453 }
8454
Andy Hung3f0c9022016-01-15 17:49:46 -08008455 // Use this to track timestamp information
8456 // ALOGD("%s", mTimestamp.toString().c_str());
8457
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008458 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008459 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008460 // Force input into standby so that it tries to recover at next read attempt
8461 inputStandBy();
8462 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008463 }
8464 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008465 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008466 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008467 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008468 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008469
Andy Hung8946a282018-04-19 20:04:56 -07008470#ifdef TEE_SINK
8471 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8472#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008473 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008474 {
8475 size_t part1 = mRsmpInFramesP2 - rear;
8476 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008477 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008478 (framesRead - part1) * mFrameSize);
8479 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008480 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008481 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008482
8483 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008484
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008485 // loop over each active track
8486 for (size_t i = 0; i < size; i++) {
8487 activeTrack = activeTracks[i];
8488
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008489 // skip fast tracks, as those are handled directly by FastCapture
8490 if (activeTrack->isFastTrack()) {
8491 continue;
8492 }
8493
Andy Hung73c02e42015-03-29 01:13:58 -07008494 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008495 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8496
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008497 enum {
8498 OVERRUN_UNKNOWN,
8499 OVERRUN_TRUE,
8500 OVERRUN_FALSE
8501 } overrun = OVERRUN_UNKNOWN;
8502
8503 // loop over getNextBuffer to handle circular sink
8504 for (;;) {
8505
Andy Hung8d31fd22023-06-26 19:20:57 -07008506 activeTrack->sinkBuffer().frameCount = ~0;
8507 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8508 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008509 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8510
Andy Hung73c02e42015-03-29 01:13:58 -07008511 // check available frames and handle overrun conditions
8512 // if the record track isn't draining fast enough.
8513 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514 size_t framesIn;
Andy Hung8d31fd22023-06-26 19:20:57 -07008515 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008516 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008517 overrun = OVERRUN_TRUE;
8518 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008519 if (framesOut == 0 || framesIn == 0) {
8520 break;
8521 }
8522
Andy Hung6770c6f2015-04-07 13:43:36 -07008523 // Don't allow framesOut to be larger than what is possible with resampling
8524 // from framesIn.
8525 // This isn't strictly necessary but helps limit buffer resizing in
8526 // RecordBufferConverter. TODO: remove when no longer needed.
8527 framesOut = min(framesOut,
8528 destinationFramesPossible(
Andy Hung8d31fd22023-06-26 19:20:57 -07008529 framesIn, mSampleRate, activeTrack->sampleRate()));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008530
8531 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008532 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008533 // straight from RecordThread buffer to RecordTrack buffer.
8534 AudioBufferProvider::Buffer buffer;
8535 buffer.frameCount = framesOut;
Andy Hung920f6572022-10-06 12:09:49 -07008536 const status_t getNextBufferStatus =
Andy Hung8d31fd22023-06-26 19:20:57 -07008537 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung920f6572022-10-06 12:09:49 -07008538 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008539 ALOGV_IF(buffer.frameCount != framesOut,
8540 "%s() read less than expected (%zu vs %zu)",
8541 __func__, buffer.frameCount, framesOut);
8542 framesOut = buffer.frameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008543 memcpy(activeTrack->sinkBuffer().raw,
8544 buffer.raw, buffer.frameCount * mFrameSize);
8545 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008546 } else {
8547 framesOut = 0;
8548 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung920f6572022-10-06 12:09:49 -07008549 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008550 }
8551 } else {
8552 // process frames from the RecordThread buffer provider to the RecordTrack
8553 // buffer
Andy Hung8d31fd22023-06-26 19:20:57 -07008554 framesOut = activeTrack->recordBufferConverter()->convert(
8555 activeTrack->sinkBuffer().raw,
8556 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008557 framesOut);
8558 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008559
8560 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8561 overrun = OVERRUN_FALSE;
8562 }
8563
Andy Hung93bb5732023-05-04 21:16:34 -07008564 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8565 const ssize_t framesToDrop =
Andy Hung8d31fd22023-06-26 19:20:57 -07008566 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008567 if (framesToDrop == 0) {
8568 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008569 if (framesOut > 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008570 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008571 // Sanitize before releasing if the track has no access to the source data
8572 // An idle UID receives silence from non virtual devices until active
8573 if (activeTrack->isSilenced()) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008574 memset(activeTrack->sinkBuffer().raw,
8575 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008576 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008577 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008578 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008579 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008580 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008581 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008582 }
8583 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008584
8585 switch (overrun) {
8586 case OVERRUN_TRUE:
8587 // client isn't retrieving buffers fast enough
8588 if (!activeTrack->setOverflow()) {
8589 nsecs_t now = systemTime();
8590 // FIXME should lastWarning per track?
8591 if ((now - lastWarning) > kWarningThrottleNs) {
8592 ALOGW("RecordThread: buffer overflow");
8593 lastWarning = now;
8594 }
8595 }
8596 break;
8597 case OVERRUN_FALSE:
8598 activeTrack->clearOverflow();
8599 break;
8600 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008601 break;
8602 }
8603
Andy Hung3f0c9022016-01-15 17:49:46 -08008604 // update frame information and push timestamp out
8605 activeTrack->updateTrackFrameInfo(
Andy Hung8d31fd22023-06-26 19:20:57 -07008606 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008607 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8608 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008609 }
8610
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008611unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008612 // enable changes in effect chain
8613 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008614 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008615 if (audio_has_proportional_frames(mFormat)
8616 && loopCount == lastLoopCountRead + 1) {
8617 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8618 const double jitterMs =
8619 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8620 {framesRead, readPeriodNs},
8621 {0, 0} /* lastTimestamp */, mSampleRate);
8622 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8623
Andy Hung972bec12023-08-31 16:13:39 -07008624 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008625 mIoJitterMs.add(jitterMs);
8626 mProcessTimeMs.add(processMs);
8627 }
8628 // update timing info.
8629 mLastIoBeginNs = lastIoBeginNs;
8630 mLastIoEndNs = lastIoEndNs;
8631 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008632 }
8633
Glenn Kasten93e471f2013-08-19 08:40:07 -07008634 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008635
8636 {
Andy Hung972bec12023-08-31 16:13:39 -07008637 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008638 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008639 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008640 track->invalidate();
8641 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008642 mActiveTracks.clear();
Andy Hungc5007f82023-08-29 14:26:09 -07008643 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008644 }
8645
8646 releaseWakeLock();
8647
8648 ALOGV("RecordThread %p exiting", this);
8649 return false;
8650}
8651
Andy Hungee58e4a2023-07-07 13:47:37 -07008652void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008653{
8654 if (!mStandby) {
8655 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008656 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008657 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008658 mStandby = true;
8659 }
8660}
8661
Andy Hungee58e4a2023-07-07 13:47:37 -07008662void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008663{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008664 // Idle the fast capture if it's currently running
8665 if (mFastCapture != 0) {
8666 FastCaptureStateQueue *sq = mFastCapture->sq();
8667 FastCaptureState *state = sq->begin();
8668 if (!(state->mCommand & FastCaptureState::IDLE)) {
8669 state->mCommand = FastCaptureState::COLD_IDLE;
8670 state->mColdFutexAddr = &mFastCaptureFutex;
8671 state->mColdGen++;
8672 mFastCaptureFutex = 0;
8673 sq->end();
8674 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8675 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8676#if 0
8677 if (kUseFastCapture == FastCapture_Dynamic) {
8678 // FIXME
8679 }
8680#endif
8681#ifdef AUDIO_WATCHDOG
8682 // FIXME
8683#endif
8684 } else {
8685 sq->end(false /*didModify*/);
8686 }
8687 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008688 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008689 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008690
8691 // If going into standby, flush the pipe source.
8692 if (mPipeSource.get() != nullptr) {
8693 const ssize_t flushed = mPipeSource->flush();
8694 if (flushed > 0) {
8695 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8696 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8697 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8698 }
8699 }
Eric Laurent81784c32012-11-19 14:55:58 -08008700}
8701
Andy Hungc5007f82023-08-29 14:26:09 -07008702// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07008703sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hung88035ac2023-06-27 17:05:02 -07008704 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008705 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008706 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008707 audio_format_t format,
8708 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008709 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008710 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008711 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008712 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008713 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008714 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008715 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008716 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008717 audio_port_handle_t portId,
8718 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008719{
Glenn Kasten74935e42013-12-19 08:56:45 -08008720 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008721 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung8d31fd22023-06-26 19:20:57 -07008722 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008723 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008724 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008725 audio_input_flags_t requestedFlags = *flags;
8726 uint32_t sampleRate;
8727
8728 lStatus = initCheck();
8729 if (lStatus != NO_ERROR) {
8730 ALOGE("createRecordTrack_l() audio driver not initialized");
8731 goto Exit;
8732 }
8733
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008734 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8735 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8736 lStatus = BAD_VALUE;
8737 goto Exit;
8738 }
8739
Eric Laurentec376dc2021-04-08 20:41:22 +02008740 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008741 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008742 lStatus = PERMISSION_DENIED;
8743 goto Exit;
8744 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008745 if (maxSharedAudioHistoryMs < 0
Andy Hung25a80ac2023-07-19 12:47:35 -07008746 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008747 lStatus = BAD_VALUE;
8748 goto Exit;
8749 }
8750 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008751 if (*pSampleRate == 0) {
8752 *pSampleRate = mSampleRate;
8753 }
8754 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008755
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008756 // special case for FAST flag considered OK if fast capture is present and access to
8757 // audio history is not required
8758 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008759 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8760 }
8761
Eric Laurentf14db3c2017-12-08 14:20:36 -08008762 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008763 if ((*flags & inputFlags) != *flags) {
8764 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8765 " input flags (%08x)",
8766 *flags, inputFlags);
8767 *flags = (audio_input_flags_t)(*flags & inputFlags);
8768 }
Eric Laurent81784c32012-11-19 14:55:58 -08008769
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008770 // client expresses a preference for FAST and no access to audio history,
8771 // but we get the final say
8772 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008773 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008774 // we formerly checked for a callback handler (non-0 tid),
8775 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008776 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008777 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008778 // Frame count is not specified (0), or is less than or equal the pipe depth.
8779 // It is OK to provide a higher capacity than requested.
8780 // We will force it to mPipeFramesP2 below.
8781 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008782 // PCM data
8783 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008784 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008785 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008786 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008787 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008788 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008789 hasFastCapture() &&
8790 // there are sufficient fast track slots available
8791 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008792 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008793 // check compatibility with audio effects.
Andy Hung972bec12023-08-31 16:13:39 -07008794 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008795 // Do not accept FAST flag if the session has software effects
Andy Hung116bc262023-06-20 18:56:17 -07008796 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008797 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008798 audio_input_flags_t old = *flags;
8799 chain->checkInputFlagCompatibility(flags);
8800 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008801 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8802 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008803 }
8804 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008805 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008806 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8807 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008808 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008809 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8810 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008811 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008812 this, frameCount, mFrameCount, mPipeFramesP2,
8813 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008814 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008815 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008816 }
8817 }
8818
Eric Laurentf14db3c2017-12-08 14:20:36 -08008819 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8820 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8821 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8822 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8823 lStatus = BAD_TYPE;
8824 goto Exit;
8825 }
8826
Glenn Kasten74105912014-07-03 12:28:53 -07008827 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008828 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008829 // fast track: frame count is exactly the pipe depth
8830 frameCount = mPipeFramesP2;
8831 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008832 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008833 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008834 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8835 // or 20 ms if there is a fast capture
8836 // TODO This could be a roundupRatio inline, and const
8837 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8838 * sampleRate + mSampleRate - 1) / mSampleRate;
8839 // minimum number of notification periods is at least kMinNotifications,
8840 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8841 static const size_t kMinNotifications = 3;
8842 static const uint32_t kMinMs = 30;
8843 // TODO This could be a roundupRatio inline
8844 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8845 // TODO This could be a roundupRatio inline
8846 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8847 maxNotificationFrames;
8848 const size_t minFrameCount = maxNotificationFrames *
8849 max(kMinNotifications, minNotificationsByMs);
8850 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008851 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8852 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008853 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008854 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008855 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008856 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008857
Andy Hungc5007f82023-08-29 14:26:09 -07008858 { // scope for mutex()
Andy Hung972bec12023-08-31 16:13:39 -07008859 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008860 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008861 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008862 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008863 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008864 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008865 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008866 }
Eric Laurent81784c32012-11-19 14:55:58 -08008867
Andy Hung8d31fd22023-06-26 19:20:57 -07008868 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008869 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008870 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung8d31fd22023-06-26 19:20:57 -07008871 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008872 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008873
Glenn Kasten03003332013-08-06 15:40:54 -07008874 lStatus = track->initCheck();
8875 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008876 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008877 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008878 goto Exit;
8879 }
8880 mTracks.add(track);
8881
Eric Laurent05067782016-06-01 18:27:28 -07008882 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008883 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8884 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8885 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008886 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008887 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008888
8889 if (maxSharedAudioHistoryMs != 0) {
8890 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8891 }
Eric Laurent81784c32012-11-19 14:55:58 -08008892 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008893
Eric Laurent81784c32012-11-19 14:55:58 -08008894 lStatus = NO_ERROR;
8895
8896Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008897 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008898 return track;
8899}
8900
Andy Hungee58e4a2023-07-07 13:47:37 -07008901status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008902 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008903 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008904{
8905 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8906 sp<ThreadBase> strongMe = this;
8907 status_t status = NO_ERROR;
8908
8909 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008910 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008911 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008912 recordTrack->synchronizedRecordState().startRecording(
Andy Hung583043b2023-07-17 17:05:00 -07008913 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008914 event, triggerSession,
8915 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008916 }
8917
8918 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008919 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hung972bec12023-08-31 16:13:39 -07008920 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07008921 if (recordTrack->isInvalid()) {
8922 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008923 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8924 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008925 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008926 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung8d31fd22023-06-26 19:20:57 -07008927 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008928 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8929 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008930 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung8d31fd22023-06-26 19:20:57 -07008931 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008932 } else {
Andy Hung8d31fd22023-06-26 19:20:57 -07008933 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008934 }
8935 return status;
8936 }
8937
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008938 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8939 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8940 // or using a separate command thread
Andy Hung8d31fd22023-06-26 19:20:57 -07008941 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008942 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008943 if (recordTrack->isExternalTrack()) {
Andy Hungc5007f82023-08-29 14:26:09 -07008944 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008945 status = AudioSystem::startInput(recordTrack->portId());
Andy Hungc5007f82023-08-29 14:26:09 -07008946 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07008947 if (recordTrack->isInvalid()) {
8948 recordTrack->clearSyncStartEvent();
Andy Hung8d31fd22023-06-26 19:20:57 -07008949 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8950 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008951 // STARTING_2 forces destroy to call stopInput.
8952 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008953 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8954 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008955 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008956 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008957 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung8d31fd22023-06-26 19:20:57 -07008958 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008959 // Someone else has changed state, let them take over,
8960 // leave mState in the new state.
8961 recordTrack->clearSyncStartEvent();
8962 return INVALID_OPERATION;
8963 }
8964 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008965 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008966 ALOGW("%s(%d): startInput failed, status %d",
8967 __func__, recordTrack->id(), status);
8968 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8969 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008970 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008971 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008972 return status;
8973 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008974 sendIoConfigEvent_l(
8975 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008976 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008977
8978 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8979
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008980 // Catch up with current buffer indices if thread is already running.
8981 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8982 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8983 // see previously buffered data before it called start(), but with greater risk of overrun.
8984
Andy Hung8d31fd22023-06-26 19:20:57 -07008985 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008986 if (!recordTrack->isDirect()) {
8987 // clear any converter state as new data will be discontinuous
Andy Hung8d31fd22023-06-26 19:20:57 -07008988 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008989 }
Andy Hung8d31fd22023-06-26 19:20:57 -07008990 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08008991 // signal thread to start
Andy Hungc5007f82023-08-29 14:26:09 -07008992 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008993 return status;
8994 }
Eric Laurent81784c32012-11-19 14:55:58 -08008995}
8996
Andy Hungee58e4a2023-07-07 13:47:37 -07008997void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08008998{
Andy Hungee58e4a2023-07-07 13:47:37 -07008999 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009000
9001 if (strongEvent != 0) {
Andy Hungd29af632023-06-23 19:27:19 -07009002 sp<IAfTrackBase> ptr =
9003 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9004 if (ptr != nullptr) {
Andy Hung99b1ba62023-07-14 11:00:08 -07009005 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hungd29af632023-06-23 19:27:19 -07009006 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009007 }
Eric Laurent81784c32012-11-19 14:55:58 -08009008 }
9009}
9010
Andy Hungee58e4a2023-07-07 13:47:37 -07009011bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009012 ALOGV("RecordThread::stop");
Andy Hungc5007f82023-08-29 14:26:09 -07009013 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009014 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung8d31fd22023-06-26 19:20:57 -07009015 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009016 return false;
9017 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009018 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung8d31fd22023-06-26 19:20:57 -07009019 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009020
Andy Hungabfab202019-03-07 19:45:54 -08009021 // NOTE: Waiting here is important to keep stop synchronous.
9022 // This is needed for proper patchRecord peer release.
Andy Hung8d31fd22023-06-26 19:20:57 -07009023 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hungc5007f82023-08-29 14:26:09 -07009024 mWaitWorkCV.notify_all(); // signal thread to stop
9025 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009026 }
Andy Hungce685402018-10-05 17:23:27 -07009027
Andy Hung8d31fd22023-06-26 19:20:57 -07009028 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009029 ALOGV("Record stopped OK");
9030 return true;
9031 }
Andy Hungce685402018-10-05 17:23:27 -07009032
9033 // don't handle anything - we've been invalidated or restarted and in a different state
9034 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung8d31fd22023-06-26 19:20:57 -07009035 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009036 return false;
9037}
9038
Andy Hungee58e4a2023-07-07 13:47:37 -07009039bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009040{
9041 return false;
9042}
9043
Andy Hungee58e4a2023-07-07 13:47:37 -07009044status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009045{
9046#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9047 if (!isValidSyncEvent(event)) {
9048 return BAD_VALUE;
9049 }
9050
Glenn Kastend848eb42016-03-08 13:42:11 -08009051 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009052 status_t ret = NAME_NOT_FOUND;
9053
Andy Hung972bec12023-08-31 16:13:39 -07009054 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009055
9056 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009057 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009058 if (eventSession == track->sessionId()) {
9059 (void) track->setSyncEvent(event);
9060 ret = NO_ERROR;
9061 }
9062 }
9063 return ret;
9064#else
9065 return BAD_VALUE;
9066#endif
9067}
9068
Andy Hungee58e4a2023-07-07 13:47:37 -07009069status_t RecordThread::getActiveMicrophones(
Andy Hung87c693c2023-07-06 20:56:16 -07009070 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009071{
9072 ALOGV("RecordThread::getActiveMicrophones");
Andy Hung972bec12023-08-31 16:13:39 -07009073 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009074 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009075 return NO_INIT;
9076 }
jiabin9ff780e2018-03-19 18:19:52 -07009077 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9078 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009079}
9080
Andy Hungee58e4a2023-07-07 13:47:37 -07009081status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009082 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009083{
Paul McLean12340082019-03-19 09:35:05 -06009084 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hung972bec12023-08-31 16:13:39 -07009085 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009086 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009087 return NO_INIT;
9088 }
Paul McLean12340082019-03-19 09:35:05 -06009089 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009090}
9091
Andy Hungee58e4a2023-07-07 13:47:37 -07009092status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009093{
Paul McLean12340082019-03-19 09:35:05 -06009094 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hung972bec12023-08-31 16:13:39 -07009095 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009096 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009097 return NO_INIT;
9098 }
Paul McLean12340082019-03-19 09:35:05 -06009099 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009100}
9101
Andy Hungee58e4a2023-07-07 13:47:37 -07009102status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009103 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9104 int64_t sharedAudioStartMs) {
Andy Hung972bec12023-08-31 16:13:39 -07009105 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009106 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9107}
9108
Andy Hungee58e4a2023-07-07 13:47:37 -07009109status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009110 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9111 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009112
Eric Laurentec376dc2021-04-08 20:41:22 +02009113 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9114 return BAD_VALUE;
9115 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009116
9117 if (sharedAudioStartMs < 0
9118 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009119 return BAD_VALUE;
9120 }
9121
Eric Laurent2407ce32021-04-26 14:56:03 +02009122 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9123 // As we cannot detect more than one wraparound, only accept values up current write position
9124 // after one wraparound
9125 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9126 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009127 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009128 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9129 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009130 // Bring the start frame position within the input buffer to match the documented
9131 // "best effort" behavior of the API.
9132 if (sharedOffset < 0) {
9133 sharedAudioStartFrames = mRsmpInRear;
Andy Hung920f6572022-10-06 12:09:49 -07009134 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009135 sharedAudioStartFrames =
9136 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009137 }
9138
Eric Laurentec376dc2021-04-08 20:41:22 +02009139 mSharedAudioPackageName = sharedAudioPackageName;
9140 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009141 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009142 } else {
9143 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009144 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009145 }
9146 return NO_ERROR;
9147}
9148
Andy Hungee58e4a2023-07-07 13:47:37 -07009149void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009150 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9151 mSharedAudioStartFrames = -1;
9152 mSharedAudioPackageName = "";
9153}
9154
Andy Hungee58e4a2023-07-07 13:47:37 -07009155ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009156{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009157 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009158 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009159 }
9160 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009161 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung8d31fd22023-06-26 19:20:57 -07009162 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009163 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009164 }
9165 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009166 MetadataUpdate change;
9167 change.recordMetadataUpdate = metadata.tracks;
9168 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009169}
9170
Andy Hungc5007f82023-08-29 14:26:09 -07009171// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -07009172void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009173{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009174 track->terminate();
Andy Hung8d31fd22023-06-26 19:20:57 -07009175 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009176
Eric Laurent81784c32012-11-19 14:55:58 -08009177 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009178 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009179 removeTrack_l(track);
9180 }
9181}
9182
Andy Hungee58e4a2023-07-07 13:47:37 -07009183void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009184{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009185 String8 result;
9186 track->appendDump(result, false /* active */);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009187 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009188
Eric Laurent81784c32012-11-19 14:55:58 -08009189 mTracks.remove(track);
9190 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009191 if (track->isFastTrack()) {
9192 ALOG_ASSERT(!mFastTrackAvail);
9193 mFastTrackAvail = true;
9194 }
Eric Laurent81784c32012-11-19 14:55:58 -08009195}
9196
Andy Hungee58e4a2023-07-07 13:47:37 -07009197void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009198{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009199 AudioStreamIn *input = mInput;
9200 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9201 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009202 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009203 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009204 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009205 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009206 }
Andy Hungbfa64962017-06-12 14:43:19 -07009207
9208 if (input != nullptr) {
9209 dprintf(fd, " Hal stream dump:\n");
9210 (void)input->stream->dump(fd);
9211 }
9212
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009213 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009214 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009215
Glenn Kasten2f90c512015-12-02 11:40:09 -08009216 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9217 // while we are dumping it. It may be inconsistent, but it won't mutate!
9218 // This is a large object so we place it on the heap.
9219 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009220 const std::unique_ptr<FastCaptureDumpState> copy =
9221 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009222 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009223}
9224
Andy Hungee58e4a2023-07-07 13:47:37 -07009225void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009226{
Eric Laurent81784c32012-11-19 14:55:58 -08009227 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009228 size_t numtracks = mTracks.size();
9229 size_t numactive = mActiveTracks.size();
9230 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009231 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009232 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009233 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009234 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009235 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009236 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009237 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009238 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009239 if (track != 0) {
9240 bool active = mActiveTracks.indexOf(track) >= 0;
9241 if (active) {
9242 numactiveseen++;
9243 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009244 result.append(prefix);
9245 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009246 }
Eric Laurent81784c32012-11-19 14:55:58 -08009247 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009248 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009249 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009250 }
9251
Marco Nelissenb2208842014-02-07 14:00:50 -08009252 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009253 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009254 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009255 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009256 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009257 for (size_t i = 0; i < numactive; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009258 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009259 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009260 result.append(prefix);
9261 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009262 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009263 }
Eric Laurent81784c32012-11-19 14:55:58 -08009264
9265 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009266 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009267}
9268
Andy Hungee58e4a2023-07-07 13:47:37 -07009269void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009270{
Andy Hung972bec12023-08-31 16:13:39 -07009271 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009272 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009273 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009274 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009275 track->setSilenced(silenced);
9276 }
9277 }
9278}
Andy Hung73c02e42015-03-29 01:13:58 -07009279
Andy Hung8d31fd22023-06-26 19:20:57 -07009280void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009281{
Andy Hung87c693c2023-07-06 20:56:16 -07009282 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009283 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009284 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009285 const int32_t rear = recordThread->mRsmpInRear;
9286 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009287 if (mRecordTrack->startFrames() >= 0) {
9288 int32_t startFrames = mRecordTrack->startFrames();
9289 // Accept a recent wraparound of mRsmpInRear
9290 if (startFrames <= rear) {
9291 deltaFrames = rear - startFrames;
9292 } else {
9293 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009294 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009295 // start frame cannot be further in the past than start of resampling buffer
9296 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9297 deltaFrames = recordThread->mRsmpInFrames;
9298 }
9299 }
9300 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009301}
9302
Andy Hung8d31fd22023-06-26 19:20:57 -07009303void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009304 size_t *framesAvailable, bool *hasOverrun)
9305{
Andy Hung87c693c2023-07-06 20:56:16 -07009306 const auto threadBase = mRecordTrack->thread().promote();
Andy Hungee58e4a2023-07-07 13:47:37 -07009307 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009308 const int32_t rear = recordThread->mRsmpInRear;
9309 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009310 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009311
9312 size_t framesIn;
9313 bool overrun = false;
9314 if (filled < 0) {
9315 // should not happen, but treat like a massive overrun and re-sync
9316 framesIn = 0;
9317 mRsmpInFront = rear;
9318 overrun = true;
9319 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9320 framesIn = (size_t) filled;
9321 } else {
9322 // client is not keeping up with server, but give it latest data
9323 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009324 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9325 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009326 overrun = true;
9327 }
9328 if (framesAvailable != NULL) {
9329 *framesAvailable = framesIn;
9330 }
9331 if (hasOverrun != NULL) {
9332 *hasOverrun = overrun;
9333 }
9334}
9335
Eric Laurent81784c32012-11-19 14:55:58 -08009336// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009337status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009338 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009339{
Andy Hung87c693c2023-07-06 20:56:16 -07009340 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009341 if (threadBase == 0) {
9342 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009343 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009344 return NOT_ENOUGH_DATA;
9345 }
Andy Hungee58e4a2023-07-07 13:47:37 -07009346 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009347 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009348 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009349 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009350 // FIXME should not be P2 (don't want to increase latency)
9351 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009352 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009353 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009354
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009355 front &= recordThread->mRsmpInFramesP2 - 1;
9356 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009357 if (part1 > (size_t) filled) {
9358 part1 = filled;
9359 }
9360 size_t ask = buffer->frameCount;
9361 ALOG_ASSERT(ask > 0);
9362 if (part1 > ask) {
9363 part1 = ask;
9364 }
9365 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009366 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009367 buffer->raw = NULL;
9368 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009369 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009370 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009371 }
9372
Andy Hung57446612015-04-19 23:56:46 -07009373 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009374 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009375 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009376 return NO_ERROR;
9377}
9378
9379// AudioBufferProvider interface
Andy Hung8d31fd22023-06-26 19:20:57 -07009380void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009381 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009382{
Hongwei Wang95e37682019-04-12 11:13:36 -07009383 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009384 if (stepCount == 0) {
9385 return;
9386 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009387 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009388 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009389 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009390 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009391 buffer->frameCount = 0;
9392}
9393
Andy Hungee58e4a2023-07-07 13:47:37 -07009394void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009395{
Andy Hung972bec12023-08-31 16:13:39 -07009396 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009397 checkBtNrec_l();
9398}
9399
Andy Hungee58e4a2023-07-07 13:47:37 -07009400void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009401{
9402 // disable AEC and NS if the device is a BT SCO headset supporting those
9403 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009404 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung583043b2023-07-17 17:05:00 -07009405 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009406 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9407 for (size_t i = 0; i < mEffectChains.size(); i++) {
9408 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9409 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9410 }
9411 }
9412}
9413
Andy Hung97a893e2015-03-29 01:03:07 -07009414
Andy Hungee58e4a2023-07-07 13:47:37 -07009415bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009416 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009417{
9418 bool reconfig = false;
9419
Eric Laurent10351942014-05-08 18:49:52 -07009420 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009421
Eric Laurent10351942014-05-08 18:49:52 -07009422 audio_format_t reqFormat = mFormat;
9423 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009424 // 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 +08009425 [[maybe_unused]] audio_channel_mask_t channelMask =
9426 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009427
9428 AudioParameter param = AudioParameter(keyValuePair);
9429 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009430
9431 // scope for AutoPark extends to end of method
9432 AutoPark<FastCapture> park(mFastCapture);
9433
Eric Laurent10351942014-05-08 18:49:52 -07009434 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9435 // channel count change can be requested. Do we mandate the first client defines the
9436 // HAL sampling rate and channel count or do we allow changes on the fly?
9437 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9438 samplingRate = value;
9439 reconfig = true;
9440 }
9441 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009442 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009443 status = BAD_VALUE;
9444 } else {
9445 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009446 reconfig = true;
9447 }
Eric Laurent10351942014-05-08 18:49:52 -07009448 }
9449 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9450 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009451 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009452 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009453 status = BAD_VALUE;
9454 } else {
9455 channelMask = mask;
9456 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009457 }
Eric Laurent10351942014-05-08 18:49:52 -07009458 }
9459 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9460 // do not accept frame count changes if tracks are open as the track buffer
9461 // size depends on frame count and correct behavior would not be guaranteed
9462 // if frame count is changed after track creation
9463 if (mActiveTracks.size() > 0) {
9464 status = INVALID_OPERATION;
9465 } else {
9466 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009467 }
Eric Laurent10351942014-05-08 18:49:52 -07009468 }
9469 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009470 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009471 }
9472 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9473 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009474 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009475 }
Glenn Kastene198c362013-08-13 09:13:36 -07009476
Eric Laurent10351942014-05-08 18:49:52 -07009477 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009478 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009479 if (status == INVALID_OPERATION) {
9480 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009481 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009482 }
9483 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009484 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009485 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9486 if (mInput->stream->getAudioProperties(&config) == OK &&
9487 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9488 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009489 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009490 status = NO_ERROR;
9491 }
Eric Laurent81784c32012-11-19 14:55:58 -08009492 }
Eric Laurent10351942014-05-08 18:49:52 -07009493 if (status == NO_ERROR) {
9494 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009495 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009496 }
9497 }
Eric Laurent81784c32012-11-19 14:55:58 -08009498 }
Eric Laurent10351942014-05-08 18:49:52 -07009499
Eric Laurent81784c32012-11-19 14:55:58 -08009500 return reconfig;
9501}
9502
Andy Hungee58e4a2023-07-07 13:47:37 -07009503String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009504{
Andy Hung972bec12023-08-31 16:13:39 -07009505 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009506 if (initCheck() == NO_ERROR) {
9507 String8 out_s8;
9508 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9509 return out_s8;
9510 }
Eric Laurent81784c32012-11-19 14:55:58 -08009511 }
Andy Hung920f6572022-10-06 12:09:49 -07009512 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009513}
9514
Andy Hungee58e4a2023-07-07 13:47:37 -07009515void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009516 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009517 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009518 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009519 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009520 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009521 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009522 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9523 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009524 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009525 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009526 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009527 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009528 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009529 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009530 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009531 break;
9532 }
Andy Hung583043b2023-07-17 17:05:00 -07009533 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009534}
9535
Andy Hungee58e4a2023-07-07 13:47:37 -07009536void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009537{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009538 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9539 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009540 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009541 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9542 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009543 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9544 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009545 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009546 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009547 ALOGI("HAL format %#x is not linear pcm", mFormat);
9548 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009549 result = mInput->stream->getFrameSize(&mFrameSize);
9550 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009551 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9552 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009553 result = mInput->stream->getBufferSize(&mBufferSize);
9554 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009555 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009556 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9557 "mBufferSize=%zu, mFrameCount=%zu",
9558 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009559
Eric Laurentec376dc2021-04-08 20:41:22 +02009560 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9561 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009562 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009563
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009564 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9565 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009566
9567 audio_input_flags_t flags = mInput->flags;
9568 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9569 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -07009570 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009571 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9572 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9573 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9574 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9575 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9576 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009577}
9578
Andy Hungee58e4a2023-07-07 13:47:37 -07009579uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009580{
Andy Hung972bec12023-08-31 16:13:39 -07009581 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009582 uint32_t result;
9583 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9584 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009585 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009586 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009587}
9588
Andy Hungee58e4a2023-07-07 13:47:37 -07009589KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009590{
Glenn Kastend848eb42016-03-08 13:42:11 -08009591 KeyedVector<audio_session_t, bool> ids;
Andy Hung972bec12023-08-31 16:13:39 -07009592 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009593 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009594 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009595 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009596 if (ids.indexOfKey(sessionId) < 0) {
9597 ids.add(sessionId, true);
9598 }
9599 }
9600 return ids;
9601}
9602
Andy Hungee58e4a2023-07-07 13:47:37 -07009603AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009604{
Andy Hung972bec12023-08-31 16:13:39 -07009605 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009606 AudioStreamIn *input = mInput;
9607 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009608 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009609 return input;
9610}
9611
Andy Hungc5007f82023-08-29 14:26:09 -07009612// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hungee58e4a2023-07-07 13:47:37 -07009613sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009614{
9615 if (mInput == NULL) {
9616 return NULL;
9617 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009618 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009619}
9620
Andy Hungee58e4a2023-07-07 13:47:37 -07009621status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009622{
Eric Laurent81784c32012-11-19 14:55:58 -08009623 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009624 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009625 chain->setInBuffer(NULL);
9626 chain->setOutBuffer(NULL);
9627
9628 checkSuspendOnAddEffectChain_l(chain);
9629
Eric Laurent1b928682014-10-02 19:41:47 -07009630 // make sure enabled pre processing effects state is communicated to the HAL as we
9631 // just moved them to a new input stream.
9632 chain->syncHalEffectsState();
9633
Eric Laurent81784c32012-11-19 14:55:58 -08009634 mEffectChains.add(chain);
9635
9636 return NO_ERROR;
9637}
9638
Andy Hungee58e4a2023-07-07 13:47:37 -07009639size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009640{
9641 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009642
9643 for (size_t i = 0; i < mEffectChains.size(); i++) {
9644 if (chain == mEffectChains[i]) {
9645 mEffectChains.removeAt(i);
9646 break;
9647 }
Eric Laurent81784c32012-11-19 14:55:58 -08009648 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009649 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009650}
9651
Andy Hungee58e4a2023-07-07 13:47:37 -07009652status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009653 audio_patch_handle_t *handle)
9654{
9655 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009656
9657 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009658 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009659 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009660 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009661 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009662 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009663 }
9664
Eric Laurentd8365c52017-07-16 15:27:05 -07009665 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009666
9667 // store new source and send to effects
9668 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9669 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009670 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009671 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009672 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009673 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009674
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009675 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009676 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9677 status = hwDevice->createAudioPatch(patch->num_sources,
9678 patch->sources,
9679 patch->num_sinks,
9680 patch->sinks,
9681 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009682 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009683 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9684 patch->sinks[0].ext.mix.usecase.source,
9685 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009686 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009687 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009688
jiabinc52b1ff2019-10-31 17:20:42 -07009689 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009690 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009691 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009692 }
Eric Laurent296fb132015-05-01 11:38:42 -07009693
Andy Hungc2b11cb2020-04-22 09:04:01 -07009694 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009695 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009696 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009697 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009698 // also dispatch to active AudioRecords
9699 for (const auto &track : mActiveTracks) {
9700 track->logEndInterval();
9701 track->logBeginInterval(pathSourcesAsString);
9702 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009703 // Force meteadata update after a route change
9704 mActiveTracks.setHasChanged();
9705
Eric Laurent1c333e22014-05-20 10:48:17 -07009706 return status;
9707}
9708
Andy Hungee58e4a2023-07-07 13:47:37 -07009709status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009710{
9711 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009712
jiabinc52b1ff2019-10-31 17:20:42 -07009713 mPatch = audio_patch{};
9714 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009715
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009716 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009717 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9718 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009719 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009720 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009721 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009722 // Force meteadata update after a route change
9723 mActiveTracks.setHasChanged();
9724
Eric Laurent1c333e22014-05-20 10:48:17 -07009725 return status;
9726}
9727
Andy Hungee58e4a2023-07-07 13:47:37 -07009728void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009729{
Andy Hung972bec12023-08-31 16:13:39 -07009730 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009731 mOutDevices = outDevices;
9732 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9733 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009734 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009735 }
9736}
9737
Andy Hungee58e4a2023-07-07 13:47:37 -07009738int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009739{
9740 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009741 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009742 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009743 int32_t oldestFront = mRsmpInRear;
9744 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009745 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009746 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009747 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009748 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009749 if (filled > maxFilled) {
9750 oldestFront = front;
9751 maxFilled = filled;
9752 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009753 }
Andy Hung920f6572022-10-06 12:09:49 -07009754 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009755 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9756 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009757 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009758}
9759
Andy Hungee58e4a2023-07-07 13:47:37 -07009760void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009761{
9762 if (offset == 0) {
9763 return;
9764 }
9765 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung8d31fd22023-06-26 19:20:57 -07009766 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009767 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung8d31fd22023-06-26 19:20:57 -07009768 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009769 }
9770}
9771
Andy Hungee58e4a2023-07-07 13:47:37 -07009772void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009773{
9774 // This is the formula for calculating the temporary buffer size.
9775 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9776 // 1 full output buffer, regardless of the alignment of the available input.
9777 // The value is somewhat arbitrary, and could probably be even larger.
9778 // A larger value should allow more old data to be read after a track calls start(),
9779 // without increasing latency.
9780 //
9781 // Note this is independent of the maximum downsampling ratio permitted for capture.
9782 size_t minRsmpInFrames = mFrameCount * 7;
9783
9784 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9785 // capture history available to another client using the same session ID:
9786 // dimension the resampler input buffer accordingly.
9787
9788 // Get oldest client read position: getOldestFront_l() must be called before altering
9789 // mRsmpInRear, or mRsmpInFrames
9790 int32_t previousFront = getOldestFront_l();
9791 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9792 int32_t previousRear = mRsmpInRear;
9793 mRsmpInRear = 0;
9794
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009795 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hungee58e4a2023-07-07 13:47:37 -07009796 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009797 "resizeInputBuffer_l() called with invalid max shared history %d",
9798 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009799 if (maxSharedAudioHistoryMs != 0) {
9800 // resizeInputBuffer_l should never be called with a non zero shared history if the
9801 // buffer was not already allocated
9802 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9803 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9804 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9805 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009806 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009807 return;
9808 }
9809 mRsmpInFrames = rsmpInFrames;
9810 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009811 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009812 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9813 // initialized
9814 if (mRsmpInFrames < minRsmpInFrames) {
9815 mRsmpInFrames = minRsmpInFrames;
9816 }
9817 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9818
9819 // TODO optimize audio capture buffer sizes ...
9820 // Here we calculate the size of the sliding buffer used as a source
9821 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9822 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9823 // be better to have it derived from the pipe depth in the long term.
9824 // The current value is higher than necessary. However it should not add to latency.
9825
9826 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9827 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9828
9829 void *rsmpInBuffer;
9830 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9831 // if posix_memalign fails, will segv here.
9832 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9833
9834 // Copy audio history if any from old buffer before freeing it
9835 if (previousRear != 0) {
9836 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9837 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9838
9839 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9840 previousFront &= previousRsmpInFramesP2 - 1;
9841 size_t part1 = previousRsmpInFramesP2 - previousFront;
9842 if (part1 > (size_t) unread) {
9843 part1 = unread;
9844 }
9845 if (part1 != 0) {
9846 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9847 part1 * mFrameSize);
9848 mRsmpInRear = part1;
9849 part1 = unread - part1;
9850 if (part1 != 0) {
9851 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9852 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9853 mRsmpInRear += part1;
9854 }
9855 }
9856 // Update front for all clients according to new rear
9857 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9858 } else {
9859 mRsmpInRear = 0;
9860 }
9861 free(mRsmpInBuffer);
9862 mRsmpInBuffer = rsmpInBuffer;
9863}
9864
Andy Hungee58e4a2023-07-07 13:47:37 -07009865void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009866{
Andy Hung972bec12023-08-31 16:13:39 -07009867 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009868 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009869 if (record->getSource()) {
9870 mSource = record->getSource();
9871 }
Eric Laurent83b88082014-06-20 18:31:16 -07009872}
9873
Andy Hungee58e4a2023-07-07 13:47:37 -07009874void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009875{
Andy Hung972bec12023-08-31 16:13:39 -07009876 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009877 if (mSource == record->getSource()) {
9878 mSource = mInput;
9879 }
Eric Laurent83b88082014-06-20 18:31:16 -07009880 destroyTrack_l(record);
9881}
9882
Andy Hungee58e4a2023-07-07 13:47:37 -07009883void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009884{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009885 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009886 config->role = AUDIO_PORT_ROLE_SINK;
9887 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9888 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009889 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9890 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9891 config->flags.input = mInput->flags;
9892 }
Eric Laurent83b88082014-06-20 18:31:16 -07009893}
Eric Laurent1c333e22014-05-20 10:48:17 -07009894
Eric Laurent6acd1d42017-01-04 14:23:29 -08009895// ----------------------------------------------------------------------------
9896// Mmap
9897// ----------------------------------------------------------------------------
9898
Andy Hung7aa7d102023-07-07 15:58:48 -07009899// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9900// MmapPlaybackThread or MmapCaptureThread instance.
9901class MmapThreadHandle : public MmapStreamInterface {
9902public:
9903 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9904 ~MmapThreadHandle() override;
9905
9906 // MmapStreamInterface virtuals
9907 status_t createMmapBuffer(int32_t minSizeFrames,
9908 struct audio_mmap_buffer_info* info) final;
9909 status_t getMmapPosition(struct audio_mmap_position* position) final;
9910 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9911 status_t start(const AudioClient& client,
9912 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9913 status_t stop(audio_port_handle_t handle) final;
9914 status_t standby() final;
9915 status_t reportData(const void* buffer, size_t frameCount) final;
9916private:
9917 const sp<IAfMmapThread> mThread;
9918};
9919
9920/* static */
9921sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9922 const sp<IAfMmapThread>& mmapThread) {
9923 return sp<MmapThreadHandle>::make(mmapThread);
9924}
9925
9926MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009927 : mThread(thread)
9928{
Phil Burk9fabbf82017-08-03 12:02:00 -07009929 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930}
9931
Andy Hung7aa7d102023-07-07 15:58:48 -07009932// MmapStreamInterface could be directly implemented by MmapThread excepting this
9933// special handling on adapter dtor.
9934MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009935{
Phil Burk9fabbf82017-08-03 12:02:00 -07009936 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009937}
9938
Andy Hung7aa7d102023-07-07 15:58:48 -07009939status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009940 struct audio_mmap_buffer_info *info)
9941{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009942 return mThread->createMmapBuffer(minSizeFrames, info);
9943}
9944
Andy Hung7aa7d102023-07-07 15:58:48 -07009945status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009947 return mThread->getMmapPosition(position);
9948}
9949
Andy Hung7aa7d102023-07-07 15:58:48 -07009950status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009951 int64_t *timeNanos) {
9952 return mThread->getExternalPosition(position, timeNanos);
9953}
9954
Andy Hung7aa7d102023-07-07 15:58:48 -07009955status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009956 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957{
jiabind1f1cb62020-03-24 11:57:57 -07009958 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009959}
9960
Andy Hung7aa7d102023-07-07 15:58:48 -07009961status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009962{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009963 return mThread->stop(handle);
9964}
9965
Andy Hung7aa7d102023-07-07 15:58:48 -07009966status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009967{
Eric Laurent18b57012017-02-13 16:23:52 -08009968 return mThread->standby();
9969}
9970
Andy Hung7aa7d102023-07-07 15:58:48 -07009971status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9972{
jiabinfc791ee2023-02-15 19:43:40 +00009973 return mThread->reportData(buffer, frameCount);
9974}
9975
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976
Andy Hungee58e4a2023-07-07 13:47:37 -07009977MmapThread::MmapThread(
Andy Hung583043b2023-07-17 17:05:00 -07009978 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung920f6572022-10-06 12:09:49 -07009979 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung583043b2023-07-17 17:05:00 -07009980 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009981 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009982 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009983 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009984 mActiveTracks(&this->mLocalLog),
9985 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9986 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009987{
Eric Laurent18b57012017-02-13 16:23:52 -08009988 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009989 readHalParameters_l();
9990}
9991
Andy Hungee58e4a2023-07-07 13:47:37 -07009992void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009993{
9994 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9995}
9996
Andy Hungee58e4a2023-07-07 13:47:37 -07009997void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009998{
Andy Hung8d31fd22023-06-26 19:20:57 -07009999 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -070010000 {
Andy Hung972bec12023-08-31 16:13:39 -070010001 audio_utils::lock_guard _l(mutex());
Andy Hung8d31fd22023-06-26 19:20:57 -070010002 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010003 activeTracks.add(t);
10004 }
10005 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010006 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010007 stop(t->portId());
10008 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010009 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010010 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010011 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010012 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010013 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010014 }
10015}
10016
10017
Andy Hungee58e4a2023-07-07 13:47:37 -070010018void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010019 audio_stream_type_t streamType __unused,
10020 audio_session_t sessionId,
10021 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010022 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010023 audio_port_handle_t portId)
10024{
10025 mAttr = *attr;
10026 mSessionId = sessionId;
10027 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010028 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010029 mPortId = portId;
10030}
10031
Andy Hungee58e4a2023-07-07 13:47:37 -070010032status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010033 struct audio_mmap_buffer_info *info)
10034{
10035 if (mHalStream == 0) {
10036 return NO_INIT;
10037 }
Eric Laurent18b57012017-02-13 16:23:52 -080010038 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010039 return mHalStream->createMmapBuffer(minSizeFrames, info);
10040}
10041
Andy Hungee58e4a2023-07-07 13:47:37 -070010042status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010043{
10044 if (mHalStream == 0) {
10045 return NO_INIT;
10046 }
10047 return mHalStream->getMmapPosition(position);
10048}
10049
Andy Hungee58e4a2023-07-07 13:47:37 -070010050status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010051{
Eric Laurentdda206a2022-07-08 17:28:35 +020010052 // The HAL must receive track metadata before starting the stream
10053 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010054 status_t ret = mHalStream->start();
10055 if (ret != NO_ERROR) {
10056 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10057 return ret;
10058 }
Andy Hungcf10d742020-04-28 15:38:24 -070010059 if (mStandby) {
10060 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010061 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010062 mStandby = false;
10063 }
Eric Laurent331679c2018-04-16 17:03:16 -070010064 return NO_ERROR;
10065}
10066
Andy Hungee58e4a2023-07-07 13:47:37 -070010067status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010068 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010069 audio_port_handle_t *handle)
10070{
Eric Laurenta54f1282017-07-01 19:39:32 -070010071 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010072 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010073 if (mHalStream == 0) {
10074 return NO_INIT;
10075 }
10076
10077 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010078
Eric Laurentdda206a2022-07-08 17:28:35 +020010079 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010080 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010081 acquireWakeLock();
10082 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010083 }
10084
10085 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10086
10087 audio_io_handle_t io = mId;
Andy Hung6cd79802023-07-19 16:56:19 -070010088 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010089 client.attributionSource);
10090
Eric Laurenta54f1282017-07-01 19:39:32 -070010091 if (isOutput()) {
10092 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10093 config.sample_rate = mSampleRate;
10094 config.channel_mask = mChannelMask;
10095 config.format = mFormat;
10096 audio_stream_type_t stream = streamType();
10097 audio_output_flags_t flags =
10098 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010099 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010100 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010101 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010102 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010103 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10104 mSessionId,
10105 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010106 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010107 &config,
10108 flags,
10109 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010110 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010111 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010112 &isSpatialized,
10113 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010114 ALOGD_IF(!secondaryOutputs.empty(),
10115 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010117 audio_config_base_t config;
10118 config.sample_rate = mSampleRate;
10119 config.channel_mask = mChannelMask;
10120 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010121 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010122 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010123 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010124 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010125 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010126 &config,
10127 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10128 &deviceId,
10129 &portId);
10130 }
10131 // APM should not chose a different input or output stream for the same set of attributes
10132 // and audo configuration
10133 if (ret != NO_ERROR || io != mId) {
10134 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10135 __FUNCTION__, ret, io, mId);
10136 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010137 }
10138
10139 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010140 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010141 } else {
jiabin09609032022-06-15 19:26:01 +000010142 {
10143 // Add the track record before starting input so that the silent status for the
10144 // client can be cached.
Andy Hung972bec12023-08-31 16:13:39 -070010145 audio_utils::lock_guard _l(mutex());
jiabin09609032022-06-15 19:26:01 +000010146 setClientSilencedState_l(portId, false /*silenced*/);
10147 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010148 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010149 }
10150
Andy Hung972bec12023-08-31 16:13:39 -070010151 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010152 // abort if start is rejected by audio policy manager
10153 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010154 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010155 if (!mActiveTracks.isEmpty()) {
Andy Hungc5007f82023-08-29 14:26:09 -070010156 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010157 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010158 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010159 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010160 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010161 }
Andy Hungc5007f82023-08-29 14:26:09 -070010162 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010163 } else {
10164 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010165 }
jiabin09609032022-06-15 19:26:01 +000010166 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010167 return PERMISSION_DENIED;
10168 }
10169
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010170 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung8d31fd22023-06-26 19:20:57 -070010171 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10172 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010173 mChannelMask, mSessionId, isOutput(),
10174 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010175 IPCThreadState::self()->getCallingPid(), portId);
jiabin09609032022-06-15 19:26:01 +000010176 if (!isOutput()) {
10177 track->setSilenced_l(isClientSilenced_l(portId));
10178 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010179
Eric Laurent4eb58f12018-12-07 16:41:02 -080010180 if (isOutput()) {
10181 // force volume update when a new track is added
10182 mHalVolFloat = -1.0f;
10183 } else if (!track->isSilenced_l()) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010184 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung920f6572022-10-06 12:09:49 -070010185 if (t->isSilenced_l()
10186 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010187 t->invalidate();
Andy Hung920f6572022-10-06 12:09:49 -070010188 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010189 }
10190 }
10191
Eric Laurent6acd1d42017-01-04 14:23:29 -080010192 mActiveTracks.add(track);
Andy Hung116bc262023-06-20 18:56:17 -070010193 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010194 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010195 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196 chain->incTrackCnt();
10197 chain->incActiveTrackCnt();
10198 }
10199
Andy Hungc2b11cb2020-04-22 09:04:01 -070010200 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010201 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010202
10203 if (mActiveTracks.size() == 1) {
10204 ret = exitStandby_l();
10205 }
10206
Eric Laurent6acd1d42017-01-04 14:23:29 -080010207 broadcast_l();
10208
Eric Laurentdda206a2022-07-08 17:28:35 +020010209 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010210
Eric Laurentdda206a2022-07-08 17:28:35 +020010211 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010212}
10213
Andy Hungee58e4a2023-07-07 13:47:37 -070010214status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010215{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010216 ALOGV("%s handle %d", __FUNCTION__, handle);
10217
10218 if (mHalStream == 0) {
10219 return NO_INIT;
10220 }
10221
Eric Laurenta54f1282017-07-01 19:39:32 -070010222 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010223 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010224 return NO_ERROR;
10225 }
10226
Andy Hung972bec12023-08-31 16:13:39 -070010227 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070010228
Andy Hung8d31fd22023-06-26 19:20:57 -070010229 sp<IAfMmapTrack> track;
10230 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231 if (handle == t->portId()) {
10232 track = t;
10233 break;
10234 }
10235 }
10236 if (track == 0) {
10237 return BAD_VALUE;
10238 }
10239
10240 mActiveTracks.remove(track);
jiabin09609032022-06-15 19:26:01 +000010241 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010242
Andy Hungc5007f82023-08-29 14:26:09 -070010243 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010244 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010245 AudioSystem::stopOutput(track->portId());
10246 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010247 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010248 AudioSystem::stopInput(track->portId());
10249 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010250 }
Andy Hungc5007f82023-08-29 14:26:09 -070010251 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010252
Andy Hung116bc262023-06-20 18:56:17 -070010253 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010254 if (chain != 0) {
10255 chain->decActiveTrackCnt();
10256 chain->decTrackCnt();
10257 }
10258
Eric Laurentdda206a2022-07-08 17:28:35 +020010259 if (mActiveTracks.isEmpty()) {
10260 mHalStream->stop();
10261 }
10262
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263 broadcast_l();
10264
Eric Laurent6acd1d42017-01-04 14:23:29 -080010265 return NO_ERROR;
10266}
10267
Andy Hungee58e4a2023-07-07 13:47:37 -070010268status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010269{
10270 ALOGV("%s", __FUNCTION__);
10271
10272 if (mHalStream == 0) {
10273 return NO_INIT;
10274 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010275 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010276 return INVALID_OPERATION;
10277 }
10278 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010279 if (!mStandby) {
10280 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010281 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010282 mStandby = true;
10283 }
Eric Laurent18b57012017-02-13 16:23:52 -080010284 releaseWakeLock();
10285 return NO_ERROR;
10286}
10287
Andy Hungee58e4a2023-07-07 13:47:37 -070010288status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010289 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10290 return INVALID_OPERATION;
10291}
10292
Andy Hungee58e4a2023-07-07 13:47:37 -070010293void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010294{
10295 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10296 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10297 mFormat = mHALFormat;
10298 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10299 result = mHalStream->getFrameSize(&mFrameSize);
10300 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010301 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10302 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010303 result = mHalStream->getBufferSize(&mBufferSize);
10304 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10305 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010306
Andy Hungcf10d742020-04-28 15:38:24 -070010307 // TODO: make a readHalParameters call?
10308 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010309 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung25a80ac2023-07-19 12:47:35 -070010310 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010311 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10312 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10313 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10314 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10315 /*
10316 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10317 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10318 (int32_t)mHapticChannelMask)
10319 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10320 (int32_t)mHapticChannelCount)
10321 */
10322 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung25a80ac2023-07-19 12:47:35 -070010323 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010324 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10325 (int32_t)mFrameCount) // sic - added HAL
10326 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010327}
10328
Andy Hungee58e4a2023-07-07 13:47:37 -070010329bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010330{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010331 checkSilentMode_l();
10332
10333 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10334
10335 while (!exitPending())
10336 {
Andy Hung116bc262023-06-20 18:56:17 -070010337 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010338
Andy Hung13850be2019-03-14 11:33:09 -070010339 { // under Thread lock
Andy Hungc5007f82023-08-29 14:26:09 -070010340 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010341
Eric Laurent6acd1d42017-01-04 14:23:29 -080010342 if (mSignalPending) {
10343 // A signal was raised while we were unlocked
10344 mSignalPending = false;
10345 } else {
10346 if (mConfigEvents.isEmpty()) {
10347 // we're about to wait, flush the binder command buffer
10348 IPCThreadState::self()->flushCommands();
10349
10350 if (exitPending()) {
10351 break;
10352 }
10353
Eric Laurent6acd1d42017-01-04 14:23:29 -080010354 // wait until we have something to do...
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010355 ALOGV("%s going to sleep", myName.c_str());
Andy Hungc5007f82023-08-29 14:26:09 -070010356 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010357 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010358
10359 checkSilentMode_l();
10360
10361 continue;
10362 }
10363 }
10364
10365 processConfigEvents_l();
10366
10367 processVolume_l();
10368
10369 checkInvalidTracks_l();
10370
10371 mActiveTracks.updatePowerState(this);
10372
Kevin Rocard069c2712018-03-29 19:09:14 -070010373 updateMetadata_l();
10374
Eric Laurent6acd1d42017-01-04 14:23:29 -080010375 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010376 } // release Thread lock
10377
Eric Laurent6acd1d42017-01-04 14:23:29 -080010378 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010379 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010380 }
Andy Hung13850be2019-03-14 11:33:09 -070010381
10382 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010383 unlockEffectChains(effectChains);
10384 // Effect chains will be actually deleted here if they were removed from
10385 // mEffectChains list during mixing or effects processing
10386 }
10387
10388 threadLoop_exit();
10389
10390 if (!mStandby) {
10391 threadLoop_standby();
10392 mStandby = true;
10393 }
10394
Eric Laurent6acd1d42017-01-04 14:23:29 -080010395 ALOGV("Thread %p type %d exiting", this, mType);
10396 return false;
10397}
10398
Andy Hungc5007f82023-08-29 14:26:09 -070010399// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070010400bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010401 status_t& status)
10402{
10403 AudioParameter param = AudioParameter(keyValuePair);
10404 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010405 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010406 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010407 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010408 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010409 if (sendToHal) {
10410 status = mHalStream->setParameters(keyValuePair);
10411 } else {
10412 status = NO_ERROR;
10413 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414
10415 return false;
10416}
10417
Andy Hungee58e4a2023-07-07 13:47:37 -070010418String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010419{
Andy Hung972bec12023-08-31 16:13:39 -070010420 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010421 String8 out_s8;
10422 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10423 return out_s8;
10424 }
Andy Hung920f6572022-10-06 12:09:49 -070010425 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010426}
10427
Andy Hungee58e4a2023-07-07 13:47:37 -070010428void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010429 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010430 sp<AudioIoDescriptor> desc;
10431 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010432 switch (event) {
10433 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010434 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010435 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010436 isInput = true;
10437 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010438 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010439 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010440 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010441 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10442 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010443 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010444 case AUDIO_INPUT_CLOSED:
10445 case AUDIO_OUTPUT_CLOSED:
10446 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010447 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010448 break;
10449 }
Andy Hung583043b2023-07-17 17:05:00 -070010450 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451}
10452
Andy Hungee58e4a2023-07-07 13:47:37 -070010453status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 audio_patch_handle_t *handle)
Andy Hungc5007f82023-08-29 14:26:09 -070010455NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010456{
10457 status_t status = NO_ERROR;
10458
10459 // store new device and send to effects
10460 audio_devices_t type = AUDIO_DEVICE_NONE;
10461 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010462 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10463 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10464 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010465 if (isOutput()) {
10466 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010467 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10468 && !mAudioHwDev->supportsAudioPatches(),
10469 "Enumerated device type(%#x) must not be used "
10470 "as it does not support audio patches",
10471 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010472 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung920f6572022-10-06 12:09:49 -070010473 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10474 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010475 }
10476 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010477 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010478 } else {
10479 type = patch->sources[0].ext.device.type;
10480 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010481 numDevices = mPatch.num_sources;
10482 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010483 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010484 }
10485
10486 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010487 if (isOutput()) {
10488 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10489 } else {
10490 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10491 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010492 }
10493
jiabinc52b1ff2019-10-31 17:20:42 -070010494 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010495 // store new source and send to effects
10496 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10497 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10498 for (size_t i = 0; i < mEffectChains.size(); i++) {
10499 mEffectChains[i]->setAudioSource_l(mAudioSource);
10500 }
10501 }
10502 }
10503
10504 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010505 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10506 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010507 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010508 audio_port_config port;
10509 std::optional<audio_source_t> source;
10510 if (isOutput()) {
10511 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010512 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010513 port = patch->sources[0];
10514 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010515 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010516 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010517 *handle = AUDIO_PATCH_HANDLE_NONE;
10518 }
10519
jiabinc52b1ff2019-10-31 17:20:42 -070010520 if (numDevices == 0 || mDeviceId != deviceId) {
10521 if (isOutput()) {
10522 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10523 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010524 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010525 } else {
10526 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10527 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10528 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010529 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010530 if (mDeviceId != deviceId && callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010531 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010532 callback->onRoutingChanged(deviceId);
Andy Hungc5007f82023-08-29 14:26:09 -070010533 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534 }
jiabinc52b1ff2019-10-31 17:20:42 -070010535 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010536 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010537 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010538 // Force meteadata update after a route change
10539 mActiveTracks.setHasChanged();
10540
Eric Laurent6acd1d42017-01-04 14:23:29 -080010541 return status;
10542}
10543
Andy Hungee58e4a2023-07-07 13:47:37 -070010544status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010545{
10546 status_t status = NO_ERROR;
10547
jiabinc52b1ff2019-10-31 17:20:42 -070010548 mPatch = audio_patch{};
10549 mOutDeviceTypeAddrs.clear();
10550 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010551
10552 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10553 supportsAudioPatches : false;
10554
10555 if (supportsAudioPatches) {
10556 status = mHalDevice->releaseAudioPatch(handle);
10557 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010558 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010559 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010560 // Force meteadata update after a route change
10561 mActiveTracks.setHasChanged();
10562
Eric Laurent6acd1d42017-01-04 14:23:29 -080010563 return status;
10564}
10565
Andy Hungee58e4a2023-07-07 13:47:37 -070010566void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010567{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010568 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010569 if (isOutput()) {
10570 config->role = AUDIO_PORT_ROLE_SOURCE;
10571 config->ext.mix.hw_module = mAudioHwDev->handle();
10572 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10573 } else {
10574 config->role = AUDIO_PORT_ROLE_SINK;
10575 config->ext.mix.hw_module = mAudioHwDev->handle();
10576 config->ext.mix.usecase.source = mAudioSource;
10577 }
10578}
10579
Andy Hungee58e4a2023-07-07 13:47:37 -070010580status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010581{
10582 audio_session_t session = chain->sessionId();
10583
10584 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10585 // Attach all tracks with same session ID to this chain.
10586 // indicate all active tracks in the chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010587 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588 if (session == track->sessionId()) {
10589 chain->incTrackCnt();
10590 chain->incActiveTrackCnt();
10591 }
10592 }
10593
10594 chain->setThread(this);
10595 chain->setInBuffer(nullptr);
10596 chain->setOutBuffer(nullptr);
10597 chain->syncHalEffectsState();
10598
10599 mEffectChains.add(chain);
10600 checkSuspendOnAddEffectChain_l(chain);
10601 return NO_ERROR;
10602}
10603
Andy Hungee58e4a2023-07-07 13:47:37 -070010604size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010605{
10606 audio_session_t session = chain->sessionId();
10607
10608 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10609
10610 for (size_t i = 0; i < mEffectChains.size(); i++) {
10611 if (chain == mEffectChains[i]) {
10612 mEffectChains.removeAt(i);
10613 // detach all active tracks from the chain
10614 // detach all tracks with same session ID from this chain
Andy Hung8d31fd22023-06-26 19:20:57 -070010615 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010616 if (session == track->sessionId()) {
10617 chain->decActiveTrackCnt();
10618 chain->decTrackCnt();
10619 }
10620 }
10621 break;
10622 }
10623 }
10624 return mEffectChains.size();
10625}
10626
Andy Hungee58e4a2023-07-07 13:47:37 -070010627void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010628{
10629 mHalStream->standby();
10630}
10631
Andy Hungee58e4a2023-07-07 13:47:37 -070010632void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010633{
Phil Burk7dce7282017-09-27 13:51:41 -070010634 // Do not call callback->onTearDown() because it is redundant for thread exit
10635 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010636}
10637
Andy Hungee58e4a2023-07-07 13:47:37 -070010638status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010639{
10640 return BAD_VALUE;
10641}
10642
Andy Hungee58e4a2023-07-07 13:47:37 -070010643bool MmapThread::isValidSyncEvent(
10644 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010645{
10646 return false;
10647}
10648
Andy Hungee58e4a2023-07-07 13:47:37 -070010649status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010650 const effect_descriptor_t *desc, audio_session_t sessionId)
10651{
10652 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010653 if (audio_is_global_session(sessionId)) {
10654 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010655 desc->name, mThreadName);
10656 return BAD_VALUE;
10657 }
10658
10659 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10660 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10661 desc->name);
10662 return BAD_VALUE;
10663 }
10664 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010665 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10666 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010667 return BAD_VALUE;
10668 }
10669
10670 // Only allow effects without processing load or latency
10671 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10672 return BAD_VALUE;
10673 }
10674
Andy Hung116bc262023-06-20 18:56:17 -070010675 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010676 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10677 return BAD_VALUE;
10678 }
10679
Eric Laurent6acd1d42017-01-04 14:23:29 -080010680 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010681}
10682
Andy Hungee58e4a2023-07-07 13:47:37 -070010683void MmapThread::checkInvalidTracks_l()
Andy Hungc5007f82023-08-29 14:26:09 -070010684NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010685{
Eric Laurent039c24a2022-10-07 14:01:59 +020010686 sp<MmapStreamCallback> callback;
Andy Hung8d31fd22023-06-26 19:20:57 -070010687 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010688 if (track->isInvalid()) {
Eric Laurent039c24a2022-10-07 14:01:59 +020010689 callback = mCallback.promote();
10690 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10691 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
10692 mNoCallbackWarningCount++;
10693 }
10694 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010695 }
10696 }
Eric Laurent039c24a2022-10-07 14:01:59 +020010697 if (callback != 0) {
Andy Hungc5007f82023-08-29 14:26:09 -070010698 mutex().unlock();
Eric Laurent039c24a2022-10-07 14:01:59 +020010699 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hungc5007f82023-08-29 14:26:09 -070010700 mutex().lock();
jiabindfa32482022-10-06 19:45:50 +000010701 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010702}
10703
Andy Hungee58e4a2023-07-07 13:47:37 -070010704void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010705{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010706 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10707 mAttr.content_type, mAttr.usage, mAttr.source);
10708 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010709 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010710 dprintf(fd, " No active clients\n");
10711 }
10712}
10713
Andy Hungee58e4a2023-07-07 13:47:37 -070010714void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010715{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010716 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010717 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010718 dprintf(fd, " %zu Tracks\n", numtracks);
10719 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010720 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010721 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010722 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010723 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010724 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010725 result.append(prefix);
10726 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010727 }
10728 } else {
10729 dprintf(fd, "\n");
10730 }
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +000010731 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010732}
10733
Andy Hungee58e4a2023-07-07 13:47:37 -070010734/* static */
10735sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070010736 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070010737 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070010738 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070010739}
10740
10741MmapPlaybackThread::MmapPlaybackThread(
Andy Hung583043b2023-07-17 17:05:00 -070010742 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010743 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070010744 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010745 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010746 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010747{
10748 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10749 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung583043b2023-07-17 17:05:00 -070010750 mMasterVolume = afThreadCallback->masterVolume_l();
10751 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010752
10753 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10754 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10755 mStreamTypes[stream].volume = 0.0f;
Andy Hung583043b2023-07-17 17:05:00 -070010756 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010757 }
10758 // Audio patch and call assistant volume are always max
10759 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10760 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10761 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10762 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10763
Eric Laurent6acd1d42017-01-04 14:23:29 -080010764 if (mAudioHwDev) {
10765 if (mAudioHwDev->canSetMasterVolume()) {
10766 mMasterVolume = 1.0;
10767 }
10768
10769 if (mAudioHwDev->canSetMasterMute()) {
10770 mMasterMute = false;
10771 }
10772 }
10773}
10774
Andy Hungee58e4a2023-07-07 13:47:37 -070010775void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010776 audio_stream_type_t streamType,
10777 audio_session_t sessionId,
10778 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010779 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010780 audio_port_handle_t portId)
10781{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010782 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010783 mStreamType = streamType;
10784}
10785
Andy Hungee58e4a2023-07-07 13:47:37 -070010786AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010787{
Andy Hung972bec12023-08-31 16:13:39 -070010788 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010789 AudioStreamOut *output = mOutput;
10790 mOutput = NULL;
10791 return output;
10792}
10793
Andy Hungee58e4a2023-07-07 13:47:37 -070010794void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795{
Andy Hung972bec12023-08-31 16:13:39 -070010796 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010797 // Don't apply master volume in SW if our HAL can do it for us.
10798 if (mAudioHwDev &&
10799 mAudioHwDev->canSetMasterVolume()) {
10800 mMasterVolume = 1.0;
10801 } else {
10802 mMasterVolume = value;
10803 }
10804}
10805
Andy Hungee58e4a2023-07-07 13:47:37 -070010806void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010807{
Andy Hung972bec12023-08-31 16:13:39 -070010808 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010809 // Don't apply master mute in SW if our HAL can do it for us.
10810 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10811 mMasterMute = false;
10812 } else {
10813 mMasterMute = muted;
10814 }
10815}
10816
Andy Hungee58e4a2023-07-07 13:47:37 -070010817void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010818{
Andy Hung972bec12023-08-31 16:13:39 -070010819 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010820 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010821 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010822 broadcast_l();
10823 }
10824}
10825
Andy Hungee58e4a2023-07-07 13:47:37 -070010826float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010827{
Andy Hung972bec12023-08-31 16:13:39 -070010828 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010829 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010830}
10831
Andy Hungee58e4a2023-07-07 13:47:37 -070010832void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010833{
Andy Hung972bec12023-08-31 16:13:39 -070010834 audio_utils::lock_guard _l(mutex());
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010835 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010836 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837 broadcast_l();
10838 }
10839}
10840
Andy Hungee58e4a2023-07-07 13:47:37 -070010841void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010842{
Andy Hung972bec12023-08-31 16:13:39 -070010843 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010844 if (streamType == mStreamType) {
Andy Hung8d31fd22023-06-26 19:20:57 -070010845 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010846 track->invalidate();
10847 }
10848 broadcast_l();
10849 }
10850}
10851
Andy Hungee58e4a2023-07-07 13:47:37 -070010852void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010853{
Andy Hung972bec12023-08-31 16:13:39 -070010854 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010855 bool trackMatch = false;
Andy Hung8d31fd22023-06-26 19:20:57 -070010856 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010857 if (portIds.find(track->portId()) != portIds.end()) {
10858 track->invalidate();
10859 trackMatch = true;
10860 portIds.erase(track->portId());
10861 }
10862 if (portIds.empty()) {
10863 break;
10864 }
10865 }
10866 if (trackMatch) {
10867 broadcast_l();
10868 }
10869}
10870
Andy Hungee58e4a2023-07-07 13:47:37 -070010871void MmapPlaybackThread::processVolume_l()
Andy Hung920f6572022-10-06 12:09:49 -070010872NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010873{
10874 float volume;
10875
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010876 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010877 volume = 0;
10878 } else {
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010879 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010880 }
10881
10882 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010883 // Convert volumes from float to 8.24
10884 uint32_t vol = (uint32_t)(volume * (1 << 24));
10885
10886 // Delegate volume control to effect in track effect chain if needed
10887 // only one effect chain can be present on DirectOutputThread, so if
10888 // there is one, the track is connected to it
10889 if (!mEffectChains.isEmpty()) {
10890 mEffectChains[0]->setVolume_l(&vol, &vol);
10891 volume = (float)vol / (1 << 24);
10892 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010893 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010894 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10895 mHalVolFloat = volume; // HW volume control worked, so update value.
10896 mNoCallbackWarningCount = 0;
10897 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010898 sp<MmapStreamCallback> callback = mCallback.promote();
10899 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010900 mHalVolFloat = volume; // SW volume control worked, so update value.
10901 mNoCallbackWarningCount = 0;
Andy Hungc5007f82023-08-29 14:26:09 -070010902 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010903 callback->onVolumeChanged(volume);
Andy Hungc5007f82023-08-29 14:26:09 -070010904 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010905 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010906 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10907 ALOGW("Could not set MMAP stream volume: no volume callback!");
10908 mNoCallbackWarningCount++;
10909 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010910 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010911 }
Andy Hung8d31fd22023-06-26 19:20:57 -070010912 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010913 track->setMetadataHasChanged();
Andy Hung583043b2023-07-17 17:05:00 -070010914 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010915 /*muteState=*/{mMasterMute,
Eric Laurent1f9b5e62023-07-03 18:14:07 +020010916 streamVolume_l() == 0.f,
10917 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010918 // TODO(b/241533526): adjust logic to include mute from AppOps
10919 false /*muteFromPlaybackRestricted*/,
10920 false /*muteFromClientVolume*/,
10921 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010922 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010923 }
10924}
10925
Andy Hungee58e4a2023-07-07 13:47:37 -070010926ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010927{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010928 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010929 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010930 }
10931 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070010932 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010933 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010934 playback_track_metadata_v7_t trackMetadata;
10935 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010936 .usage = track->attributes().usage,
10937 .content_type = track->attributes().content_type,
10938 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010939 };
10940 trackMetadata.channel_mask = track->channelMask(),
10941 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10942 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010943 }
10944 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010945
10946 MetadataUpdate change;
10947 change.playbackMetadataUpdate = metadata.tracks;
10948 return change;
10949};
Kevin Rocard069c2712018-03-29 19:09:14 -070010950
Andy Hungee58e4a2023-07-07 13:47:37 -070010951void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010952{
10953 if (!mMasterMute) {
10954 char value[PROPERTY_VALUE_MAX];
10955 if (property_get("ro.audio.silent", value, "0") > 0) {
10956 char *endptr;
10957 unsigned long ul = strtoul(value, &endptr, 0);
10958 if (*endptr == '\0' && ul != 0) {
10959 ALOGD("Silence is golden");
10960 // The setprop command will not allow a property to be changed after
10961 // the first time it is set, so we don't have to worry about un-muting.
10962 setMasterMute_l(true);
10963 }
10964 }
10965 }
10966}
10967
Andy Hungee58e4a2023-07-07 13:47:37 -070010968void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010969{
10970 MmapThread::toAudioPortConfig(config);
10971 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10972 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10973 config->flags.output = mOutput->flags;
10974 }
10975}
10976
Andy Hungee58e4a2023-07-07 13:47:37 -070010977status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung440901d2023-06-29 21:19:25 -070010978 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010979{
10980 if (mOutput == nullptr) {
10981 return NO_INIT;
10982 }
10983 struct timespec timestamp;
10984 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10985 if (status == NO_ERROR) {
10986 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10987 }
10988 return status;
10989}
10990
Andy Hungee58e4a2023-07-07 13:47:37 -070010991status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010010992 // Send to MelProcessor for sound dose measurement.
10993 auto processor = mMelProcessor.load();
10994 if (processor) {
10995 processor->process(buffer, frameCount * mFrameSize);
10996 }
10997
jiabinfc791ee2023-02-15 19:43:40 +000010998 return NO_ERROR;
10999}
11000
Andy Hungc5007f82023-08-29 14:26:09 -070011001// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011002void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011003 const sp<audio_utils::MelProcessor>& processor)
11004{
11005 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011006 mMelProcessor.store(processor);
11007 if (processor) {
11008 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011009 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011010
11011 // no need to update output format for MMapPlaybackThread since it is
11012 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011013}
11014
Andy Hungc5007f82023-08-29 14:26:09 -070011015// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hungee58e4a2023-07-07 13:47:37 -070011016void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011017{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011018 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11019 auto melProcessor = mMelProcessor.load();
11020 if (melProcessor != nullptr) {
11021 melProcessor->pause();
11022 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011023}
11024
Andy Hungee58e4a2023-07-07 13:47:37 -070011025void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011026{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011027 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011028
Glenn Kastend3bb6452016-12-05 18:14:37 -080011029 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent1f9b5e62023-07-03 18:14:07 +020011030 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011031 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11032}
11033
Andy Hungee58e4a2023-07-07 13:47:37 -070011034/* static */
11035sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung583043b2023-07-17 17:05:00 -070011036 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hungee58e4a2023-07-07 13:47:37 -070011037 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011038 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011039}
11040
11041MmapCaptureThread::MmapCaptureThread(
Andy Hung583043b2023-07-17 17:05:00 -070011042 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011043 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011044 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045 mInput(input)
11046{
11047 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11048 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11049}
11050
Andy Hungee58e4a2023-07-07 13:47:37 -070011051status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011052{
Phil Burkf054fc32018-12-06 09:45:59 -080011053 {
11054 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011055 if (mInput != nullptr && mInput->stream != nullptr) {
11056 mInput->stream->setGain(1.0f);
11057 }
11058 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011059 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011060}
11061
Andy Hungee58e4a2023-07-07 13:47:37 -070011062AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011063{
Andy Hung972bec12023-08-31 16:13:39 -070011064 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011065 AudioStreamIn *input = mInput;
11066 mInput = NULL;
11067 return input;
11068}
Kevin Rocard069c2712018-03-29 19:09:14 -070011069
Andy Hungee58e4a2023-07-07 13:47:37 -070011070void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011071{
11072 bool changed = false;
11073 bool silenced = false;
11074
11075 sp<MmapStreamCallback> callback = mCallback.promote();
11076 if (callback == 0) {
11077 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11078 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11079 mNoCallbackWarningCount++;
11080 }
11081 }
11082
11083 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11084 // track is silenced and unmute otherwise
11085 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11086 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11087 changed = true;
11088 silenced = mActiveTracks[i]->isSilenced_l();
11089 }
11090 }
11091
11092 if (changed) {
11093 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11094 }
11095}
11096
Andy Hungee58e4a2023-07-07 13:47:37 -070011097ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011098{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011099 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011100 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011101 }
11102 StreamInHalInterface::SinkMetadata metadata;
Andy Hung8d31fd22023-06-26 19:20:57 -070011103 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011104 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011105 record_track_metadata_v7_t trackMetadata;
11106 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011107 .source = track->attributes().source,
11108 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011109 };
11110 trackMetadata.channel_mask = track->channelMask(),
11111 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11112 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011113 }
11114 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011115 MetadataUpdate change;
11116 change.recordMetadataUpdate = metadata.tracks;
11117 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011118}
11119
Andy Hungee58e4a2023-07-07 13:47:37 -070011120void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011121{
Andy Hung972bec12023-08-31 16:13:39 -070011122 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011123 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011124 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011125 mActiveTracks[i]->setSilenced_l(silenced);
11126 broadcast_l();
11127 }
11128 }
jiabin09609032022-06-15 19:26:01 +000011129 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011130}
11131
Andy Hungee58e4a2023-07-07 13:47:37 -070011132void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011133{
11134 MmapThread::toAudioPortConfig(config);
11135 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11136 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11137 config->flags.input = mInput->flags;
11138 }
11139}
11140
Andy Hungee58e4a2023-07-07 13:47:37 -070011141status_t MmapCaptureThread::getExternalPosition(
Andy Hung440901d2023-06-29 21:19:25 -070011142 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011143{
11144 if (mInput == nullptr) {
11145 return NO_INIT;
11146 }
11147 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11148}
11149
jiabinc658e452022-10-21 20:52:21 +000011150// ----------------------------------------------------------------------------
11151
Andy Hungee58e4a2023-07-07 13:47:37 -070011152/* static */
11153sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung583043b2023-07-17 17:05:00 -070011154 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hungee58e4a2023-07-07 13:47:37 -070011155 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung583043b2023-07-17 17:05:00 -070011156 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hungee58e4a2023-07-07 13:47:37 -070011157}
11158
Andy Hung583043b2023-07-17 17:05:00 -070011159BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011160 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung583043b2023-07-17 17:05:00 -070011161 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011162
Andy Hungee58e4a2023-07-07 13:47:37 -070011163PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung8d31fd22023-06-26 19:20:57 -070011164 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011165 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11166 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011167 float volumeLeft = 1.0f;
11168 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011169 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11170 const int trackId = mActiveTracks[0]->id();
11171 mAudioMixer->setParameter(
11172 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11173 mAudioMixer->setParameter(
11174 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11175 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011176 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011177 mIsBitPerfect = true;
11178 } else {
11179 mIsBitPerfect = false;
11180 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11181 // active.
11182 for (const auto& track : mActiveTracks) {
11183 const int trackId = track->id();
11184 mAudioMixer->setParameter(
11185 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11186 }
11187 }
jiabin76d94692022-12-15 21:51:21 +000011188 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11189 mVolumeLeft = volumeLeft;
11190 mVolumeRight = volumeRight;
11191 setVolumeForOutput_l(volumeLeft, volumeRight);
11192 }
jiabinc658e452022-10-21 20:52:21 +000011193 return result;
11194}
11195
Andy Hungee58e4a2023-07-07 13:47:37 -070011196void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011197 MixerThread::threadLoop_mix();
11198 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11199}
11200
Glenn Kasten63238ef2015-03-02 15:50:29 -080011201} // namespace android