blob: c6b498305b50f8b5efdd75e991af60f7af708a15 [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 Hung4d693a32023-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 Hung4d693a32023-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 Hung4d693a32023-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 Hung4d693a32023-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 Hung4d693a32023-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 Hung4d693a32023-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 Hung4d693a32023-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 Hung71742ab2023-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 Hung4d693a32023-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 Lindahl9e661ad2022-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 Hung4d693a32023-07-19 12:47:35 -0700246static const nsecs_t kDefaultStandbyTimeInNsecs = seconds(3);
Andy Hung18bef9b2023-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 Hungf8ab4692023-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 Hung4d693a32023-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 Naganova77d5552022-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 Hung71ba4b32022-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 Wasilczyk8f36f6e2023-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 Hung71742ab2023-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 Hung2cbc2722023-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 Hung2cbc2722023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung87e82412023-08-29 14:26:09 -0700688 audio_utils::lock_guard lock(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -0800689 requestExit();
Andy Hung87e82412023-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 Hung71742ab2023-07-07 13:47:37 -0700697status_t ThreadBase::setParameters(const String8& keyValuePairs)
Eric Laurent81784c32012-11-19 14:55:58 -0800698{
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +0000699 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.c_str());
Andy Hungf79092d2023-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 Hung71742ab2023-07-07 13:47:37 -0700707status_t ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
Andy Hung71ba4b32022-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 Hung87e82412023-08-29 14:26:09 -0700719 mWaitWorkCV.notify_one();
720 mutex().unlock();
Eric Laurent10351942014-05-08 18:49:52 -0700721 {
Andy Hung87e82412023-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 Hung87e82412023-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 Hung87e82412023-08-29 14:26:09 -0700732 mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800733 return status;
734}
735
Andy Hung71742ab2023-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 Hungf79092d2023-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 Hung87e82412023-08-29 14:26:09 -0700743// sendIoConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-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 Hung71742ab2023-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 Hungf79092d2023-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 Hung87e82412023-08-29 14:26:09 -0700767// sendPrioConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-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 Hung87e82412023-08-29 14:26:09 -0700775// sendSetParameterConfigEvent_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-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 Hung71742ab2023-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 Hungf79092d2023-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 Hung71742ab2023-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 Hungf79092d2023-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 Hung71742ab2023-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 Hungf79092d2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -0700837void ThreadBase::sendCheckOutputStageEffectsEvent()
Eric Laurentb3f315a2021-07-13 15:09:05 +0200838{
Andy Hungf79092d2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -0700850void ThreadBase::sendHalLatencyModesChangedEvent_l()
Eric Laurent6f9534f2022-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 Hung71742ab2023-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 Wasilczyk8f36f6e2023-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 Laurent6f9534f2022-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 Hungf79092d2023-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 Hung87e82412023-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 Hung71742ab2023-07-07 13:47:37 -07001024void ThreadBase::dump(int fd, const Vector<String16>& args)
Andy Hung71ba4b32022-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 Hung87e82412023-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 Hung87e82412023-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 Hung71742ab2023-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 Hung4d693a32023-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 Wasilczyk8f36f6e2023-08-15 20:59:35 +00001073 channelMaskToString(mChannelMask, mType != RECORD).c_str());
Andy Hung4d693a32023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-07-07 13:47:37 -07001154void ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001155{
Andy Hungf79092d2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -07001208void ThreadBase::releaseWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001209{
Andy Hungf79092d2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -07001267void ThreadBase::clearPowerManager()
Eric Laurent81784c32012-11-19 14:55:58 -08001268{
Andy Hungf79092d2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-07-07 13:47:37 -07001394void ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
Eric Laurent6b446ce2019-12-13 10:56:31 -08001395 audio_session_t sessionId,
Andy Hung71ba4b32022-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 Hung87e82412023-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 Hung87e82412023-08-29 14:26:09 -07001415 mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001416 }
1417}
1418
Andy Hung87e82412023-08-29 14:26:09 -07001419// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-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 Hungbd72c542023-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 Hung87e82412023-08-29 14:26:09 -07001463// checkEffectCompatibility_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-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 Hungbd72c542023-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 Hung87e82412023-08-29 14:26:09 -07001618// ThreadBase::createEffect_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07001619sp<IAfEffectHandle> ThreadBase::createEffect_l(
Andy Hungd65869f2023-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 Hungbd72c542023-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 Hungbd72c542023-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 Hung87e82412023-08-29 14:26:09 -07001647 { // scope for mutex()
Andy Hungf79092d2023-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 Hungbd72c542023-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 Hung2cbc2722023-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 Hung2cbc2722023-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 Hung2cbc2722023-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 Hungbd72c542023-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 Hungf79092d2023-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 Hung71742ab2023-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 Hungbd72c542023-06-20 18:56:17 -07001728 sp<IAfEffectModule> effect;
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001729 {
Andy Hungf79092d2023-08-31 16:13:39 -07001730 audio_utils::lock_guard _l(mutex());
Andy Hungbd72c542023-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 Hung2cbc2722023-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 Hung71742ab2023-07-07 13:47:37 -07001754void ThreadBase::onEffectEnable(const sp<IAfEffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001755 if (isOffloadOrMmap()) {
Andy Hungf79092d2023-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 Hung2cbc2722023-07-17 17:05:00 -07001765 mAfThreadCallback->onNonOffloadableGlobalEffectEnable();
Eric Laurent6b446ce2019-12-13 10:56:31 -08001766 }
1767 }
1768}
1769
Andy Hung71742ab2023-07-07 13:47:37 -07001770void ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001771 if (isOffloadOrMmap()) {
Andy Hungf79092d2023-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 Hung71742ab2023-07-07 13:47:37 -07001777sp<IAfEffectModule> ThreadBase::getEffect(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001778 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001779{
Andy Hungf79092d2023-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 Hung71742ab2023-07-07 13:47:37 -07001784sp<IAfEffectModule> ThreadBase::getEffect_l(audio_session_t sessionId,
Andy Hung4989d312023-06-29 21:19:25 -07001785 int effectId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001786{
Andy Hungbd72c542023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hungf79092d2023-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 Hungbd72c542023-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 Hungf79092d2023-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 Hungf79092d2023-08-31 16:13:39 -07001812 ALOGV("%s: new effect chain for session %d", __func__, sessionId);
Andy Hungbd72c542023-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 Hungf79092d2023-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 Hungf79092d2023-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 Hung2cbc2722023-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 Hung71742ab2023-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 Hungbd72c542023-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 Hung71742ab2023-07-07 13:47:37 -07001863void ThreadBase::lockEffectChains_l(
Andy Hungbd72c542023-06-20 18:56:17 -07001864 Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-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 Hung60a6c3d2023-08-29 12:19:17 -07001869 mEffectChains[i]->mutex().lock();
Eric Laurent81784c32012-11-19 14:55:58 -08001870 }
1871}
1872
Andy Hung71742ab2023-07-07 13:47:37 -07001873void ThreadBase::unlockEffectChains(
Andy Hungbd72c542023-06-20 18:56:17 -07001874 const Vector<sp<IAfEffectChain>>& effectChains)
Andy Hung71ba4b32022-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 Hung60a6c3d2023-08-29 12:19:17 -07001878 effectChains[i]->mutex().unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001879 }
1880}
1881
Andy Hung71742ab2023-07-07 13:47:37 -07001882sp<IAfEffectChain> ThreadBase::getEffectChain(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08001883{
Andy Hungf79092d2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -07001900void ThreadBase::setMode(audio_mode_t mode)
Eric Laurent81784c32012-11-19 14:55:58 -08001901{
Andy Hungf79092d2023-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 Hung71742ab2023-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 Hung71742ab2023-07-07 13:47:37 -07001920void ThreadBase::systemReady()
Eric Laurent72e3f392015-05-20 14:43:50 -07001921{
Andy Hungf79092d2023-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 Hung71742ab2023-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;
1944 ++mBatteryCounter[track->uid()].second;
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 Hung71742ab2023-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++;
1958 --mBatteryCounter[track->uid()].second;
1959 // 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 Hung71742ab2023-07-07 13:47:37 -07001969void ThreadBase::ActiveTracks<T>::clear() {
Andy Hungdae27702016-10-31 14:01:16 -07001970 for (const sp<T> &track : mActiveTracks) {
1971 BatteryNotifier::getInstance().noteStopAudio(track->uid());
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();
1978 mBatteryCounter.clear();
1979}
1980
1981template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07001982void ThreadBase::ActiveTracks<T>::updatePowerState(
Andy Hung71ba4b32022-10-06 12:09:49 -07001983 const sp<ThreadBase>& thread, bool force) {
Andy Hungdae27702016-10-31 14:01:16 -07001984 // Updates ActiveTracks client uids to the thread wakelock.
1985 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1986 thread->updateWakeLockUids_l(getWakeLockUids());
1987 mLastActiveTracksGeneration = mActiveTracksGeneration;
1988 }
1989
1990 // Updates BatteryNotifier uids
1991 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1992 const uid_t uid = it->first;
1993 ssize_t &previous = it->second.first;
1994 ssize_t &current = it->second.second;
1995 if (current > 0) {
1996 if (previous == 0) {
1997 BatteryNotifier::getInstance().noteStartAudio(uid);
1998 }
1999 previous = current;
2000 ++it;
2001 } else if (current == 0) {
2002 if (previous > 0) {
2003 BatteryNotifier::getInstance().noteStopAudio(uid);
2004 }
2005 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
2006 } else /* (current < 0) */ {
2007 LOG_ALWAYS_FATAL("negative battery count %zd", current);
2008 }
2009 }
2010}
Eric Laurent83b88082014-06-20 18:31:16 -07002011
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002012template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002013bool ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002014 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07002015 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002016
2017 for (const sp<T> &track : mActiveTracks) {
2018 // Do not short-circuit as all hasChanged states must be reset
2019 // as all the metadata are going to be sent
2020 hasChanged |= track->readAndClearHasChanged();
2021 }
Kevin Rocard069c2712018-03-29 19:09:14 -07002022 return hasChanged;
2023}
2024
2025template <typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002026void ThreadBase::ActiveTracks<T>::logTrack(
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002027 const char *funcName, const sp<T> &track) const {
2028 if (mLocalLog != nullptr) {
2029 String8 result;
2030 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002031 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002032 }
2033}
2034
Andy Hung71742ab2023-07-07 13:47:37 -07002035void ThreadBase::broadcast_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -08002036{
2037 // Thread could be blocked waiting for async
2038 // so signal it to handle state changes immediately
2039 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
2040 // be lost so we also flag to prevent it blocking on mWaitWorkCV
2041 mSignalPending = true;
Andy Hung87e82412023-08-29 14:26:09 -07002042 mWaitWorkCV.notify_all();
Eric Laurent6acd1d42017-01-04 14:23:29 -08002043}
2044
Andy Hungd0979812019-02-21 15:51:44 -08002045// Call only from threadLoop() or when it is idle.
2046// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
Andy Hung71742ab2023-07-07 13:47:37 -07002047void ThreadBase::sendStatistics(bool force)
Andy Hungd0979812019-02-21 15:51:44 -08002048{
2049 // Do not log if we have no stats.
2050 // We choose the timestamp verifier because it is the most likely item to be present.
2051 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
2052 if (nstats == 0) {
2053 return;
2054 }
2055
2056 // Don't log more frequently than once per 12 hours.
2057 // We use BOOTTIME to include suspend time.
2058 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
2059 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
2060 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
2061 return;
2062 }
2063
2064 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
2065 mLastRecordedTimeNs = timeNs;
2066
Ray Essickf27e9872019-12-07 06:28:46 -08002067 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08002068
2069#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
2070
2071 // thread configuration
2072 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
2073 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
2074 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
2075 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
2076 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
2077 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
2078 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07002079 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
2080 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08002081
2082 // thread statistics
2083 if (mIoJitterMs.getN() > 0) {
2084 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
2085 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
2086 }
2087 if (mProcessTimeMs.getN() > 0) {
2088 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
2089 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
2090 }
2091 const auto tsjitter = mTimestampVerifier.getJitterMs();
2092 if (tsjitter.getN() > 0) {
2093 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
2094 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
2095 }
2096 if (mLatencyMs.getN() > 0) {
2097 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
2098 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
2099 }
Robert Wu06db0a32021-08-10 19:05:34 +00002100 if (mMonopipePipeDepthStats.getN() > 0) {
2101 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
2102 mMonopipePipeDepthStats.getMean());
2103 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
2104 mMonopipePipeDepthStats.getStdDev());
2105 }
Andy Hungd0979812019-02-21 15:51:44 -08002106
2107 item->selfrecord();
2108}
2109
Andy Hung71742ab2023-07-07 13:47:37 -07002110product_strategy_t ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
Eric Laurentd66d7a12021-07-13 13:35:32 +02002111{
Andy Hung2cbc2722023-07-17 17:05:00 -07002112 if (!mAfThreadCallback->isAudioPolicyReady()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002113 return PRODUCT_STRATEGY_NONE;
2114 }
2115 return AudioSystem::getStrategyForStream(stream);
2116}
2117
Andy Hung87e82412023-08-29 14:26:09 -07002118// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07002119void ThreadBase::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002120 const sp<audio_utils::MelProcessor>& /*processor*/)
2121{
2122 // Do nothing
2123 ALOGW("%s: ThreadBase does not support CSD", __func__);
2124}
2125
Andy Hung87e82412023-08-29 14:26:09 -07002126// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07002127void ThreadBase::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +01002128{
2129 // Do nothing
2130 ALOGW("%s: ThreadBase does not support CSD", __func__);
2131}
2132
Eric Laurent81784c32012-11-19 14:55:58 -08002133// ----------------------------------------------------------------------------
2134// Playback
2135// ----------------------------------------------------------------------------
2136
Andy Hung2cbc2722023-07-17 17:05:00 -07002137PlaybackThread::PlaybackThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08002138 AudioStreamOut* output,
2139 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07002140 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02002141 bool systemReady,
2142 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07002143 : ThreadBase(afThreadCallback, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08002144 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hungf8ab4692023-07-20 21:44:14 -07002145 mMixerBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08002146 mMixerBuffer(NULL),
2147 mMixerBufferSize(0),
2148 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
2149 mMixerBufferValid(false),
Andy Hungf8ab4692023-07-20 21:44:14 -07002150 mEffectBufferEnabled(kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08002151 mEffectBuffer(NULL),
2152 mEffectBufferSize(0),
2153 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
2154 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07002155 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08002156 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07002157 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002158 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08002159 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08002160 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08002161 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08002162 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08002163 mMixerStatus(MIXER_IDLE),
2164 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Andy Hung18bef9b2023-07-20 21:31:38 -07002165 mStandbyDelayNs(getStandbyTimeInNanos()),
Eric Laurentbfb1b832013-01-07 09:53:42 -08002166 mBytesRemaining(0),
2167 mCurrentWriteLength(0),
2168 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07002169 mWriteAckSequence(0),
2170 mDrainSequence(0),
Andy Hung01b29482023-07-19 16:22:58 -07002171 mScreenState(mAfThreadCallback->getScreenState()),
Eric Laurent81784c32012-11-19 14:55:58 -08002172 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002173 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07002174 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01002175 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
Brian Lindahl9e661ad2022-07-27 18:01:07 +02002176 mDownStreamPatch{},
Eric Laurentb0463942022-12-20 16:31:10 +01002177 mIsTimestampAdvancing(kMinimumTimeBetweenTimestampChecksNs)
Eric Laurent81784c32012-11-19 14:55:58 -08002178{
Glenn Kastend7dca052015-03-05 16:05:54 -08002179 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07002180 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002181
Andy Hung87e82412023-08-29 14:26:09 -07002182 // Assumes constructor is called by AudioFlinger with its mutex() held, but
Eric Laurent81784c32012-11-19 14:55:58 -08002183 // it would be safer to explicitly pass initial masterVolume/masterMute as
2184 // parameter.
2185 //
2186 // If the HAL we are using has support for master volume or master mute,
2187 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2188 // and the mute set to false).
Andy Hung2cbc2722023-07-17 17:05:00 -07002189 mMasterVolume = afThreadCallback->masterVolume_l();
2190 mMasterMute = afThreadCallback->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002191 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002192 if (mOutput->audioHwDev->canSetMasterVolume()) {
2193 mMasterVolume = 1.0;
2194 }
2195
2196 if (mOutput->audioHwDev->canSetMasterMute()) {
2197 mMasterMute = false;
2198 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002199 mIsMsdDevice = strcmp(
2200 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002201 }
2202
Eric Laurentf1f22e72021-07-13 14:04:14 +02002203 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2204 mMixerChannelMask = mixerConfig->channel_mask;
2205 }
2206
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002207 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002208
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002209 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002210 && mMixerChannelMask != mChannelMask) {
2211 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2212 mChannelMask, mMixerChannelMask);
2213 }
2214
Andy Hungc8fddf32018-08-08 18:32:37 -07002215 // TODO: We may also match on address as well as device type for
2216 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002217 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002218 // TODO: This property should be ensure that only contains one single device type.
2219 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2220 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002221 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2222 : AUDIO_DEVICE_NONE));
2223 }
2224
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002225 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2226 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002227 mStreamTypes[stream].volume = 0.0f;
Andy Hung2cbc2722023-07-17 17:05:00 -07002228 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
Eric Laurent81784c32012-11-19 14:55:58 -08002229 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002230 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002231 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2232 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002233 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2234 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002235}
2236
Andy Hung71742ab2023-07-07 13:47:37 -07002237PlaybackThread::~PlaybackThread()
Eric Laurent81784c32012-11-19 14:55:58 -08002238{
Andy Hung2cbc2722023-07-17 17:05:00 -07002239 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002240 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002241 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002242 free(mEffectBuffer);
Eric Laurentb62d0362021-10-26 17:40:18 +02002243 free(mPostSpatializerBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002244}
2245
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002246// Thread virtuals
2247
Andy Hung71742ab2023-07-07 13:47:37 -07002248void PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002249{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002250 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002251 ALOGE("The stream is not open yet"); // This should not happen.
2252 } else {
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002253 // Callbacks take strong or weak pointers as a parameter.
2254 // Since PlaybackThread passes itself as a callback handler, it can only
2255 // be done outside of the constructor. Creating weak and especially strong
2256 // pointers to a refcounted object in its own constructor is strongly
2257 // discouraged, see comments in system/core/libutils/include/utils/RefBase.h.
2258 // Even if a function takes a weak pointer, it is possible that it will
2259 // need to convert it to a strong pointer down the line.
2260 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING &&
2261 mOutput->stream->setCallback(this) == OK) {
2262 mUseAsyncWrite = true;
Andy Hung71742ab2023-07-07 13:47:37 -07002263 mCallbackThread = sp<AsyncCallbackThread>::make(this);
Mikhail Naganovaec565e2023-02-22 16:31:28 -08002264 }
2265
jiabinf6eb4c32020-02-25 14:06:25 -08002266 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002267 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002268 }
2269 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002270 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Andy Hung44d648b2022-04-08 17:33:40 -07002271 mThreadSnapshot.setTid(getTid());
Eric Laurent81784c32012-11-19 14:55:58 -08002272}
2273
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002274// ThreadBase virtuals
Andy Hung71742ab2023-07-07 13:47:37 -07002275void PlaybackThread::preExit()
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002276{
2277 ALOGV(" preExit()");
Ytai Ben-Tsvi7e0183f2022-02-04 10:49:54 -08002278 status_t result = mOutput->stream->exit();
2279 ALOGE_IF(result != OK, "Error when calling exit(): %d", result);
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002280}
2281
Andy Hung71742ab2023-07-07 13:47:37 -07002282void PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08002283{
Eric Laurent81784c32012-11-19 14:55:58 -08002284 String8 result;
2285
Marco Nelissenb2208842014-02-07 14:00:50 -08002286 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002287 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2288 const stream_type_t *st = &mStreamTypes[i];
2289 if (i > 0) {
2290 result.appendFormat(", ");
2291 }
2292 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2293 if (st->mute) {
2294 result.append("M");
2295 }
2296 }
2297 result.append("\n");
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002298 write(fd, result.c_str(), result.length());
Eric Laurent81784c32012-11-19 14:55:58 -08002299 result.clear();
2300
Eric Laurent81784c32012-11-19 14:55:58 -08002301 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2302 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002303 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002304 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002305
2306 size_t numtracks = mTracks.size();
2307 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002308 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002309 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002310 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002311 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002312 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002313 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002314 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002315 for (size_t i = 0; i < numtracks; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002316 sp<IAfTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08002317 if (track != 0) {
2318 bool active = mActiveTracks.indexOf(track) >= 0;
2319 if (active) {
2320 numactiveseen++;
2321 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002322 result.append(prefix);
2323 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002324 }
2325 }
2326 } else {
2327 result.append("\n");
2328 }
2329 if (numactiveseen != numactive) {
2330 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002331 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002332 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002333 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002334 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002335 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002336 sp<IAfTrack> track = mActiveTracks[i];
Andy Hungdae27702016-10-31 14:01:16 -07002337 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002338 result.append(prefix);
2339 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002340 }
2341 }
2342 }
2343
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002344 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002345}
2346
Andy Hung71742ab2023-07-07 13:47:37 -07002347void PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002348{
Andy Hung04cb8f72020-03-20 13:44:33 -07002349 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002350 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002351 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2352 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002353 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2354 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2355 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2356 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002357 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002358 dprintf(fd, " Total writes: %d\n", mNumWrites);
2359 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2360 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2361 dprintf(fd, " Suspend count: %d\n", mSuspended);
2362 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2363 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2364 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2365 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002366 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002367 AudioStreamOut *output = mOutput;
2368 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002369 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002370 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002371 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2372 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2373 if (mPipeSink.get() != nullptr) {
2374 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2375 }
2376 if (output != nullptr) {
2377 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002378 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002379 }
Eric Laurent81784c32012-11-19 14:55:58 -08002380}
2381
Andy Hung87e82412023-08-29 14:26:09 -07002382// PlaybackThread::createTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07002383sp<IAfTrack> PlaybackThread::createTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07002384 const sp<Client>& client,
Eric Laurent81784c32012-11-19 14:55:58 -08002385 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002386 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002387 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002388 audio_format_t format,
2389 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002390 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002391 size_t *pNotificationFrameCount,
2392 uint32_t notificationsPerBuffer,
2393 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002394 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002395 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002396 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002397 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002398 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002399 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002400 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002401 audio_port_handle_t portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02002402 const sp<media::IAudioTrackCallback>& callback,
jiabinc658e452022-10-21 20:52:21 +00002403 bool isSpatialized,
2404 bool isBitPerfect)
Eric Laurent81784c32012-11-19 14:55:58 -08002405{
Glenn Kasten74935e42013-12-19 08:56:45 -08002406 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002407 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07002408 sp<IAfTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08002409 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002410 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002411 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002412 uint32_t sampleRate;
2413
2414 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2415 lStatus = BAD_VALUE;
2416 goto Exit;
2417 }
Eric Laurent21da6472017-11-09 16:29:26 -08002418
2419 if (*pSampleRate == 0) {
2420 *pSampleRate = mSampleRate;
2421 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002422 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002423
2424 // special case for FAST flag considered OK if fast mixer is present
2425 if (hasFastMixer()) {
2426 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2427 }
2428
2429 // Check if requested flags are compatible with output stream flags
2430 if ((*flags & outputFlags) != *flags) {
2431 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2432 *flags, outputFlags);
2433 *flags = (audio_output_flags_t)(*flags & outputFlags);
2434 }
Eric Laurent81784c32012-11-19 14:55:58 -08002435
jiabinc658e452022-10-21 20:52:21 +00002436 if (isBitPerfect) {
Andy Hungbd72c542023-06-20 18:56:17 -07002437 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
jiabinc658e452022-10-21 20:52:21 +00002438 if (chain.get() != nullptr) {
2439 // Bit-perfect is required according to the configuration and preferred mixer
2440 // attributes, but it is not in the output flag from the client's request. Explicitly
2441 // adding bit-perfect flag to check the compatibility
2442 audio_output_flags_t flagsToCheck =
2443 (audio_output_flags_t)(*flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT);
2444 chain->checkOutputFlagCompatibility(&flagsToCheck);
2445 if ((flagsToCheck & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE) {
2446 ALOGE("%s cannot create track as there is data-processing effect attached to "
2447 "given session id(%d)", __func__, sessionId);
2448 lStatus = BAD_VALUE;
2449 goto Exit;
2450 }
2451 *flags = flagsToCheck;
2452 }
2453 }
2454
Eric Laurent81784c32012-11-19 14:55:58 -08002455 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002456 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002457 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002458 // PCM data
2459 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002460 // TODO: extract as a data library function that checks that a computationally
2461 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002462 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002463 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2464 (channelMask == AUDIO_CHANNEL_OUT_MONO
2465 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002466 // hardware sample rate
2467 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002468 // normal mixer has an associated fast mixer
2469 hasFastMixer() &&
2470 // there are sufficient fast track slots available
2471 (mFastTrackAvailMask != 0)
2472 // FIXME test that MixerThread for this fast track has a capable output HAL
2473 // FIXME add a permission test also?
2474 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002475 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2476 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002477 // read the fast track multiplier property the first time it is needed
2478 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2479 if (ok != 0) {
2480 ALOGE("%s pthread_once failed: %d", __func__, ok);
2481 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002482 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002483 }
Eric Laurent4c415062016-06-17 16:14:16 -07002484
2485 // check compatibility with audio effects.
Andy Hung87e82412023-08-29 14:26:09 -07002486 { // scope for mutex()
Andy Hungf79092d2023-08-31 16:13:39 -07002487 audio_utils::lock_guard _l(mutex());
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002488 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002489 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002490 AUDIO_SESSION_OUTPUT_STAGE,
2491 AUDIO_SESSION_OUTPUT_MIX,
2492 sessionId,
2493 }) {
Andy Hungbd72c542023-06-20 18:56:17 -07002494 sp<IAfEffectChain> chain = getEffectChain_l(session);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002495 if (chain.get() != nullptr) {
2496 audio_output_flags_t old = *flags;
2497 chain->checkOutputFlagCompatibility(flags);
2498 if (old != *flags) {
2499 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2500 (int)session, (int)old, (int)*flags);
2501 }
Eric Laurent4c415062016-06-17 16:14:16 -07002502 }
2503 }
2504 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002505 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002506 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2507 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002508 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002509 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002510 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002511 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002512 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002513 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002514 audio_is_linear_pcm(format), channelMask, sampleRate,
2515 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002516 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002517 }
2518 }
Eric Laurent21da6472017-11-09 16:29:26 -08002519
2520 if (!audio_has_proportional_frames(format)) {
2521 if (sharedBuffer != 0) {
2522 // Same comment as below about ignoring frameCount parameter for set()
2523 frameCount = sharedBuffer->size();
2524 } else if (frameCount == 0) {
2525 frameCount = mNormalFrameCount;
2526 }
2527 if (notificationFrameCount != frameCount) {
2528 notificationFrameCount = frameCount;
2529 }
2530 } else if (sharedBuffer != 0) {
2531 // FIXME: Ensure client side memory buffers need
2532 // not have additional alignment beyond sample
2533 // (e.g. 16 bit stereo accessed as 32 bit frame).
2534 size_t alignment = audio_bytes_per_sample(format);
2535 if (alignment & 1) {
2536 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2537 alignment = 1;
2538 }
2539 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2540 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2541 if (channelCount > 1) {
2542 // More than 2 channels does not require stronger alignment than stereo
2543 alignment <<= 1;
2544 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002545 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002546 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002547 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002548 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002549 goto Exit;
2550 }
Eric Laurent21da6472017-11-09 16:29:26 -08002551
2552 // When initializing a shared buffer AudioTrack via constructors,
2553 // there's no frameCount parameter.
2554 // But when initializing a shared buffer AudioTrack via set(),
2555 // there _is_ a frameCount parameter. We silently ignore it.
2556 frameCount = sharedBuffer->size() / frameSize;
2557 } else {
2558 size_t minFrameCount = 0;
2559 // For fast tracks we try to respect the application's request for notifications per buffer.
2560 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2561 if (notificationsPerBuffer > 0) {
2562 // Avoid possible arithmetic overflow during multiplication.
2563 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2564 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2565 notificationsPerBuffer, mFrameCount);
2566 } else {
2567 minFrameCount = mFrameCount * notificationsPerBuffer;
2568 }
2569 }
2570 } else {
2571 // For normal PCM streaming tracks, update minimum frame count.
2572 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2573 // cover audio hardware latency.
2574 // This is probably too conservative, but legacy application code may depend on it.
2575 // If you change this calculation, also review the start threshold which is related.
2576 uint32_t latencyMs = latency_l();
2577 if (latencyMs == 0) {
2578 ALOGE("Error when retrieving output stream latency");
2579 lStatus = UNKNOWN_ERROR;
2580 goto Exit;
2581 }
2582
2583 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2584 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2585
Eric Laurent81784c32012-11-19 14:55:58 -08002586 }
Eric Laurent21da6472017-11-09 16:29:26 -08002587 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002588 frameCount = minFrameCount;
2589 }
Eric Laurent81784c32012-11-19 14:55:58 -08002590 }
Eric Laurent21da6472017-11-09 16:29:26 -08002591
2592 // Make sure that application is notified with sufficient margin before underrun.
2593 // The client can divide the AudioTrack buffer into sub-buffers,
2594 // and expresses its desire to server as the notification frame count.
2595 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2596 size_t maxNotificationFrames;
2597 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2598 // notify every HAL buffer, regardless of the size of the track buffer
2599 maxNotificationFrames = mFrameCount;
2600 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002601 // Triple buffer the notification period for a triple buffered mixer period;
2602 // otherwise, double buffering for the notification period is fine.
2603 //
2604 // TODO: This should be moved to AudioTrack to modify the notification period
2605 // on AudioTrack::setBufferSizeInFrames() changes.
2606 const int nBuffering =
2607 (uint64_t{frameCount} * mSampleRate)
2608 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2609
Eric Laurent21da6472017-11-09 16:29:26 -08002610 maxNotificationFrames = frameCount / nBuffering;
2611 // If client requested a fast track but this was denied, then use the smaller maximum.
2612 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2613 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2614 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2615 maxNotificationFrames = maxNotificationFramesFastDenied;
2616 }
2617 }
2618 }
2619 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2620 if (notificationFrameCount == 0) {
2621 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2622 maxNotificationFrames, frameCount);
2623 } else {
2624 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2625 notificationFrameCount, maxNotificationFrames, frameCount);
2626 }
2627 notificationFrameCount = maxNotificationFrames;
2628 }
2629 }
2630
Glenn Kasten74935e42013-12-19 08:56:45 -08002631 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002632 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002633
Glenn Kastenc3df8382014-03-13 15:05:25 -07002634 switch (mType) {
jiabinc658e452022-10-21 20:52:21 +00002635 case BIT_PERFECT:
2636 if (isBitPerfect) {
2637 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
2638 ALOGE("%s, bad parameter when request streaming bit-perfect, sampleRate=%u, "
2639 "format=%#x, channelMask=%#x, mSampleRate=%u, mFormat=%#x, mChannelMask=%#x",
2640 __func__, sampleRate, format, channelMask, mSampleRate, mFormat,
2641 mChannelMask);
2642 lStatus = BAD_VALUE;
2643 goto Exit;
2644 }
2645 }
2646 break;
Glenn Kastenc3df8382014-03-13 15:05:25 -07002647
2648 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002649 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002650 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002651 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2652 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002653 sampleRate, format, channelMask, mOutput, mFormat);
2654 lStatus = BAD_VALUE;
2655 goto Exit;
2656 }
2657 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002658 break;
2659
2660 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002661 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002662 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2663 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002664 sampleRate, format, channelMask, mOutput, mFormat);
2665 lStatus = BAD_VALUE;
2666 goto Exit;
2667 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002668 break;
2669
2670 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002671 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002672 ALOGE("createTrack_l() Bad parameter: format %#x \""
2673 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002674 format, mOutput, mFormat);
2675 lStatus = BAD_VALUE;
2676 goto Exit;
2677 }
Andy Hungcd044842014-08-07 11:04:34 -07002678 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002679 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2680 lStatus = BAD_VALUE;
2681 goto Exit;
2682 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002683 break;
2684
Eric Laurent81784c32012-11-19 14:55:58 -08002685 }
2686
2687 lStatus = initCheck();
2688 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002689 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002690 goto Exit;
2691 }
2692
Andy Hung87e82412023-08-29 14:26:09 -07002693 { // scope for mutex()
Andy Hungf79092d2023-08-31 16:13:39 -07002694 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002695
2696 // all tracks in same audio session must share the same routing strategy otherwise
2697 // conflicts will happen when tracks are moved from one output to another by audio policy
2698 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002699 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002700 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002701 sp<IAfTrack> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002702 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002703 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002704 if (sessionId == t->sessionId() && strategy != actual) {
2705 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2706 strategy, actual);
2707 lStatus = BAD_VALUE;
2708 goto Exit;
2709 }
2710 }
2711 }
2712
yucliuc9c49cd2020-07-13 16:25:21 -07002713 // Set DIRECT flag if current thread is DirectOutputThread. This can
2714 // happen when the playback is rerouted to direct output thread by
2715 // dynamic audio policy.
2716 // Do NOT report the flag changes back to client, since the client
2717 // doesn't explicitly request a direct flag.
2718 audio_output_flags_t trackFlags = *flags;
2719 if (mType == DIRECT) {
2720 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2721 }
2722
Andy Hung3ff4b552023-06-26 19:20:57 -07002723 track = IAfTrack::create(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002724 channelMask, frameCount,
2725 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002726 sessionId, creatorPid, attributionSource, trackFlags,
Andy Hung3ff4b552023-06-26 19:20:57 -07002727 IAfTrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/,
jiabinc658e452022-10-21 20:52:21 +00002728 speed, isSpatialized, isBitPerfect);
Glenn Kasten03003332013-08-06 15:40:54 -07002729
Glenn Kasten03003332013-08-06 15:40:54 -07002730 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2731 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002732 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002733 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002734 goto Exit;
2735 }
2736 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002737 {
Andy Hungf79092d2023-08-31 16:13:39 -07002738 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabinf6eb4c32020-02-25 14:06:25 -08002739 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002740 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002741 }
2742 }
Eric Laurent81784c32012-11-19 14:55:58 -08002743
Andy Hungbd72c542023-06-20 18:56:17 -07002744 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent81784c32012-11-19 14:55:58 -08002745 if (chain != 0) {
2746 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2747 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002748 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002749 chain->incTrackCnt();
2750 }
2751
Eric Laurent05067782016-06-01 18:27:28 -07002752 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002753 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2754 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2755 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002756 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002757 }
2758 }
2759
2760 lStatus = NO_ERROR;
2761
2762Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002763 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002764 return track;
2765}
2766
Andy Hung1bc088a2018-02-09 15:57:31 -08002767template<typename T>
Andy Hung71742ab2023-07-07 13:47:37 -07002768ssize_t PlaybackThread::Tracks<T>::remove(const sp<T>& track)
Andy Hung1bc088a2018-02-09 15:57:31 -08002769{
Andy Hungc0691382018-09-12 18:01:57 -07002770 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002771 const ssize_t index = mTracks.remove(track);
2772 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002773 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002774 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002775 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002776 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002777 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002778 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002779 }
2780 return index;
2781}
2782
Andy Hung71742ab2023-07-07 13:47:37 -07002783uint32_t PlaybackThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08002784{
2785 return latency;
2786}
2787
Andy Hung71742ab2023-07-07 13:47:37 -07002788uint32_t PlaybackThread::latency() const
Eric Laurent81784c32012-11-19 14:55:58 -08002789{
Andy Hungf79092d2023-08-31 16:13:39 -07002790 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002791 return latency_l();
2792}
Andy Hung71742ab2023-07-07 13:47:37 -07002793uint32_t PlaybackThread::latency_l() const
Eric Laurent81784c32012-11-19 14:55:58 -08002794{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002795 uint32_t latency;
2796 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2797 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002798 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002799 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002800}
2801
Andy Hung71742ab2023-07-07 13:47:37 -07002802void PlaybackThread::setMasterVolume(float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002803{
Andy Hungf79092d2023-08-31 16:13:39 -07002804 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002805 // Don't apply master volume in SW if our HAL can do it for us.
2806 if (mOutput && mOutput->audioHwDev &&
2807 mOutput->audioHwDev->canSetMasterVolume()) {
2808 mMasterVolume = 1.0;
2809 } else {
2810 mMasterVolume = value;
2811 }
2812}
2813
Andy Hung71742ab2023-07-07 13:47:37 -07002814void PlaybackThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002815{
2816 mMasterBalance.store(balance);
2817}
2818
Andy Hung71742ab2023-07-07 13:47:37 -07002819void PlaybackThread::setMasterMute(bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002820{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002821 if (isDuplicating()) {
2822 return;
2823 }
Andy Hungf79092d2023-08-31 16:13:39 -07002824 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002825 // Don't apply master mute in SW if our HAL can do it for us.
2826 if (mOutput && mOutput->audioHwDev &&
2827 mOutput->audioHwDev->canSetMasterMute()) {
2828 mMasterMute = false;
2829 } else {
2830 mMasterMute = muted;
2831 }
2832}
2833
Andy Hung71742ab2023-07-07 13:47:37 -07002834void PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent81784c32012-11-19 14:55:58 -08002835{
Andy Hungf79092d2023-08-31 16:13:39 -07002836 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002837 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002838 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002839}
2840
Andy Hung71742ab2023-07-07 13:47:37 -07002841void PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent81784c32012-11-19 14:55:58 -08002842{
Andy Hungf79092d2023-08-31 16:13:39 -07002843 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002844 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002845 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002846}
2847
Andy Hung71742ab2023-07-07 13:47:37 -07002848float PlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent81784c32012-11-19 14:55:58 -08002849{
Andy Hungf79092d2023-08-31 16:13:39 -07002850 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08002851 return mStreamTypes[stream].volume;
2852}
2853
Andy Hung71742ab2023-07-07 13:47:37 -07002854void PlaybackThread::setVolumeForOutput_l(float left, float right) const
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002855{
2856 mOutput->stream->setVolume(left, right);
2857}
2858
Andy Hung87e82412023-08-29 14:26:09 -07002859// addTrack_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07002860status_t PlaybackThread::addTrack_l(const sp<IAfTrack>& track)
Andy Hung87e82412023-08-29 14:26:09 -07002861NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08002862{
2863 status_t status = ALREADY_EXISTS;
2864
Eric Laurent81784c32012-11-19 14:55:58 -08002865 if (mActiveTracks.indexOf(track) < 0) {
2866 // the track is newly added, make sure it fills up all its
2867 // buffers before playing. This is to ensure the client will
2868 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002869 if (track->isExternalTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002870 IAfTrackBase::track_state state = track->state();
Andy Hung87e82412023-08-29 14:26:09 -07002871 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002872 status = AudioSystem::startOutput(track->portId());
Andy Hung87e82412023-08-29 14:26:09 -07002873 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002874 // abort track was stopped/paused while we released the lock
Andy Hung3ff4b552023-06-26 19:20:57 -07002875 if (state != track->state()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002876 if (status == NO_ERROR) {
Andy Hung87e82412023-08-29 14:26:09 -07002877 mutex().unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002878 AudioSystem::stopOutput(track->portId());
Andy Hung87e82412023-08-29 14:26:09 -07002879 mutex().lock();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002880 }
2881 return INVALID_OPERATION;
2882 }
2883 // abort if start is rejected by audio policy manager
2884 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00002885 // Do not replace the error if it is DEAD_OBJECT. When this happens, it indicates
2886 // current playback thread is reopened, which may happen when clients set preferred
2887 // mixer configuration. Returning DEAD_OBJECT will make the client restore track
2888 // immediately.
2889 return status == DEAD_OBJECT ? status : PERMISSION_DENIED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002890 }
2891#ifdef ADD_BATTERY_DATA
2892 // to track the speaker usage
2893 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2894#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002895 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002896 }
2897
Eric Laurent51716182016-02-29 18:00:56 -08002898 // set retry count for buffer fill
2899 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002900 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002901 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002902 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002903 track->retryCount() = kMaxTrackStartupRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07002904 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002905 track->fillingStatus() = mStandby ? IAfTrack::FS_FILLING : IAfTrack::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002906 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07002907 track->retryCount() = kMaxTrackStartupRetries;
2908 track->fillingStatus() =
2909 track->sharedBuffer() != 0 ? IAfTrack::FS_FILLED : IAfTrack::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002910 }
2911
Andy Hungbd72c542023-06-20 18:56:17 -07002912 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
jiabineb3bda02020-06-30 14:07:03 -07002913 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2914 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2915 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002916 // Unlock due to VibratorService will lock for this call and will
2917 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung87e82412023-08-29 14:26:09 -07002918 mutex().unlock();
Andy Hung9554ec02023-07-20 21:23:42 -07002919 const os::HapticScale intensity = afutils::onExternalVibrationStart(
jiabin57303cc2018-12-18 15:45:57 -08002920 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002921 std::optional<media::AudioVibratorInfo> vibratorInfo;
2922 {
2923 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2924 // used to play this track.
Andy Hungf79092d2023-08-31 16:13:39 -07002925 audio_utils::lock_guard _l(mAfThreadCallback->mutex());
Andy Hung2cbc2722023-07-17 17:05:00 -07002926 vibratorInfo = std::move(mAfThreadCallback->getDefaultVibratorInfo_l());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002927 }
Andy Hung87e82412023-08-29 14:26:09 -07002928 mutex().lock();
Simon Bowden62823412022-10-17 14:52:26 +00002929 track->setHapticIntensity(intensity);
Lais Andradebc3f37a2021-07-02 00:13:19 +01002930 if (vibratorInfo) {
2931 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2932 }
2933
jiabin57303cc2018-12-18 15:45:57 -08002934 // Haptic playback should be enabled by vibrator service.
2935 if (track->getHapticPlaybackEnabled()) {
2936 // Disable haptic playback of all active track to ensure only
2937 // one track playing haptic if current track should play haptic.
2938 for (const auto &t : mActiveTracks) {
2939 t->setHapticPlaybackEnabled(false);
2940 }
jiabin245cdd92018-12-07 17:55:15 -08002941 }
jiabine70bc7f2020-06-30 22:07:55 -07002942
2943 // Set haptic intensity for effect
2944 if (chain != nullptr) {
2945 chain->setHapticIntensity_l(track->id(), intensity);
2946 }
jiabin245cdd92018-12-07 17:55:15 -08002947 }
2948
Andy Hung3ff4b552023-06-26 19:20:57 -07002949 track->setResetDone(false);
Andy Hung59de4262021-06-14 10:53:54 -07002950 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002951 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002952 if (chain != 0) {
2953 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2954 track->sessionId());
2955 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002956 }
2957
Andy Hungc2b11cb2020-04-22 09:04:01 -07002958 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002959 status = NO_ERROR;
2960 }
2961
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002962 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002963 return status;
2964}
2965
Andy Hung71742ab2023-07-07 13:47:37 -07002966bool PlaybackThread::destroyTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002967{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002968 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002969 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002970 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
Andy Hung3ff4b552023-06-26 19:20:57 -07002971 track->setState(IAfTrackBase::STOPPED);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002972 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002973 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002974 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Andy Hung916987e2023-03-20 19:08:16 -07002975 if (track->isPausePending()) {
2976 track->pauseAck();
2977 }
Andy Hung3ff4b552023-06-26 19:20:57 -07002978 track->setState(IAfTrackBase::STOPPING_1);
Eric Laurent81784c32012-11-19 14:55:58 -08002979 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002980
2981 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002982}
2983
Andy Hung71742ab2023-07-07 13:47:37 -07002984void PlaybackThread::removeTrack_l(const sp<IAfTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002985{
2986 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002987
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002988 String8 result;
2989 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00002990 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2148bf02016-11-28 19:01:02 -08002991
Eric Laurent81784c32012-11-19 14:55:58 -08002992 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002993 {
Andy Hungf79092d2023-08-31 16:13:39 -07002994 audio_utils::lock_guard _atCbL(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07002995 mAudioTrackCallbacks.erase(track);
2996 }
Eric Laurent81784c32012-11-19 14:55:58 -08002997 if (track->isFastTrack()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07002998 int index = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002999 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08003000 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
3001 mFastTrackAvailMask |= 1 << index;
3002 // redundant as track is about to be destroyed, for dumpsys only
Andy Hung3ff4b552023-06-26 19:20:57 -07003003 track->fastIndex() = -1;
Eric Laurent81784c32012-11-19 14:55:58 -08003004 }
Andy Hungbd72c542023-06-20 18:56:17 -07003005 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08003006 if (chain != 0) {
3007 chain->decTrackCnt();
3008 }
3009}
3010
Andy Hung71742ab2023-07-07 13:47:37 -07003011String8 PlaybackThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08003012{
Andy Hungf79092d2023-08-31 16:13:39 -07003013 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003014 String8 out_s8;
3015 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
3016 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08003017 }
Andy Hung71ba4b32022-10-06 12:09:49 -07003018 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08003019}
3020
Andy Hung71742ab2023-07-07 13:47:37 -07003021status_t DirectOutputThread::selectPresentation(int presentationId, int programId) {
Andy Hungf79092d2023-08-31 16:13:39 -07003022 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003023 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08003024 return NO_INIT;
3025 }
3026 return mOutput->stream->selectPresentation(presentationId, programId);
3027}
3028
Andy Hung71742ab2023-07-07 13:47:37 -07003029void PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07003030 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003031 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07003032 sp<AudioIoDescriptor> desc;
3033 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003034 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07003035 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003036 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07003037 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003038 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
3039 mSampleRate, mFormat, mChannelMask,
3040 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
3041 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08003042 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07003043 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003044 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07003045 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07003046 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08003047 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07003048 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08003049 break;
3050 }
Andy Hung2cbc2722023-07-17 17:05:00 -07003051 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08003052}
3053
Andy Hung71742ab2023-07-07 13:47:37 -07003054void PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003055{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003056 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003057}
3058
Andy Hung71742ab2023-07-07 13:47:37 -07003059void PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003060{
Eric Laurent3b4529e2013-09-05 18:09:19 -07003061 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003062}
3063
Andy Hung71742ab2023-07-07 13:47:37 -07003064void PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003065{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07003066 mCallbackThread->setAsyncError();
3067}
3068
Andy Hung71742ab2023-07-07 13:47:37 -07003069void PlaybackThread::onCodecFormatChanged(
jiabinf6eb4c32020-02-25 14:06:25 -08003070 const std::basic_string<uint8_t>& metadataBs)
3071{
Andy Hung71742ab2023-07-07 13:47:37 -07003072 const auto weakPointerThis = wp<PlaybackThread>::fromExisting(this);
Kuowei Li9e2f6162022-11-23 16:25:26 +08003073 std::thread([this, metadataBs, weakPointerThis]() {
Andy Hung71742ab2023-07-07 13:47:37 -07003074 const sp<PlaybackThread> playbackThread = weakPointerThis.promote();
Kuowei Li9e2f6162022-11-23 16:25:26 +08003075 if (playbackThread == nullptr) {
3076 ALOGW("PlaybackThread was destroyed, skip codec format change event");
3077 return;
3078 }
3079
jiabinf6eb4c32020-02-25 14:06:25 -08003080 audio_utils::metadata::Data metadata =
3081 audio_utils::metadata::dataFromByteString(metadataBs);
3082 if (metadata.empty()) {
3083 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
3084 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
3085 (int)metadataBs.size());
3086 return;
3087 }
3088
3089 audio_utils::metadata::ByteString metaDataStr =
3090 audio_utils::metadata::byteStringFromData(metadata);
3091 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
Andy Hungf79092d2023-08-31 16:13:39 -07003092 audio_utils::lock_guard _l(audioTrackCbMutex());
jiabin18a4b1c2020-09-17 11:40:42 -07003093 for (const auto& callbackPair : mAudioTrackCallbacks) {
3094 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08003095 }
3096 }).detach();
3097}
3098
Andy Hung71742ab2023-07-07 13:47:37 -07003099void PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003100{
Andy Hungf79092d2023-08-31 16:13:39 -07003101 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003102 // reject out of sequence requests
3103 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
3104 mWriteAckSequence &= ~1;
Andy Hung87e82412023-08-29 14:26:09 -07003105 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003106 }
3107}
3108
Andy Hung71742ab2023-07-07 13:47:37 -07003109void PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08003110{
Andy Hungf79092d2023-08-31 16:13:39 -07003111 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07003112 // reject out of sequence requests
3113 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07003114 // Register discontinuity when HW drain is completed because that can cause
3115 // the timestamp frame position to reset to 0 for direct and offload threads.
3116 // (Out of sequence requests are ignored, since the discontinuity would be handled
3117 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11003118 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003119 mDrainSequence &= ~1;
Andy Hung87e82412023-08-29 14:26:09 -07003120 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003121 }
3122}
3123
Andy Hung71742ab2023-07-07 13:47:37 -07003124void PlaybackThread::readOutputParameters_l()
Andy Hungf79092d2023-08-31 16:13:39 -07003125NO_THREAD_SAFETY_ANALYSIS
3126// 'moveEffectChain_ll' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurent81784c32012-11-19 14:55:58 -08003127{
Glenn Kastenadad3d72014-02-21 14:51:43 -08003128 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00003129 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
3130 mSampleRate = audioConfig.sample_rate;
3131 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003132 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003133 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003134 }
Andy Hungf8ab4692023-07-20 21:44:14 -07003135 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07003136 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
3137 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003138 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003139
3140 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
3141 mMixerChannelMask = mChannelMask;
3142 }
3143
Andy Hunge5412692014-05-16 11:25:07 -07003144 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003145 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07003146
Eric Laurentf1f22e72021-07-13 14:04:14 +02003147 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
3148
Phil Burkca5e6142015-07-14 09:42:29 -07003149 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003150 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003151 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07003152 // Get format from the shim, which will be different than the HAL format
3153 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00003154 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003155 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08003156 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003157 }
Andy Hungf8ab4692023-07-20 21:44:14 -07003158 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07003159 LOG_FATAL("HAL format %#x not supported for mixed output",
3160 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07003161 }
Phil Burk062e67a2015-02-11 13:40:50 -08003162 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003163 result = mOutput->stream->getBufferSize(&mBufferSize);
3164 LOG_ALWAYS_FATAL_IF(result != OK,
3165 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07003166 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02003167 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003168 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08003169 mFrameCount);
3170 }
3171
Eric Laurentd1f69b02014-12-15 14:33:13 -08003172 mHwSupportsPause = false;
3173 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003174 bool supportsPause = false, supportsResume = false;
3175 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
3176 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003177 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003178 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08003179 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003180 } else if (supportsResume) {
3181 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08003182 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003183 }
3184 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07003185 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
3186 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
3187 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08003188
Andy Hungfbfc3952015-01-15 13:33:51 -08003189 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
3190 // For best precision, we use float instead of the associated output
3191 // device format (typically PCM 16 bit).
3192
3193 mFormat = AUDIO_FORMAT_PCM_FLOAT;
3194 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
3195 mBufferSize = mFrameSize * mFrameCount;
3196
3197 // TODO: We currently use the associated output device channel mask and sample rate.
3198 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
3199 // (if a valid mask) to avoid premature downmix.
3200 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
3201 // instead of the output device sample rate to avoid loss of high frequency information.
3202 // This may need to be updated as MixerThread/OutputTracks are added and not here.
3203 }
3204
Andy Hung09a50072014-02-27 14:30:47 -08003205 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08003206 double multiplier = 1.0;
Andy Hungd3639922022-04-28 18:00:49 -07003207 // Note: mType == SPATIALIZER does not support FastMixer.
Eric Laurent81784c32012-11-19 14:55:58 -08003208 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
3209 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08003210 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
3211 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003212
Eric Laurent81784c32012-11-19 14:55:58 -08003213 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
3214 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
3215 maxNormalFrameCount = maxNormalFrameCount & ~15;
3216 if (maxNormalFrameCount < minNormalFrameCount) {
3217 maxNormalFrameCount = minNormalFrameCount;
3218 }
3219 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
3220 if (multiplier <= 1.0) {
3221 multiplier = 1.0;
3222 } else if (multiplier <= 2.0) {
3223 if (2 * mFrameCount <= maxNormalFrameCount) {
3224 multiplier = 2.0;
3225 } else {
3226 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
3227 }
3228 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07003229 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08003230 }
3231 }
3232 mNormalFrameCount = multiplier * mFrameCount;
3233 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02003234 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003235 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3236 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003237 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003238 mNormalFrameCount);
3239
Andy Hung08fb1742015-05-31 23:22:10 -07003240 // Check if we want to throttle the processing to no more than 2x normal rate
3241 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003242 mThreadThrottleTimeMs = 0;
3243 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003244 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3245
Andy Hung010a1a12014-03-13 13:57:33 -07003246 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3247 // Originally this was int16_t[] array, need to remove legacy implications.
3248 free(mSinkBuffer);
3249 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003250
Andy Hung5b10a202014-03-13 13:59:29 -07003251 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3252 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3253 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003254 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003255
Andy Hung69aed5f2014-02-25 17:24:40 -08003256 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3257 // drives the output.
3258 free(mMixerBuffer);
3259 mMixerBuffer = NULL;
3260 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003261 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003262 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003263 * audio_bytes_per_sample(mMixerBufferFormat);
3264 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3265 }
Andy Hung98ef9782014-03-04 14:46:50 -08003266 free(mEffectBuffer);
3267 mEffectBuffer = NULL;
3268 if (mEffectBufferEnabled) {
Andy Hung319587b2023-05-23 14:01:03 -07003269 mEffectBufferFormat = AUDIO_FORMAT_PCM_FLOAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003270 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003271 * audio_bytes_per_sample(mEffectBufferFormat);
3272 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3273 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003274
Eric Laurentb62d0362021-10-26 17:40:18 +02003275 if (mType == SPATIALIZER) {
3276 free(mPostSpatializerBuffer);
3277 mPostSpatializerBuffer = nullptr;
3278 mPostSpatializerBufferSize = mNormalFrameCount * mChannelCount
3279 * audio_bytes_per_sample(mEffectBufferFormat);
3280 (void)posix_memalign(&mPostSpatializerBuffer, 32, mPostSpatializerBufferSize);
3281 }
3282
Mikhail Naganov55773032020-10-01 15:08:13 -07003283 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3284 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003285 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3286 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003287 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003288
Eric Laurent81784c32012-11-19 14:55:58 -08003289 // force reconfiguration of effect chains and engines to take new buffer size and audio
3290 // parameters into account
Andy Hung87e82412023-08-29 14:26:09 -07003291 // Note that mutex() is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003292 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3293 // matter.
Andy Hungf79092d2023-08-31 16:13:39 -07003294 // create a copy of mEffectChains as calling moveEffectChain_ll()
3295 // can reorder some effect chains
Andy Hungbd72c542023-06-20 18:56:17 -07003296 Vector<sp<IAfEffectChain>> effectChains = mEffectChains;
Eric Laurent81784c32012-11-19 14:55:58 -08003297 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hungf79092d2023-08-31 16:13:39 -07003298 mAfThreadCallback->moveEffectChain_ll(effectChains[i]->sessionId(),
Eric Laurent6c796322019-04-09 14:13:17 -07003299 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003300 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003301
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003302 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003303 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003304 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung4d693a32023-07-19 12:47:35 -07003305 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003306 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3307 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3308 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3309 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3310 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3311 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3312 (int32_t)mHapticChannelMask)
3313 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3314 (int32_t)mHapticChannelCount)
3315 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung4d693a32023-07-19 12:47:35 -07003316 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungb68f5eb2019-12-03 16:49:17 -08003317 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3318 (int32_t)mFrameCount) // sic - added HAL
3319 ;
3320 uint32_t latencyMs;
3321 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3322 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3323 }
3324 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003325}
3326
Andy Hung71742ab2023-07-07 13:47:37 -07003327ThreadBase::MetadataUpdate PlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07003328{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003329 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01003330 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003331 }
3332 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003333 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07003334 for (const sp<IAfTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -07003335 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent49e39282022-06-24 18:42:45 +02003336 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07003337 }
Kevin Rocard12381092018-04-11 09:19:59 -07003338 sendMetadataToBackend_l(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01003339 MetadataUpdate change;
3340 change.playbackMetadataUpdate = metadata.tracks;
3341 return change;
Kevin Rocard80ee2722018-04-11 15:53:48 +00003342}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003343
Andy Hung71742ab2023-07-07 13:47:37 -07003344void PlaybackThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07003345 const StreamOutHalInterface::SourceMetadata& metadata)
3346{
3347 mOutput->stream->updateSourceMetadata(metadata);
3348};
3349
Andy Hung71742ab2023-07-07 13:47:37 -07003350status_t PlaybackThread::getRenderPosition(
Andy Hung4989d312023-06-29 21:19:25 -07003351 uint32_t* halFrames, uint32_t* dspFrames) const
Eric Laurent81784c32012-11-19 14:55:58 -08003352{
3353 if (halFrames == NULL || dspFrames == NULL) {
3354 return BAD_VALUE;
3355 }
Andy Hungf79092d2023-08-31 16:13:39 -07003356 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003357 if (initCheck() != NO_ERROR) {
3358 return INVALID_OPERATION;
3359 }
Andy Hung818e7a32016-02-16 18:08:07 -08003360 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003361 *halFrames = framesWritten;
3362
3363 if (isSuspended()) {
3364 // return an estimation of rendered frames when the output is suspended
3365 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003366 *dspFrames = (uint32_t)
3367 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003368 return NO_ERROR;
3369 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003370 status_t status;
3371 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003372 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003373 *dspFrames = (size_t)frames;
3374 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003375 }
3376}
3377
Andy Hung71742ab2023-07-07 13:47:37 -07003378product_strategy_t PlaybackThread::getStrategyForSession_l(audio_session_t sessionId) const
Eric Laurent81784c32012-11-19 14:55:58 -08003379{
3380 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3381 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3382 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003383 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003384 }
3385 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003386 sp<IAfTrack> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003387 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003388 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003389 }
3390 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003391 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003392}
3393
3394
Andy Hung71742ab2023-07-07 13:47:37 -07003395AudioStreamOut* PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003396{
Andy Hungf79092d2023-08-31 16:13:39 -07003397 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003398 return mOutput;
3399}
3400
Andy Hung71742ab2023-07-07 13:47:37 -07003401AudioStreamOut* PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003402{
Andy Hungf79092d2023-08-31 16:13:39 -07003403 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003404 AudioStreamOut *output = mOutput;
3405 mOutput = NULL;
3406 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3407 // must push a NULL and wait for ack
3408 mOutputSink.clear();
3409 mPipeSink.clear();
3410 mNormalSink.clear();
3411 return output;
3412}
3413
Andy Hung87e82412023-08-29 14:26:09 -07003414// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07003415sp<StreamHalInterface> PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003416{
3417 if (mOutput == NULL) {
3418 return NULL;
3419 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003420 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003421}
3422
Andy Hung71742ab2023-07-07 13:47:37 -07003423uint32_t PlaybackThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08003424{
3425 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3426}
3427
Andy Hung71742ab2023-07-07 13:47:37 -07003428status_t PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08003429{
3430 if (!isValidSyncEvent(event)) {
3431 return BAD_VALUE;
3432 }
3433
Andy Hungf79092d2023-08-31 16:13:39 -07003434 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003435
3436 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003437 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003438 if (event->triggerSession() == track->sessionId()) {
3439 (void) track->setSyncEvent(event);
3440 return NO_ERROR;
3441 }
3442 }
3443
3444 return NAME_NOT_FOUND;
3445}
3446
Andy Hung71742ab2023-07-07 13:47:37 -07003447bool PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
Eric Laurent81784c32012-11-19 14:55:58 -08003448{
3449 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3450}
3451
Andy Hung71742ab2023-07-07 13:47:37 -07003452void PlaybackThread::threadLoop_removeTracks(
Andy Hung3ff4b552023-06-26 19:20:57 -07003453 [[maybe_unused]] const Vector<sp<IAfTrack>>& tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08003454{
Andy Hungfe726a62018-09-27 15:17:25 -07003455 // Miscellaneous track cleanup when removed from the active list,
3456 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003457#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003458 for (const auto& track : tracksToRemove) {
3459 if (track->isExternalTrack()) {
3460 // to track the speaker usage
3461 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003462 }
3463 }
Andy Hungfe726a62018-09-27 15:17:25 -07003464#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003465}
3466
Andy Hung71742ab2023-07-07 13:47:37 -07003467void PlaybackThread::checkSilentMode_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003468{
3469 if (!mMasterMute) {
3470 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003471 if (mOutDeviceTypeAddrs.empty()) {
3472 ALOGD("ro.audio.silent is ignored since no output device is set");
3473 return;
3474 }
jiabinc52b1ff2019-10-31 17:20:42 -07003475 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003476 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3477 return;
3478 }
Eric Laurent81784c32012-11-19 14:55:58 -08003479 if (property_get("ro.audio.silent", value, "0") > 0) {
3480 char *endptr;
3481 unsigned long ul = strtoul(value, &endptr, 0);
3482 if (*endptr == '\0' && ul != 0) {
3483 ALOGD("Silence is golden");
3484 // The setprop command will not allow a property to be changed after
3485 // the first time it is set, so we don't have to worry about un-muting.
3486 setMasterMute_l(true);
3487 }
3488 }
3489 }
3490}
3491
3492// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07003493ssize_t PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003494{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003495 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003496 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003498 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003499
3500 // If an NBAIO sink is present, use it to write the normal mixer's submix
3501 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003502
Andy Hung010a1a12014-03-13 13:57:33 -07003503 const size_t count = mBytesRemaining / mFrameSize;
3504
Simon Wilson2d590962012-11-29 15:18:50 -08003505 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003506 // update the setpoint when AudioFlinger::mScreenState changes
Andy Hung01b29482023-07-19 16:22:58 -07003507 const uint32_t screenState = mAfThreadCallback->getScreenState();
Eric Laurent81784c32012-11-19 14:55:58 -08003508 if (screenState != mScreenState) {
3509 mScreenState = screenState;
3510 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3511 if (pipe != NULL) {
3512 pipe->setAvgFrames((mScreenState & 1) ?
3513 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3514 }
3515 }
Andy Hung010a1a12014-03-13 13:57:33 -07003516 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003517 ATRACE_END();
Vlad Popab042ee62022-10-20 18:05:00 +02003518
Eric Laurent81784c32012-11-19 14:55:58 -08003519 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003520 bytesWritten = framesWritten * mFrameSize;
Andy Hung58e32872022-11-15 16:12:24 -08003521
Andy Hung8946a282018-04-19 20:04:56 -07003522#ifdef TEE_SINK
3523 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3524#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003525 } else {
3526 bytesWritten = framesWritten;
3527 }
3528 // otherwise use the HAL / AudioStreamOut directly
3529 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003530 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003531
Eric Laurentbfb1b832013-01-07 09:53:42 -08003532 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003533 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3534 mWriteAckSequence += 2;
3535 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003536 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003537 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003538 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003539 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003540 // FIXME We should have an implementation of timestamps for direct output threads.
3541 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003542 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003543 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003544
Eric Laurentbfb1b832013-01-07 09:53:42 -08003545 if (mUseAsyncWrite &&
3546 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3547 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003548 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003549 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003550 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003551 }
Eric Laurent81784c32012-11-19 14:55:58 -08003552 }
3553
Eric Laurent81784c32012-11-19 14:55:58 -08003554 mNumWrites++;
3555 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003556 if (mStandby) {
3557 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07003558 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07003559 mStandby = false;
3560 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003561 return bytesWritten;
3562}
3563
Andy Hung87e82412023-08-29 14:26:09 -07003564// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07003565void PlaybackThread::startMelComputation_l(
Vlad Popaf09e93f2022-10-31 16:27:12 +01003566 const sp<audio_utils::MelProcessor>& processor)
Vlad Popab042ee62022-10-20 18:05:00 +02003567{
Vlad Popa3c7a2662023-02-14 20:09:47 +01003568 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003569 if (outputSink != nullptr) {
3570 outputSink->startMelComputation(processor);
3571 }
Vlad Popab042ee62022-10-20 18:05:00 +02003572}
3573
Andy Hung87e82412023-08-29 14:26:09 -07003574// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07003575void PlaybackThread::stopMelComputation_l()
Vlad Popa3c7a2662023-02-14 20:09:47 +01003576{
3577 auto outputSink = static_cast<AudioStreamOutSink*>(mOutputSink.get());
Vlad Popa1a0c3ab2023-03-17 01:07:01 +01003578 if (outputSink != nullptr) {
3579 outputSink->stopMelComputation();
3580 }
Vlad Popab042ee62022-10-20 18:05:00 +02003581}
3582
Andy Hung71742ab2023-07-07 13:47:37 -07003583void PlaybackThread::threadLoop_drain()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003584{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003585 bool supportsDrain = false;
3586 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003587 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3588 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003589 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3590 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003591 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003592 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003593 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003594 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003595 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003596 }
3597}
3598
Andy Hung71742ab2023-07-07 13:47:37 -07003599void PlaybackThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08003600{
Eric Laurent275e8e92014-11-30 15:14:47 -08003601 {
Andy Hungf79092d2023-08-31 16:13:39 -07003602 audio_utils::lock_guard _l(mutex());
Eric Laurent275e8e92014-11-30 15:14:47 -08003603 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003604 sp<IAfTrack> track = mTracks[i];
Eric Laurent275e8e92014-11-30 15:14:47 -08003605 track->invalidate();
3606 }
Andy Hungdae27702016-10-31 14:01:16 -07003607 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3608 // After we exit there are no more track changes sent to BatteryNotifier
3609 // because that requires an active threadLoop.
3610 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3611 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003612 }
Eric Laurent81784c32012-11-19 14:55:58 -08003613}
3614
3615/*
3616The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003617 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003618 - mActiveSleepTimeUs from activeSleepTimeUs()
3619 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003620 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3621 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003622 - maxPeriod from frame count and sample rate (MIXER only)
3623
3624The parameters that affect these derived values are:
3625 - frame count
3626 - frame size
3627 - sample rate
3628 - device type: A2DP or not
3629 - device latency
3630 - format: PCM or not
3631 - active sleep time
3632 - idle sleep time
3633*/
3634
Andy Hung71742ab2023-07-07 13:47:37 -07003635void PlaybackThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08003636{
Andy Hung25c2dac2014-02-27 14:56:00 -08003637 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003638 mActiveSleepTimeUs = activeSleepTimeUs();
3639 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003640
Andy Hung18bef9b2023-07-20 21:31:38 -07003641 mStandbyDelayNs = getStandbyTimeInNanos();
Carter Hsu0ca47c22023-06-02 18:01:45 +08003642
Eric Laurent42537be2016-01-08 17:16:42 -08003643 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3644 // truncating audio when going to standby.
jiabinc52b1ff2019-10-31 17:20:42 -07003645 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003646 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3647 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3648 }
3649 }
Eric Laurent81784c32012-11-19 14:55:58 -08003650}
3651
Andy Hung71742ab2023-07-07 13:47:37 -07003652bool PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003653{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003654 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003655 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003656 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003657 size_t size = mTracks.size();
3658 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003659 sp<IAfTrack> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003660 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003661 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003662 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003663 }
3664 }
Eric Laurent13084622016-05-17 10:51:49 -07003665 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003666}
3667
Andy Hung71742ab2023-07-07 13:47:37 -07003668void PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07003669{
Andy Hungf79092d2023-08-31 16:13:39 -07003670 audio_utils::lock_guard _l(mutex());
Haynes Mathew George05317d22016-05-03 16:34:26 -07003671 invalidateTracks_l(streamType);
3672}
3673
Andy Hung71742ab2023-07-07 13:47:37 -07003674void PlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf79092d2023-08-31 16:13:39 -07003675 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08003676 invalidateTracks_l(portIds);
3677}
3678
Andy Hung71742ab2023-07-07 13:47:37 -07003679bool PlaybackThread::invalidateTracks_l(std::set<audio_port_handle_t>& portIds) {
jiabinc44b3462022-12-08 12:52:31 -08003680 bool trackMatch = false;
3681 const size_t size = mTracks.size();
3682 for (size_t i = 0; i < size; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003683 sp<IAfTrack> t = mTracks[i];
jiabinc44b3462022-12-08 12:52:31 -08003684 if (t->isExternalTrack() && portIds.find(t->portId()) != portIds.end()) {
3685 t->invalidate();
3686 portIds.erase(t->portId());
3687 trackMatch = true;
3688 }
3689 if (portIds.empty()) {
3690 break;
3691 }
3692 }
3693 return trackMatch;
3694}
3695
jiabinf042b9b2021-05-07 23:46:28 +00003696// getTrackById_l must be called with holding thread lock
Andy Hung71742ab2023-07-07 13:47:37 -07003697IAfTrack* PlaybackThread::getTrackById_l(
jiabinf042b9b2021-05-07 23:46:28 +00003698 audio_port_handle_t trackPortId) {
3699 for (size_t i = 0; i < mTracks.size(); i++) {
3700 if (mTracks[i]->portId() == trackPortId) {
3701 return mTracks[i].get();
3702 }
3703 }
3704 return nullptr;
3705}
3706
Andy Hung71742ab2023-07-07 13:47:37 -07003707status_t PlaybackThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003708{
Glenn Kastend848eb42016-03-08 13:42:11 -08003709 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003710 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Andy Hung319587b2023-05-23 14:01:03 -07003711 float *buffer = nullptr; // only used for non global sessions
Eric Laurentb62d0362021-10-26 17:40:18 +02003712
Andy Hungd3639922022-04-28 18:00:49 -07003713 if (mType == SPATIALIZER) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003714 if (!audio_is_global_session(session)) {
3715 // player sessions on a spatializer output will use a dedicated input buffer and
3716 // will either output multi channel to mEffectBuffer if the track is spatilaized
3717 // or stereo to mPostSpatializerBuffer if not spatialized.
3718 uint32_t channelMask;
3719 bool isSessionSpatialized =
3720 (hasAudioSession_l(session) & ThreadBase::SPATIALIZED_SESSION) != 0;
3721 if (isSessionSpatialized) {
3722 channelMask = mMixerChannelMask;
3723 } else {
3724 channelMask = mChannelMask;
3725 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02003726 size_t numSamples = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02003727 * (audio_channel_count_from_out_mask(channelMask) + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003728 status_t result = mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003729 numSamples * sizeof(float),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003730 &halInBuffer);
3731 if (result != OK) return result;
Eric Laurentb62d0362021-10-26 17:40:18 +02003732
Andy Hung2cbc2722023-07-17 17:05:00 -07003733 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003734 isSessionSpatialized ? mEffectBuffer : mPostSpatializerBuffer,
3735 isSessionSpatialized ? mEffectBufferSize : mPostSpatializerBufferSize,
3736 &halOutBuffer);
3737 if (result != OK) return result;
3738
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003739 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Andy Hung26836922023-05-22 17:31:57 -07003740
Mikhail Naganov022b9952017-01-04 16:36:51 -08003741 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3742 buffer, session);
Eric Laurentb62d0362021-10-26 17:40:18 +02003743 } else {
3744 // A global session on a SPATIALIZER thread is either OUTPUT_STAGE or DEVICE
3745 // - OUTPUT_STAGE session uses the mEffectBuffer as input buffer and
3746 // mPostSpatializerBuffer as output buffer
3747 // - DEVICE session uses the mPostSpatializerBuffer as input and output buffer.
Andy Hung2cbc2722023-07-17 17:05:00 -07003748 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003749 mEffectBuffer, mEffectBufferSize, &halInBuffer);
3750 if (result != OK) return result;
Andy Hung2cbc2722023-07-17 17:05:00 -07003751 result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003752 mPostSpatializerBuffer, mPostSpatializerBufferSize, &halOutBuffer);
3753 if (result != OK) return result;
Eric Laurent81784c32012-11-19 14:55:58 -08003754
Eric Laurentb62d0362021-10-26 17:40:18 +02003755 if (session == AUDIO_SESSION_DEVICE) {
3756 halInBuffer = halOutBuffer;
3757 }
3758 }
3759 } else {
Andy Hung2cbc2722023-07-17 17:05:00 -07003760 status_t result = mAfThreadCallback->getEffectsFactoryHal()->mirrorBuffer(
Eric Laurentb62d0362021-10-26 17:40:18 +02003761 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3762 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3763 &halInBuffer);
3764 if (result != OK) return result;
3765 halOutBuffer = halInBuffer;
3766 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
3767 if (!audio_is_global_session(session)) {
Andy Hung319587b2023-05-23 14:01:03 -07003768 buffer = halInBuffer ? reinterpret_cast<float*>(halInBuffer->externalData())
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003769 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003770 // Only one effect chain can be present in direct output thread and it uses
3771 // the sink buffer as input
3772 if (mType != DIRECT) {
3773 size_t numSamples = mNormalFrameCount
3774 * (audio_channel_count_from_out_mask(mMixerChannelMask)
3775 + mHapticChannelCount);
Andy Hung2cbc2722023-07-17 17:05:00 -07003776 const status_t allocateStatus =
3777 mAfThreadCallback->getEffectsFactoryHal()->allocateBuffer(
Andy Hung319587b2023-05-23 14:01:03 -07003778 numSamples * sizeof(float),
Eric Laurentb62d0362021-10-26 17:40:18 +02003779 &halInBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07003780 if (allocateStatus != OK) return allocateStatus;
Andy Hung26836922023-05-22 17:31:57 -07003781
Shunkai Yao44bdbad2023-01-14 05:11:58 +00003782 buffer = halInBuffer ? halInBuffer->audioBuffer()->f32 : buffer;
Eric Laurentb62d0362021-10-26 17:40:18 +02003783 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3784 buffer, session);
3785 }
3786 }
3787 }
3788
3789 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003790 // Attach all tracks with same session ID to this chain.
3791 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003792 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003793 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003794 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p",
3795 track.get(), buffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003796 track->setMainBuffer(buffer);
3797 chain->incTrackCnt();
3798 }
3799 }
3800
3801 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003802 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003803 if (session == track->sessionId()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02003804 ALOGV("addEffectChain_l() activating track %p on session %d",
3805 track.get(), session);
Eric Laurent81784c32012-11-19 14:55:58 -08003806 chain->incActiveTrackCnt();
3807 }
3808 }
3809 }
Eric Laurentb62d0362021-10-26 17:40:18 +02003810
Eric Laurentaaa44472014-09-12 17:41:50 -07003811 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003812 chain->setInBuffer(halInBuffer);
3813 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003814 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3815 // chains list in order to be processed last as it contains output device effects.
3816 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3817 // processing effects specific to an output stream before effects applied to all streams
3818 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003819 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3820 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003821 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003822 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003823 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003824 // Effect chain for other sessions are inserted at beginning of effect
3825 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003826 // sessions is not important.
3827 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003828 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3829 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003830 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003831 size_t size = mEffectChains.size();
3832 size_t i = 0;
3833 for (i = 0; i < size; i++) {
3834 if (mEffectChains[i]->sessionId() < session) {
3835 break;
3836 }
3837 }
3838 mEffectChains.insertAt(chain, i);
3839 checkSuspendOnAddEffectChain_l(chain);
3840
3841 return NO_ERROR;
3842}
3843
Andy Hung71742ab2023-07-07 13:47:37 -07003844size_t PlaybackThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08003845{
Glenn Kastend848eb42016-03-08 13:42:11 -08003846 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003847
3848 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3849
3850 for (size_t i = 0; i < mEffectChains.size(); i++) {
3851 if (chain == mEffectChains[i]) {
3852 mEffectChains.removeAt(i);
3853 // detach all active tracks from the chain
Andy Hung3ff4b552023-06-26 19:20:57 -07003854 for (const sp<IAfTrack>& track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003855 if (session == track->sessionId()) {
3856 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3857 chain.get(), session);
3858 chain->decActiveTrackCnt();
3859 }
3860 }
3861
3862 // detach all tracks with same session ID from this chain
Andy Hung71ba4b32022-10-06 12:09:49 -07003863 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003864 sp<IAfTrack> track = mTracks[j];
Eric Laurent81784c32012-11-19 14:55:58 -08003865 if (session == track->sessionId()) {
Andy Hung319587b2023-05-23 14:01:03 -07003866 track->setMainBuffer(reinterpret_cast<float*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003867 chain->decTrackCnt();
3868 }
3869 }
3870 break;
3871 }
3872 }
3873 return mEffectChains.size();
3874}
3875
Andy Hung71742ab2023-07-07 13:47:37 -07003876status_t PlaybackThread::attachAuxEffect(
Andy Hung3ff4b552023-06-26 19:20:57 -07003877 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003878{
Andy Hungf79092d2023-08-31 16:13:39 -07003879 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08003880 return attachAuxEffect_l(track, EffectId);
3881}
3882
Andy Hung71742ab2023-07-07 13:47:37 -07003883status_t PlaybackThread::attachAuxEffect_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07003884 const sp<IAfTrack>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003885{
3886 status_t status = NO_ERROR;
3887
3888 if (EffectId == 0) {
3889 track->setAuxBuffer(0, NULL);
3890 } else {
3891 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
Andy Hungbd72c542023-06-20 18:56:17 -07003892 sp<IAfEffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
Eric Laurent81784c32012-11-19 14:55:58 -08003893 if (effect != 0) {
3894 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3895 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3896 } else {
3897 status = INVALID_OPERATION;
3898 }
3899 } else {
3900 status = BAD_VALUE;
3901 }
3902 }
3903 return status;
3904}
3905
Andy Hung71742ab2023-07-07 13:47:37 -07003906void PlaybackThread::detachAuxEffect_l(int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003907{
3908 for (size_t i = 0; i < mTracks.size(); ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07003909 sp<IAfTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08003910 if (track->auxEffectId() == effectId) {
3911 attachAuxEffect_l(track, 0);
3912 }
3913 }
3914}
3915
Andy Hung71742ab2023-07-07 13:47:37 -07003916bool PlaybackThread::threadLoop()
Andy Hung71ba4b32022-10-06 12:09:49 -07003917NO_THREAD_SAFETY_ANALYSIS // manual locking of AudioFlinger
Eric Laurent81784c32012-11-19 14:55:58 -08003918{
Andy Hung4bf583b2023-05-30 18:10:23 -07003919 aflog::setThreadWriter(mNBLogWriter.get());
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003920
Andy Hungb001e132023-10-03 10:49:34 -07003921 if (mType == SPATIALIZER) {
3922 const pid_t tid = getTid();
3923 if (tid == -1) { // odd: we are here, we must be a running thread.
3924 ALOGW("%s: Cannot update Spatializer mixer thread priority, no tid", __func__);
3925 } else {
3926 const int priorityBoost = requestSpatializerPriority(getpid(), tid);
3927 if (priorityBoost > 0) {
3928 stream()->setHalThreadPriority(priorityBoost);
3929 }
3930 }
3931 }
3932
Andy Hung3ff4b552023-06-26 19:20:57 -07003933 Vector<sp<IAfTrack>> tracksToRemove;
Eric Laurent81784c32012-11-19 14:55:58 -08003934
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003935 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003936 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003937
3938 // MIXER
3939 nsecs_t lastWarning = 0;
3940
3941 // DUPLICATING
3942 // FIXME could this be made local to while loop?
3943 writeFrames = 0;
3944
3945 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003946 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003947
Andy Hungd3639922022-04-28 18:00:49 -07003948 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08003949 sleepTimeShift = 0;
3950 }
3951
3952 CpuStats cpuStats;
3953 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3954
3955 acquireWakeLock();
3956
Glenn Kasteneef598c2017-04-03 14:41:13 -07003957 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3958 // thread associated with this PlaybackThread.
3959 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3960 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003961 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3962 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003963 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003964 const char *logString = NULL;
3965
rago1bb90822017-05-02 18:31:48 -07003966 // Estimated time for next buffer to be written to hal. This is used only on
3967 // suspended mode (for now) to help schedule the wait time until next iteration.
3968 nsecs_t timeLoopNextNs = 0;
3969
Eric Laurent664539d2013-09-23 18:24:31 -07003970 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003971
Andy Hung2dbffc22018-08-08 18:50:41 -07003972 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003973
Eric Laurentb3f315a2021-07-13 15:09:05 +02003974 sendCheckOutputStageEffectsEvent();
3975
Andy Hung446f4df2019-02-21 12:26:41 -08003976 // loopCount is used for statistics and diagnostics.
3977 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003978 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003979 // Log merge requests are performed during AudioFlinger binder transactions, but
3980 // that does not cover audio playback. It's requested here for that reason.
Andy Hung2cbc2722023-07-17 17:05:00 -07003981 mAfThreadCallback->requestLogMerge();
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003982
Eric Laurent81784c32012-11-19 14:55:58 -08003983 cpuStats.sample(myName);
3984
Andy Hungbd72c542023-06-20 18:56:17 -07003985 Vector<sp<IAfEffectChain>> effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003986 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Eric Laurentb62d0362021-10-26 17:40:18 +02003987 bool isHapticSessionSpatialized = false;
Andy Hung3ff4b552023-06-26 19:20:57 -07003988 std::vector<sp<IAfTrack>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003989
Andy Hung2dbffc22018-08-08 18:50:41 -07003990 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3991 //
Andy Hung87e82412023-08-29 14:26:09 -07003992 // Note: we access outDeviceTypes() outside of mutex().
jiabinc52b1ff2019-10-31 17:20:42 -07003993 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003994 // Here, we try for the AF lock, but do not block on it as the latency
3995 // is more informational.
Andy Hung2ac52f12023-08-28 18:36:53 -07003996 if (mAfThreadCallback->mutex().try_lock()) {
Andy Hungd63e79d2023-07-13 16:52:46 -07003997 std::vector<SoftwarePatch> swPatches;
Andy Hung71ba4b32022-10-06 12:09:49 -07003998 double latencyMs = 0.; // not required; initialized for clang-tidy
Andy Hung2dbffc22018-08-08 18:50:41 -07003999 status_t status = INVALID_OPERATION;
4000 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hung2cbc2722023-07-17 17:05:00 -07004001 if (mAfThreadCallback->getPatchPanel()->getDownstreamSoftwarePatches(
Andy Hungd63e79d2023-07-13 16:52:46 -07004002 id(), &swPatches) == OK
Andy Hung2dbffc22018-08-08 18:50:41 -07004003 && swPatches.size() > 0) {
4004 status = swPatches[0].getLatencyMs_l(&latencyMs);
4005 downstreamPatchHandle = swPatches[0].getPatchHandle();
4006 }
4007 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11004008 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004009 lastDownstreamPatchHandle = downstreamPatchHandle;
4010 }
4011 if (status == OK) {
4012 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08004013 // latency of 5 seconds).
4014 const double minLatency = 0., maxLatency = 5000.;
4015 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10004016 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004017 } else {
4018 ALOGD("out of range downstream latency %lf ms", latencyMs);
Andy Hung71ba4b32022-10-06 12:09:49 -07004019 latencyMs = std::clamp(latencyMs, minLatency, maxLatency);
Andy Hung2dbffc22018-08-08 18:50:41 -07004020 }
Dean Wheatley30d28422018-11-06 10:27:40 +11004021 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07004022 }
Andy Hung2cbc2722023-07-17 17:05:00 -07004023 mAfThreadCallback->mutex().unlock();
Andy Hung2dbffc22018-08-08 18:50:41 -07004024 }
4025 } else {
4026 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
4027 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11004028 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07004029 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4030 }
4031 }
4032
Eric Laurentb3f315a2021-07-13 15:09:05 +02004033 if (mCheckOutputStageEffects.exchange(false)) {
4034 checkOutputStageEffects();
4035 }
4036
Vlad Popa7e81cea2023-01-19 16:34:16 +01004037 MetadataUpdate metadataUpdate;
Andy Hung87e82412023-08-29 14:26:09 -07004038 { // scope for mutex()
Eric Laurent81784c32012-11-19 14:55:58 -08004039
Andy Hung87e82412023-08-29 14:26:09 -07004040 audio_utils::unique_lock _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08004041
Eric Laurent021cf962014-05-13 10:18:14 -07004042 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02004043 if (mCheckOutputStageEffects.load()) {
4044 continue;
4045 }
Eric Laurent10351942014-05-08 18:49:52 -07004046
Andy Hung87e82412023-08-29 14:26:09 -07004047 // See comment at declaration of logString for why this is done under mutex()
Glenn Kasten9e58b552013-01-18 15:09:48 -08004048 if (logString != NULL) {
4049 mNBLogWriter->logTimestamp();
4050 mNBLogWriter->log(logString);
4051 logString = NULL;
4052 }
4053
Dean Wheatley12473e92021-03-18 23:00:55 +11004054 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07004055
Eric Laurent81784c32012-11-19 14:55:58 -08004056 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004057 if (mSignalPending) {
4058 // A signal was raised while we were unlocked
4059 mSignalPending = false;
4060 } else if (waitingAsyncCallback_l()) {
4061 if (exitPending()) {
4062 break;
4063 }
Marco Nelissen078538c2015-05-12 09:17:57 -07004064 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07004065 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07004066 releaseWakeLock_l();
4067 released = true;
4068 }
Andy Hung10cbff12017-02-21 17:30:14 -08004069
4070 const int64_t waitNs = computeWaitTimeNs_l();
4071 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
Andy Hung87e82412023-08-29 14:26:09 -07004072 std::cv_status cvstatus =
4073 mWaitWorkCV.wait_for(_l, std::chrono::nanoseconds(waitNs));
4074 if (cvstatus == std::cv_status::timeout) {
Andy Hung10cbff12017-02-21 17:30:14 -08004075 mSignalPending = true; // if timeout recheck everything
4076 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004077 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07004078 if (released) {
4079 acquireWakeLock_l();
4080 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004081 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4082 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07004083
4084 continue;
4085 }
Eric Tan39ec8d62018-07-24 09:49:29 -07004086 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08004087 isSuspended()) {
4088 // put audio hardware into standby after short delay
4089 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004090
4091 threadLoop_standby();
4092
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004093 // This is where we go into standby
4094 if (!mStandby) {
4095 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07004096 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07004097 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02004098 setStandby_l();
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07004099 }
Andy Hungd0979812019-02-21 15:51:44 -08004100 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08004101 }
4102
Eric Tan39ec8d62018-07-24 09:49:29 -07004103 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004104 // we're about to wait, flush the binder command buffer
4105 IPCThreadState::self()->flushCommands();
4106
4107 clearOutputTracks();
4108
4109 if (exitPending()) {
4110 break;
4111 }
4112
4113 releaseWakeLock_l();
4114 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004115 ALOGV("%s going to sleep", myName.c_str());
Andy Hung87e82412023-08-29 14:26:09 -07004116 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00004117 ALOGV("%s waking up", myName.c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08004118 acquireWakeLock_l();
4119
4120 mMixerStatus = MIXER_IDLE;
4121 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
4122 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004123 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004124 checkSilentMode_l();
4125
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004126 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
4127 mSleepTimeUs = mIdleSleepTimeUs;
Andy Hungd3639922022-04-28 18:00:49 -07004128 if (mType == MIXER || mType == SPATIALIZER) {
Eric Laurent81784c32012-11-19 14:55:58 -08004129 sleepTimeShift = 0;
4130 }
4131
4132 continue;
4133 }
4134 }
Eric Laurent81784c32012-11-19 14:55:58 -08004135 // mMixerStatusIgnoringFastTracks is also updated internally
4136 mMixerStatus = prepareTracks_l(&tracksToRemove);
4137
Andy Hungdae27702016-10-31 14:01:16 -07004138 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08004139
Vlad Popa7e81cea2023-01-19 16:34:16 +01004140 metadataUpdate = updateMetadata_l();
Kevin Rocard069c2712018-03-29 19:09:14 -07004141
Eric Laurent81784c32012-11-19 14:55:58 -08004142 // prevent any changes in effect chain list and in each effect chain
4143 // during mixing and effect process as the audio buffers could be deleted
4144 // or modified if an effect is created or deleted
4145 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07004146
4147 // Determine which session to pick up haptic data.
4148 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07004149 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004150 // TODO: Write haptic data directly to sink buffer when mixing.
Eric Laurentb62d0362021-10-26 17:40:18 +02004151 if (mHapticChannelCount > 0) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004152 for (const auto& track : mActiveTracks) {
Andy Hungbd72c542023-06-20 18:56:17 -07004153 sp<IAfEffectChain> effectChain = getEffectChain_l(track->sessionId());
Eric Laurentb62d0362021-10-26 17:40:18 +02004154 if (effectChain != nullptr
4155 && effectChain->containsHapticGeneratingEffect_l()) {
jiabineb3bda02020-06-30 14:07:03 -07004156 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004157 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004158 mType == SPATIALIZER && track->isSpatialized();
jiabineb3bda02020-06-30 14:07:03 -07004159 break;
4160 }
Eric Laurentb62d0362021-10-26 17:40:18 +02004161 if (activeHapticSessionId == AUDIO_SESSION_NONE
4162 && track->getHapticPlaybackEnabled()) {
Andy Hung6e6a2e62019-04-30 16:38:41 -07004163 activeHapticSessionId = track->sessionId();
Eric Laurentb62d0362021-10-26 17:40:18 +02004164 isHapticSessionSpatialized =
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004165 mType == SPATIALIZER && track->isSpatialized();
Andy Hung6e6a2e62019-04-30 16:38:41 -07004166 }
4167 }
4168 }
4169
Andy Hungc1646382019-04-30 16:12:10 -07004170 // Acquire a local copy of active tracks with lock (release w/o lock).
4171 //
4172 // Control methods on the track acquire the ThreadBase lock (e.g. start()
4173 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
4174 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
4175 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Eric Laurent6f9534f2022-05-03 18:15:04 +02004176
4177 setHalLatencyMode_l();
Eric Laurent19952e12023-04-20 10:08:29 +02004178
Jiabin Huangfb476842022-12-06 03:18:10 +00004179 for (const auto &track : mActiveTracks ) {
4180 track->updateTeePatches();
4181 }
4182
Eric Laurent19952e12023-04-20 10:08:29 +02004183 // signal actual start of output stream when the render position reported by the kernel
4184 // starts moving.
Eric Laurent4edbd8c2023-05-22 17:00:24 +02004185 if (!mHalStarted && ((isSuspended() && (mBytesWritten != 0)) || (!mStandby
4186 && (mKernelPositionOnStandby
4187 != mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL])))) {
Eric Laurent19952e12023-04-20 10:08:29 +02004188 mHalStarted = true;
Andy Hung87e82412023-08-29 14:26:09 -07004189 mWaitHalStartCV.notify_all();
Eric Laurent19952e12023-04-20 10:08:29 +02004190 }
Andy Hung87e82412023-08-29 14:26:09 -07004191 } // mutex() scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08004192
Eric Laurentbfb1b832013-01-07 09:53:42 -08004193 if (mBytesRemaining == 0) {
4194 mCurrentWriteLength = 0;
4195 if (mMixerStatus == MIXER_TRACKS_READY) {
4196 // threadLoop_mix() sets mCurrentWriteLength
4197 threadLoop_mix();
4198 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
4199 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004200 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08004201 // must be written to HAL
4202 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004203 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08004204 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07004205
4206 // Tally underrun frames as we are inserting 0s here.
4207 for (const auto& track : activeTracks) {
Andy Hung3ff4b552023-06-26 19:20:57 -07004208 if (track->fillingStatus() == IAfTrack::FS_ACTIVE
Andy Hunge2e830f2019-12-03 12:54:46 -08004209 && !track->isStopped()
4210 && !track->isPaused()
4211 && !track->isTerminated()) {
4212 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
4213 __func__, track->id(), track->getTrackStateAsString(),
4214 mNormalFrameCount);
Andy Hung3ff4b552023-06-26 19:20:57 -07004215 track->audioTrackServerProxy()->tallyUnderrunFrames(
4216 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07004217 }
4218 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004219 }
4220 }
Andy Hung98ef9782014-03-04 14:46:50 -08004221 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004222 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08004223 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
jiabinc658e452022-10-21 20:52:21 +00004224 // or mSinkBuffer (if there are no effects and there is no data already copied to
4225 // mSinkBuffer).
Andy Hung98ef9782014-03-04 14:46:50 -08004226 //
4227 // This is done pre-effects computation; if effects change to
4228 // support higher precision, this needs to move.
4229 //
4230 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004231 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02004232 uint32_t mixerChannelCount = mEffectBufferValid ?
4233 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
jiabinc658e452022-10-21 20:52:21 +00004234 if (mMixerBufferValid && (mEffectBufferValid || !mHasDataCopiedToSinkBuffer)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004235 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
4236 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
4237
David Li88ee0902022-06-22 10:01:21 +08004238 // Apply mono blending and balancing if the effect buffer is not valid. Otherwise,
4239 // do these processes after effects are applied.
4240 if (!mEffectBufferValid) {
4241 // mono blend occurs for mixer threads only (not direct or offloaded)
4242 // and is handled here if we're going directly to the sink.
4243 if (requireMonoBlend()) {
4244 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount,
4245 mNormalFrameCount, true /*limit*/);
4246 }
Andy Hung2ddee192015-12-18 17:34:44 -08004247
David Li88ee0902022-06-22 10:01:21 +08004248 if (!hasFastMixer()) {
4249 // Balance must take effect after mono conversion.
4250 // We do it here if there is no FastMixer.
4251 // mBalance detects zero balance within the class for speed
4252 // (not needed here).
4253 mBalance.setBalance(mMasterBalance.load());
4254 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
4255 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004256 }
4257
Andy Hung98ef9782014-03-04 14:46:50 -08004258 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02004259 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08004260
4261 // If we're going directly to the sink and there are haptic channels,
4262 // we should adjust channels as the sample data is partially interleaved
4263 // in this case.
4264 if (!mEffectBufferValid && mHapticChannelCount > 0) {
4265 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
4266 mChannelCount + mHapticChannelCount,
4267 audio_bytes_per_sample(format),
4268 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
4269 }
Andy Hung98ef9782014-03-04 14:46:50 -08004270 }
4271
Eric Laurentbfb1b832013-01-07 09:53:42 -08004272 mBytesRemaining = mCurrentWriteLength;
4273 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07004274 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
4275 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
4276 const size_t framesRemaining = mBytesRemaining / mFrameSize;
4277 mBytesWritten += mBytesRemaining;
4278 mFramesWritten += framesRemaining;
4279 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08004280 mBytesRemaining = 0;
4281 }
Eric Laurent81784c32012-11-19 14:55:58 -08004282
Eric Laurentbfb1b832013-01-07 09:53:42 -08004283 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004284 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004285 for (size_t i = 0; i < effectChains.size(); i ++) {
4286 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07004287 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07004288 if (activeHapticSessionId != AUDIO_SESSION_NONE
4289 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07004290 // Haptic data is active in this case, copy it directly from
4291 // in buffer to out buffer.
Eric Laurentb62d0362021-10-26 17:40:18 +02004292 uint32_t hapticSessionChannelCount = mEffectBufferValid ?
4293 audio_channel_count_from_out_mask(mMixerChannelMask) :
4294 mChannelCount;
4295 if (mType == SPATIALIZER && !isHapticSessionSpatialized) {
4296 hapticSessionChannelCount = mChannelCount;
4297 }
4298
jiabin47affe52019-04-04 18:02:07 -07004299 const size_t audioBufferSize = mNormalFrameCount
Eric Laurentb62d0362021-10-26 17:40:18 +02004300 * audio_bytes_per_frame(hapticSessionChannelCount,
Andy Hung319587b2023-05-23 14:01:03 -07004301 AUDIO_FORMAT_PCM_FLOAT);
jiabin47affe52019-04-04 18:02:07 -07004302 memcpy_by_audio_format(
4303 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004304 AUDIO_FORMAT_PCM_FLOAT,
jiabin47affe52019-04-04 18:02:07 -07004305 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
Andy Hung319587b2023-05-23 14:01:03 -07004306 AUDIO_FORMAT_PCM_FLOAT, mNormalFrameCount * mHapticChannelCount);
jiabin47affe52019-04-04 18:02:07 -07004307 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004308 }
Eric Laurent81784c32012-11-19 14:55:58 -08004309 }
4310 }
Eric Laurent59fe0102013-09-27 18:48:26 -07004311 // Process effect chains for offloaded thread even if no audio
4312 // was read from audio track: process only updates effect state
4313 // and thus does have to be synchronized with audio writes but may have
4314 // to be called while waiting for async write callback
4315 if (mType == OFFLOAD) {
4316 for (size_t i = 0; i < effectChains.size(); i ++) {
4317 effectChains[i]->process_l();
4318 }
4319 }
Eric Laurent81784c32012-11-19 14:55:58 -08004320
Andy Hung98ef9782014-03-04 14:46:50 -08004321 // Only if the Effects buffer is enabled and there is data in the
4322 // Effects buffer (buffer valid), we need to
4323 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004324 // TODO use mSleepTimeUs == 0 as an additional condition.
jiabinc658e452022-10-21 20:52:21 +00004325 if (mEffectBufferValid && !mHasDataCopiedToSinkBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004326 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Eric Laurentb62d0362021-10-26 17:40:18 +02004327 void *effectBuffer = (mType == SPATIALIZER) ? mPostSpatializerBuffer : mEffectBuffer;
Andy Hung2ddee192015-12-18 17:34:44 -08004328 if (requireMonoBlend()) {
Eric Laurentb62d0362021-10-26 17:40:18 +02004329 mono_blend(effectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
Glenn Kasten03c48d52016-01-27 17:25:17 -08004330 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08004331 }
4332
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004333 if (!hasFastMixer()) {
4334 // Balance must take effect after mono conversion.
4335 // We do it here if there is no FastMixer.
4336 // mBalance detects zero balance within the class for speed (not needed here).
4337 mBalance.setBalance(mMasterBalance.load());
Eric Laurentb62d0362021-10-26 17:40:18 +02004338 mBalance.process((float *)effectBuffer, mNormalFrameCount);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004339 }
4340
Eric Laurentb62d0362021-10-26 17:40:18 +02004341 // for SPATIALIZER thread, Move haptics channels from mEffectBuffer to
4342 // mPostSpatializerBuffer if the haptics track is spatialized.
4343 // Otherwise, the haptics channels are already in mPostSpatializerBuffer.
4344 // For other thread types, the haptics channels are already in mEffectBuffer.
4345 if (mType == SPATIALIZER && isHapticSessionSpatialized) {
4346 const size_t srcBufferSize = mNormalFrameCount *
4347 audio_bytes_per_frame(audio_channel_count_from_out_mask(mMixerChannelMask),
4348 mEffectBufferFormat);
4349 const size_t dstBufferSize = mNormalFrameCount
4350 * audio_bytes_per_frame(mChannelCount, mEffectBufferFormat);
4351
4352 memcpy_by_audio_format((uint8_t*)mPostSpatializerBuffer + dstBufferSize,
4353 mEffectBufferFormat,
4354 (uint8_t*)mEffectBuffer + srcBufferSize,
4355 mEffectBufferFormat,
4356 mNormalFrameCount * mHapticChannelCount);
Eric Laurent39095982021-08-24 18:29:27 +02004357 }
Atneya Nair68436cf2022-09-19 17:51:37 -07004358 const size_t framesToCopy = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
4359 if (mFormat == AUDIO_FORMAT_PCM_FLOAT &&
4360 mEffectBufferFormat == AUDIO_FORMAT_PCM_FLOAT) {
4361 // Clamp PCM float values more than this distance from 0 to insulate
4362 // a HAL which doesn't handle NaN correctly.
4363 static constexpr float HAL_FLOAT_SAMPLE_LIMIT = 2.0f;
4364 memcpy_to_float_from_float_with_clamping(static_cast<float*>(mSinkBuffer),
4365 static_cast<const float*>(effectBuffer),
4366 framesToCopy, HAL_FLOAT_SAMPLE_LIMIT /* absMax */);
4367 } else {
4368 memcpy_by_audio_format(mSinkBuffer, mFormat,
4369 effectBuffer, mEffectBufferFormat, framesToCopy);
4370 }
jiabin245cdd92018-12-07 17:55:15 -08004371 // The sample data is partially interleaved when haptic channels exist,
4372 // we need to adjust channels here.
4373 if (mHapticChannelCount > 0) {
4374 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
4375 mChannelCount + mHapticChannelCount,
4376 audio_bytes_per_sample(mFormat),
4377 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
4378 }
Andy Hung98ef9782014-03-04 14:46:50 -08004379 }
4380
Eric Laurent81784c32012-11-19 14:55:58 -08004381 // enable changes in effect chain
4382 unlockEffectChains(effectChains);
4383
Vlad Popafce10862023-02-03 10:37:07 +01004384 if (!metadataUpdate.playbackMetadataUpdate.empty()) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004385 mAfThreadCallback->getMelReporter()->updateMetadataForCsd(id(),
Vlad Popafce10862023-02-03 10:37:07 +01004386 metadataUpdate.playbackMetadataUpdate);
4387 }
4388
Eric Laurentbfb1b832013-01-07 09:53:42 -08004389 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004390 // mSleepTimeUs == 0 means we must write to audio hardware
4391 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07004392 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004393 // writePeriodNs is updated >= 0 when ret > 0.
4394 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004395 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07004396 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08004397 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07004398 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08004399 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004400 if (ret < 0) {
4401 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08004402 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004403 mBytesWritten += ret;
4404 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004405 const int64_t frames = ret / mFrameSize;
4406 mFramesWritten += frames;
4407
4408 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4409 // process information relating to write time.
4410 if (audio_has_proportional_frames(mFormat)) {
4411 // we are in a continuous mixing cycle
4412 if (mMixerStatus == MIXER_TRACKS_READY &&
4413 loopCount == lastLoopCountWritten + 1) {
4414
4415 const double jitterMs =
4416 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4417 {frames, writePeriodNs},
4418 {0, 0} /* lastTimestamp */, mSampleRate);
4419 const double processMs =
4420 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4421
Andy Hungf79092d2023-08-31 16:13:39 -07004422 audio_utils::lock_guard _l(mutex());
Andy Hung446f4df2019-02-21 12:26:41 -08004423 mIoJitterMs.add(jitterMs);
4424 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004425
4426 if (mPipeSink.get() != nullptr) {
4427 // Using the Monopipe availableToWrite, we estimate the current
4428 // buffer size.
4429 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4430 const ssize_t
4431 availableToWrite = mPipeSink->availableToWrite();
4432 const size_t pipeFrames = monoPipe->maxFrames();
4433 const size_t
4434 remainingFrames = pipeFrames - max(availableToWrite, 0);
4435 mMonopipePipeDepthStats.add(remainingFrames);
4436 }
Andy Hung446f4df2019-02-21 12:26:41 -08004437 }
4438
4439 // write blocked detection
4440 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
Andy Hungd3639922022-04-28 18:00:49 -07004441 if ((mType == MIXER || mType == SPATIALIZER)
4442 && deltaWriteNs > maxPeriod) {
Andy Hung446f4df2019-02-21 12:26:41 -08004443 mNumDelayedWrites++;
4444 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4445 ATRACE_NAME("underrun");
4446 ALOGW("write blocked for %lld msecs, "
4447 "%d delayed writes, thread %d",
4448 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4449 mNumDelayedWrites, mId);
4450 lastWarning = lastIoEndNs;
4451 }
4452 }
4453 }
4454 // update timing info.
4455 mLastIoBeginNs = lastIoBeginNs;
4456 mLastIoEndNs = lastIoEndNs;
4457 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004458 }
4459 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4460 (mMixerStatus == MIXER_DRAIN_ALL)) {
4461 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004462 }
Andy Hungd3639922022-04-28 18:00:49 -07004463 if ((mType == MIXER || mType == SPATIALIZER) && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004464
4465 if (mThreadThrottle
4466 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004467 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004468 // Limit MixerThread data processing to no more than twice the
4469 // expected processing rate.
4470 //
4471 // This helps prevent underruns with NuPlayer and other applications
4472 // which may set up buffers that are close to the minimum size, or use
4473 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4474 //
4475 // The throttle smooths out sudden large data drains from the device,
4476 // e.g. when it comes out of standby, which often causes problems with
4477 // (1) mixer threads without a fast mixer (which has its own warm-up)
4478 // (2) minimum buffer sized tracks (even if the track is full,
4479 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004480 //
4481 // Total time spent in last processing cycle equals time spent in
4482 // 1. threadLoop_write, as well as time spent in
4483 // 2. threadLoop_mix (significant for heavy mixing, especially
4484 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004485
Andy Hung446f4df2019-02-21 12:26:41 -08004486 // it's OK if deltaMs is an overestimate.
4487
4488 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004489
Ivan Lozanoea04d392017-11-07 14:37:07 -08004490 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004491 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004492 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004493
Andy Hung08fb1742015-05-31 23:22:10 -07004494 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004495 // notify of throttle start on verbose log
4496 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4497 "mixer(%p) throttle begin:"
4498 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004499 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004500 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004501 // Throttle must be attributed to the previous mixer loop's write time
4502 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004503 // This also ensures proper timing statistics.
4504 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004505 } else {
4506 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4507 if (diff > 0) {
4508 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004509 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004510 ALOGD_IF(!isSingleDeviceType(
4511 outDeviceTypes(), audio_is_a2dp_out_device) &&
4512 !isSingleDeviceType(
4513 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004514 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004515 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4516 }
Andy Hung08fb1742015-05-31 23:22:10 -07004517 }
4518 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004519 }
Eric Laurent81784c32012-11-19 14:55:58 -08004520
Eric Laurentbfb1b832013-01-07 09:53:42 -08004521 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004522 ATRACE_BEGIN("sleep");
Andy Hung87e82412023-08-29 14:26:09 -07004523 audio_utils::unique_lock _l(mutex());
rago1bb90822017-05-02 18:31:48 -07004524 // suspended requires accurate metering of sleep time.
4525 if (isSuspended()) {
4526 // advance by expected sleepTime
4527 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4528 const nsecs_t nowNs = systemTime();
4529
4530 // compute expected next time vs current time.
4531 // (negative deltas are treated as delays).
4532 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4533 if (deltaNs < -kMaxNextBufferDelayNs) {
4534 // Delays longer than the max allowed trigger a reset.
4535 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4536 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4537 timeLoopNextNs = nowNs + deltaNs;
4538 } else if (deltaNs < 0) {
4539 // Delays within the max delay allowed: zero the delta/sleepTime
4540 // to help the system catch up in the next iteration(s)
4541 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4542 deltaNs = 0;
4543 }
4544 // update sleep time (which is >= 0)
4545 mSleepTimeUs = deltaNs / 1000;
4546 }
Eric Laurente93cc032016-05-05 10:15:10 -07004547 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
Andy Hung87e82412023-08-29 14:26:09 -07004548 mWaitWorkCV.wait_for(_l, std::chrono::microseconds(mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004549 }
Glenn Kastene7754022014-10-31 12:11:26 -07004550 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004551 }
Eric Laurent81784c32012-11-19 14:55:58 -08004552 }
4553
4554 // Finally let go of removed track(s), without the lock held
4555 // since we can't guarantee the destructors won't acquire that
4556 // same lock. This will also mutate and push a new fast mixer state.
4557 threadLoop_removeTracks(tracksToRemove);
4558 tracksToRemove.clear();
4559
4560 // FIXME I don't understand the need for this here;
4561 // it was in the original code but maybe the
4562 // assignment in saveOutputTracks() makes this unnecessary?
4563 clearOutputTracks();
4564
4565 // Effect chains will be actually deleted here if they were removed from
4566 // mEffectChains list during mixing or effects processing
4567 effectChains.clear();
4568
4569 // FIXME Note that the above .clear() is no longer necessary since effectChains
4570 // is now local to this block, but will keep it for now (at least until merge done).
4571 }
4572
Eric Laurentbfb1b832013-01-07 09:53:42 -08004573 threadLoop_exit();
4574
Eric Laurentcf817a22014-08-04 20:36:31 -07004575 if (!mStandby) {
4576 threadLoop_standby();
Eric Laurent19952e12023-04-20 10:08:29 +02004577 setStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08004578 }
4579
4580 releaseWakeLock();
4581
4582 ALOGV("Thread %p type %d exiting", this, mType);
4583 return false;
4584}
4585
Andy Hung71742ab2023-07-07 13:47:37 -07004586void PlaybackThread::collectTimestamps_l()
Dean Wheatley12473e92021-03-18 23:00:55 +11004587{
Dean Wheatley12473e92021-03-18 23:00:55 +11004588 if (mStandby) {
4589 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4590 return;
4591 } else if (mHwPaused) {
4592 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4593 return;
4594 }
4595
4596 // Gather the framesReleased counters for all active tracks,
4597 // and associate with the sink frames written out. We need
4598 // this to convert the sink timestamp to the track timestamp.
4599 bool kernelLocationUpdate = false;
4600 ExtendedTimestamp timestamp; // use private copy to fetch
4601
4602 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4603 // HAL may be draining some small duration buffered data for fade out.
4604 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4605 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4606 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4607 mSampleRate);
4608
4609 if (isTimestampCorrectionEnabled()) {
4610 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4611 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4612 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4613 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4614 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4615 = correctedTimestamp.mFrames;
4616 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4617 = correctedTimestamp.mTimeNs;
4618 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4619 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4620 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4621
4622 // Note: Downstream latency only added if timestamp correction enabled.
4623 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4624 const int64_t newPosition =
4625 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4626 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4627 // prevent retrograde
4628 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4629 newPosition,
4630 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4631 - mSuspendedFrames));
4632 }
4633 }
4634
4635 // We always fetch the timestamp here because often the downstream
4636 // sink will block while writing.
4637
4638 // We keep track of the last valid kernel position in case we are in underrun
4639 // and the normal mixer period is the same as the fast mixer period, or there
4640 // is some error from the HAL.
4641 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4642 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4643 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4644 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4645 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4646
4647 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4648 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4649 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4650 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4651 }
4652
4653 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4654 kernelLocationUpdate = true;
4655 } else {
4656 ALOGVV("getTimestamp error - no valid kernel position");
4657 }
4658
4659 // copy over kernel info
4660 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4661 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4662 + mSuspendedFrames; // add frames discarded when suspended
4663 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4664 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4665 } else {
4666 mTimestampVerifier.error();
4667 }
4668
4669 // mFramesWritten for non-offloaded tracks are contiguous
4670 // even after standby() is called. This is useful for the track frame
4671 // to sink frame mapping.
4672 bool serverLocationUpdate = false;
4673 if (mFramesWritten != mLastFramesWritten) {
4674 serverLocationUpdate = true;
4675 mLastFramesWritten = mFramesWritten;
4676 }
4677 // Only update timestamps if there is a meaningful change.
4678 // Either the kernel timestamp must be valid or we have written something.
4679 if (kernelLocationUpdate || serverLocationUpdate) {
4680 if (serverLocationUpdate) {
4681 // use the time before we called the HAL write - it is a bit more accurate
4682 // to when the server last read data than the current time here.
4683 //
4684 // If we haven't written anything, mLastIoBeginNs will be -1
4685 // and we use systemTime().
4686 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4687 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4688 ? systemTime() : mLastIoBeginNs;
4689 }
4690
Andy Hung3ff4b552023-06-26 19:20:57 -07004691 for (const sp<IAfTrack>& t : mActiveTracks) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004692 if (!t->isFastTrack()) {
4693 t->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07004694 t->audioTrackServerProxy()->framesReleased(),
Dean Wheatley12473e92021-03-18 23:00:55 +11004695 mFramesWritten,
4696 mSampleRate,
4697 mTimestamp);
4698 }
4699 }
4700 }
4701
4702 if (audio_has_proportional_frames(mFormat)) {
4703 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4704 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4705 mLatencyMs.add(latencyMs);
4706 }
4707 }
4708#if 0
4709 // logFormat example
4710 if (z % 100 == 0) {
4711 timespec ts;
4712 clock_gettime(CLOCK_MONOTONIC, &ts);
4713 LOGT("This is an integer %d, this is a float %f, this is my "
4714 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4715 LOGT("A deceptive null-terminated string %\0");
4716 }
4717 ++z;
4718#endif
4719}
4720
Andy Hung87e82412023-08-29 14:26:09 -07004721// removeTracks_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07004722void PlaybackThread::removeTracks_l(const Vector<sp<IAfTrack>>& tracksToRemove)
Andy Hung87e82412023-08-29 14:26:09 -07004723NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurentbfb1b832013-01-07 09:53:42 -08004724{
Andy Hungfe726a62018-09-27 15:17:25 -07004725 for (const auto& track : tracksToRemove) {
4726 mActiveTracks.remove(track);
4727 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
Andy Hungbd72c542023-06-20 18:56:17 -07004728 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Andy Hungfe726a62018-09-27 15:17:25 -07004729 if (chain != 0) {
4730 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4731 __func__, track->id(), chain.get(), track->sessionId());
4732 chain->decActiveTrackCnt();
4733 }
4734 // If an external client track, inform APM we're no longer active, and remove if needed.
4735 // We do this under lock so that the state is consistent if the Track is destroyed.
4736 if (track->isExternalTrack()) {
4737 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004738 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004739 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004740 }
4741 }
Andy Hungfe726a62018-09-27 15:17:25 -07004742 if (track->isTerminated()) {
4743 // remove from our tracks vector
4744 removeTrack_l(track);
4745 }
jiabineb3bda02020-06-30 14:07:03 -07004746 if (mHapticChannelCount > 0 &&
4747 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4748 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
Andy Hung87e82412023-08-29 14:26:09 -07004749 mutex().unlock();
jiabin57303cc2018-12-18 15:45:57 -08004750 // Unlock due to VibratorService will lock for this call and will
4751 // call Tracks.mute/unmute which also require thread's lock.
Andy Hung9554ec02023-07-20 21:23:42 -07004752 afutils::onExternalVibrationStop(track->getExternalVibration());
Andy Hung87e82412023-08-29 14:26:09 -07004753 mutex().lock();
jiabine70bc7f2020-06-30 22:07:55 -07004754
4755 // When the track is stop, set the haptic intensity as MUTE
4756 // for the HapticGenerator effect.
4757 if (chain != nullptr) {
Simon Bowden62823412022-10-17 14:52:26 +00004758 chain->setHapticIntensity_l(track->id(), os::HapticScale::MUTE);
jiabine70bc7f2020-06-30 22:07:55 -07004759 }
jiabin245cdd92018-12-07 17:55:15 -08004760 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004761 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004762}
Eric Laurent81784c32012-11-19 14:55:58 -08004763
Andy Hung71742ab2023-07-07 13:47:37 -07004764status_t PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
Eric Laurentaccc1472013-09-20 09:36:34 -07004765{
4766 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004767 ExtendedTimestamp ets;
4768 status_t status = mNormalSink->getTimestamp(ets);
4769 if (status == NO_ERROR) {
4770 status = ets.getBestTimestamp(&timestamp);
4771 }
4772 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004773 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004774 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004775 collectTimestamps_l();
4776 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4777 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004778 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004779 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4780 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4781 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4782 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4783 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004784 }
4785 return INVALID_OPERATION;
4786}
Eric Laurent1c333e22014-05-20 10:48:17 -07004787
Eric Laurenteab90452019-06-24 15:17:46 -07004788// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4789// still applied by the mixer.
4790// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4791// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4792// if more than one track are active
Andy Hung71742ab2023-07-07 13:47:37 -07004793status_t PlaybackThread::handleVoipVolume_l(float* volume)
Eric Laurenteab90452019-06-24 15:17:46 -07004794{
4795 status_t result = NO_ERROR;
4796 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4797 if (*volume != mLeftVolFloat) {
4798 result = mOutput->stream->setVolume(*volume, *volume);
Alex Leungc5dedb22023-05-10 08:00:50 -07004799 // HAL can return INVALID_OPERATION if operation is not supported.
4800 ALOGE_IF(result != OK && result != INVALID_OPERATION,
Eric Laurenteab90452019-06-24 15:17:46 -07004801 "Error when setting output stream volume: %d", result);
4802 if (result == NO_ERROR) {
4803 mLeftVolFloat = *volume;
4804 }
4805 }
4806 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4807 // remove stream volume contribution from software volume.
4808 if (mLeftVolFloat == *volume) {
4809 *volume = 1.0f;
4810 }
4811 }
4812 return result;
4813}
4814
Andy Hung71742ab2023-07-07 13:47:37 -07004815status_t MixerThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent054d9d32015-04-24 08:48:48 -07004816 audio_patch_handle_t *handle)
4817{
Andy Hungf60abce2016-08-26 11:37:54 -07004818 status_t status;
4819 if (property_get_bool("af.patch_park", false /* default_value */)) {
4820 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4821 // or if HAL does not properly lock against access.
4822 AutoPark<FastMixer> park(mFastMixer);
4823 status = PlaybackThread::createAudioPatch_l(patch, handle);
4824 } else {
4825 status = PlaybackThread::createAudioPatch_l(patch, handle);
4826 }
Eric Laurentb0463942022-12-20 16:31:10 +01004827
4828 updateHalSupportedLatencyModes_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004829 return status;
4830}
4831
Andy Hung71742ab2023-07-07 13:47:37 -07004832status_t PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07004833 audio_patch_handle_t *handle)
4834{
4835 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004836
4837 // store new device and send to effects
4838 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004839 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004840 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004841 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4842 && !mOutput->audioHwDev->supportsAudioPatches(),
4843 "Enumerated device type(%#x) must not be used "
4844 "as it does not support audio patches",
4845 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004846 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -07004847 deviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
4848 patch->sinks[i].ext.device.address);
Eric Laurent054d9d32015-04-24 08:48:48 -07004849 }
4850
François Gaffie0c280aa2018-07-25 10:02:15 +02004851 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004852#ifdef ADD_BATTERY_DATA
4853 // when changing the audio output device, call addBatteryData to notify
4854 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004855 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004856 uint32_t params = 0;
4857 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004858 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004859 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004860 }
4861
Eric Laurent054d9d32015-04-24 08:48:48 -07004862 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004863 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004864 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4865 }
4866
4867 if (params != 0) {
4868 addBatteryData(params);
4869 }
4870 }
4871#endif
4872
4873 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004874 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004875 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004876
jiabinc52b1ff2019-10-31 17:20:42 -07004877 // mPatch.num_sinks is not set when the thread is created so that
4878 // the first patch creation triggers an ioConfigChanged callback
4879 bool configChanged = (mPatch.num_sinks == 0) ||
4880 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004881 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004882 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004883 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004884
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004885 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004886 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4887 status = hwDevice->createAudioPatch(patch->num_sources,
4888 patch->sources,
4889 patch->num_sinks,
4890 patch->sinks,
4891 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004892 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004893 status = mOutput->stream->legacyCreateAudioPatch(patch->sinks[0], std::nullopt, type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004894 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004895 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004896 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004897
4898 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004899 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004900 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004901 // also dispatch to active AudioTracks for MediaMetrics
4902 for (const auto &track : mActiveTracks) {
4903 track->logEndInterval();
4904 track->logBeginInterval(patchSinksAsString);
4905 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004906
Eric Laurente8726fe2015-06-26 09:39:24 -07004907 if (configChanged) {
4908 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4909 }
Vlad Popa7e81cea2023-01-19 16:34:16 +01004910 // Force metadata update after a route change
Eric Laurentdda206a2022-07-08 17:28:35 +02004911 mActiveTracks.setHasChanged();
4912
Eric Laurent1c333e22014-05-20 10:48:17 -07004913 return status;
4914}
4915
Andy Hung71742ab2023-07-07 13:47:37 -07004916status_t MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent054d9d32015-04-24 08:48:48 -07004917{
Andy Hungf60abce2016-08-26 11:37:54 -07004918 status_t status;
4919 if (property_get_bool("af.patch_park", false /* default_value */)) {
4920 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4921 // or if HAL does not properly lock against access.
4922 AutoPark<FastMixer> park(mFastMixer);
4923 status = PlaybackThread::releaseAudioPatch_l(handle);
4924 } else {
4925 status = PlaybackThread::releaseAudioPatch_l(handle);
4926 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004927 return status;
4928}
4929
Andy Hung71742ab2023-07-07 13:47:37 -07004930status_t PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004931{
4932 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004933
jiabinc52b1ff2019-10-31 17:20:42 -07004934 mPatch = audio_patch{};
4935 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004936
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004937 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004938 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4939 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004940 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08004941 status = mOutput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07004942 }
Eric Laurentdda206a2022-07-08 17:28:35 +02004943 // Force meteadata update after a route change
4944 mActiveTracks.setHasChanged();
4945
Eric Laurent1c333e22014-05-20 10:48:17 -07004946 return status;
4947}
4948
Andy Hung71742ab2023-07-07 13:47:37 -07004949void PlaybackThread::addPatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004950{
Andy Hungf79092d2023-08-31 16:13:39 -07004951 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004952 mTracks.add(track);
4953}
4954
Andy Hung71742ab2023-07-07 13:47:37 -07004955void PlaybackThread::deletePatchTrack(const sp<IAfPatchTrack>& track)
Eric Laurent83b88082014-06-20 18:31:16 -07004956{
Andy Hungf79092d2023-08-31 16:13:39 -07004957 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07004958 destroyTrack_l(track);
4959}
4960
Andy Hung71742ab2023-07-07 13:47:37 -07004961void PlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07004962{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004963 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004964 config->role = AUDIO_PORT_ROLE_SOURCE;
4965 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4966 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004967 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4968 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4969 config->flags.output = mOutput->flags;
4970 }
Eric Laurent83b88082014-06-20 18:31:16 -07004971}
4972
Eric Laurent81784c32012-11-19 14:55:58 -08004973// ----------------------------------------------------------------------------
4974
Andy Hung71742ab2023-07-07 13:47:37 -07004975/* static */
4976sp<IAfPlaybackThread> IAfPlaybackThread::createMixerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07004977 const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Andy Hung71742ab2023-07-07 13:47:37 -07004978 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07004979 return sp<MixerThread>::make(afThreadCallback, output, id, systemReady, type, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07004980}
4981
Andy Hung2cbc2722023-07-17 17:05:00 -07004982MixerThread::MixerThread(const sp<IAfThreadCallback>& afThreadCallback, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004983 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07004984 : PlaybackThread(afThreadCallback, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004985 // mAudioMixer below
4986 // mFastMixer below
Eric Laurentb0463942022-12-20 16:31:10 +01004987 mBluetoothLatencyModesEnabled(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004988 mFastMixerFutex(0),
4989 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004990 // mOutputSink below
4991 // mPipeSink below
4992 // mNormalSink below
4993{
Andy Hung2cbc2722023-07-17 17:05:00 -07004994 setMasterBalance(afThreadCallback->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004995 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004996 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004997 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004998 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4999 mNormalFrameCount);
5000 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
5001
Andy Hungfbfc3952015-01-15 13:33:51 -08005002 if (type == DUPLICATING) {
5003 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
5004 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
5005 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
5006 return;
5007 }
Eric Laurent81784c32012-11-19 14:55:58 -08005008 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07005009 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08005010 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08005011 const NBAIO_Format offers[1] = {Format_from_SR_C(
5012 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005013#if !LOG_NDEBUG
5014 ssize_t index =
5015#else
5016 (void)
5017#endif
5018 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08005019 ALOG_ASSERT(index == 0);
5020
5021 // initialize fast mixer depending on configuration
5022 bool initFastMixer;
jiabinc658e452022-10-21 20:52:21 +00005023 if (mType == SPATIALIZER || mType == BIT_PERFECT) {
Eric Laurent81784c32012-11-19 14:55:58 -08005024 initFastMixer = false;
Eric Laurentb62d0362021-10-26 17:40:18 +02005025 } else {
5026 switch (kUseFastMixer) {
5027 case FastMixer_Never:
5028 initFastMixer = false;
5029 break;
5030 case FastMixer_Always:
5031 initFastMixer = true;
5032 break;
5033 case FastMixer_Static:
5034 case FastMixer_Dynamic:
5035 initFastMixer = mFrameCount < mNormalFrameCount;
5036 break;
5037 }
5038 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
5039 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
5040 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08005041 }
5042 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07005043 audio_format_t fastMixerFormat;
5044 if (mMixerBufferEnabled && mEffectBufferEnabled) {
5045 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
5046 } else {
5047 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
5048 }
5049 if (mFormat != fastMixerFormat) {
5050 // change our Sink format to accept our intermediate precision
5051 mFormat = fastMixerFormat;
5052 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08005053 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005054 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
5055 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
5056 }
Eric Laurent81784c32012-11-19 14:55:58 -08005057
5058 // create a MonoPipe to connect our submix to FastMixer
5059 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07005060
Andy Hung1258c1a2014-05-23 21:22:17 -07005061 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08005062 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07005063 format.mFormat = fastMixerFormat;
5064 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
5065
Eric Laurent81784c32012-11-19 14:55:58 -08005066 // This pipe depth compensates for scheduling latency of the normal mixer thread.
5067 // When it wakes up after a maximum latency, it runs a few cycles quickly before
5068 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
5069 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
Andy Hung71ba4b32022-10-06 12:09:49 -07005070 const NBAIO_Format offersFast[1] = {format};
5071 size_t numCounterOffersFast = 0;
Andy Hung8946a282018-04-19 20:04:56 -07005072#if !LOG_NDEBUG
Eric Laurent1e28aaa2023-04-16 19:34:23 +02005073 index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005074#else
5075 (void)
5076#endif
Andy Hung71ba4b32022-10-06 12:09:49 -07005077 monoPipe->negotiate(offersFast, std::size(offersFast),
5078 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent81784c32012-11-19 14:55:58 -08005079 ALOG_ASSERT(index == 0);
5080 monoPipe->setAvgFrames((mScreenState & 1) ?
5081 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
5082 mPipeSink = monoPipe;
5083
Eric Laurent81784c32012-11-19 14:55:58 -08005084 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07005085 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08005086 FastMixerStateQueue *sq = mFastMixer->sq();
5087#ifdef STATE_QUEUE_DUMP
5088 sq->setObserverDump(&mStateQueueObserverDump);
5089 sq->setMutatorDump(&mStateQueueMutatorDump);
5090#endif
5091 FastMixerState *state = sq->begin();
5092 FastTrack *fastTrack = &state->mFastTracks[0];
5093 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
5094 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
5095 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07005096 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
5097 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
5098 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07005099 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08005100 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07005101 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01005102 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08005103 fastTrack->mGeneration++;
5104 state->mFastTracksGen++;
5105 state->mTrackMask = 1;
5106 // fast mixer will use the HAL output sink
5107 state->mOutputSink = mOutputSink.get();
5108 state->mOutputSinkGen++;
5109 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08005110 // specify sink channel mask when haptic channel mask present as it can not
5111 // be calculated directly from channel count
5112 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07005113 ? AUDIO_CHANNEL_NONE
5114 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08005115 state->mCommand = FastMixerState::COLD_IDLE;
5116 // already done in constructor initialization list
5117 //mFastMixerFutex = 0;
5118 state->mColdFutexAddr = &mFastMixerFutex;
5119 state->mColdGen++;
5120 state->mDumpState = &mFastMixerDumpState;
Andy Hung2cbc2722023-07-17 17:05:00 -07005121 mFastMixerNBLogWriter = afThreadCallback->newWriter_l(kFastMixerLogSize, "FastMixer");
Glenn Kasten9e58b552013-01-18 15:09:48 -08005122 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005123 sq->end();
5124 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5125
Eric Tan0513b5d2018-09-17 10:32:48 -07005126 NBLog::thread_info_t info;
5127 info.id = mId;
5128 info.type = NBLog::FASTMIXER;
5129 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
5130
Eric Laurent81784c32012-11-19 14:55:58 -08005131 // start the fast mixer
5132 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
5133 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005134 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08005135 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005136
5137#ifdef AUDIO_WATCHDOG
5138 // create and start the watchdog
5139 mAudioWatchdog = new AudioWatchdog();
5140 mAudioWatchdog->setDump(&mAudioWatchdogDump);
5141 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
5142 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07005143 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08005144#endif
Andy Hung8946a282018-04-19 20:04:56 -07005145 } else {
5146#ifdef TEE_SINK
5147 // Only use the MixerThread tee if there is no FastMixer.
5148 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
5149 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
5150#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005151 }
5152
5153 switch (kUseFastMixer) {
5154 case FastMixer_Never:
5155 case FastMixer_Dynamic:
5156 mNormalSink = mOutputSink;
5157 break;
5158 case FastMixer_Always:
5159 mNormalSink = mPipeSink;
5160 break;
5161 case FastMixer_Static:
5162 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
5163 break;
5164 }
5165}
5166
Andy Hung71742ab2023-07-07 13:47:37 -07005167MixerThread::~MixerThread()
Eric Laurent81784c32012-11-19 14:55:58 -08005168{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005169 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005170 FastMixerStateQueue *sq = mFastMixer->sq();
5171 FastMixerState *state = sq->begin();
5172 if (state->mCommand == FastMixerState::COLD_IDLE) {
5173 int32_t old = android_atomic_inc(&mFastMixerFutex);
5174 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005175 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005176 }
5177 }
5178 state->mCommand = FastMixerState::EXIT;
5179 sq->end();
5180 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5181 mFastMixer->join();
5182 // Though the fast mixer thread has exited, it's state queue is still valid.
5183 // We'll use that extract the final state which contains one remaining fast track
5184 // corresponding to our sub-mix.
5185 state = sq->begin();
5186 ALOG_ASSERT(state->mTrackMask == 1);
5187 FastTrack *fastTrack = &state->mFastTracks[0];
5188 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
5189 delete fastTrack->mBufferProvider;
5190 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005191 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005192#ifdef AUDIO_WATCHDOG
5193 if (mAudioWatchdog != 0) {
5194 mAudioWatchdog->requestExit();
5195 mAudioWatchdog->requestExitAndWait();
5196 mAudioWatchdog.clear();
5197 }
5198#endif
5199 }
Andy Hung2cbc2722023-07-17 17:05:00 -07005200 mAfThreadCallback->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08005201 delete mAudioMixer;
5202}
5203
Andy Hung71742ab2023-07-07 13:47:37 -07005204void MixerThread::onFirstRef() {
Eric Laurentb0463942022-12-20 16:31:10 +01005205 PlaybackThread::onFirstRef();
5206
Andy Hungf79092d2023-08-31 16:13:39 -07005207 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01005208 if (mOutput != nullptr && mOutput->stream != nullptr) {
5209 status_t status = mOutput->stream->setLatencyModeCallback(this);
5210 if (status != INVALID_OPERATION) {
5211 updateHalSupportedLatencyModes_l();
5212 }
5213 // Default to enabled if the HAL supports it. This can be changed by Audioflinger after
5214 // the thread construction according to AudioFlinger::mBluetoothLatencyModesEnabled
5215 mBluetoothLatencyModesEnabled.store(
5216 mOutput->audioHwDev->supportsBluetoothVariableLatency());
5217 }
5218}
Eric Laurent81784c32012-11-19 14:55:58 -08005219
Andy Hung71742ab2023-07-07 13:47:37 -07005220uint32_t MixerThread::correctLatency_l(uint32_t latency) const
Eric Laurent81784c32012-11-19 14:55:58 -08005221{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005222 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005223 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
5224 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
5225 }
5226 return latency;
5227}
5228
Andy Hung71742ab2023-07-07 13:47:37 -07005229ssize_t MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08005230{
5231 // FIXME we should only do one push per cycle; confirm this is true
5232 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005233 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005234 FastMixerStateQueue *sq = mFastMixer->sq();
5235 FastMixerState *state = sq->begin();
5236 if (state->mCommand != FastMixerState::MIX_WRITE &&
5237 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
5238 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07005239
5240 // FIXME workaround for first HAL write being CPU bound on some devices
5241 ATRACE_BEGIN("write");
5242 mOutput->write((char *)mSinkBuffer, 0);
5243 ATRACE_END();
5244
Eric Laurent81784c32012-11-19 14:55:58 -08005245 int32_t old = android_atomic_inc(&mFastMixerFutex);
5246 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07005247 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08005248 }
5249#ifdef AUDIO_WATCHDOG
5250 if (mAudioWatchdog != 0) {
5251 mAudioWatchdog->resume();
5252 }
5253#endif
5254 }
5255 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08005256#ifdef FAST_THREAD_STATISTICS
Andy Hung2cbc2722023-07-17 17:05:00 -07005257 mFastMixerDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08005258 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08005259#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005260 sq->end();
5261 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
5262 if (kUseFastMixer == FastMixer_Dynamic) {
5263 mNormalSink = mPipeSink;
5264 }
5265 } else {
5266 sq->end(false /*didModify*/);
5267 }
5268 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005269 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08005270}
5271
Andy Hung71742ab2023-07-07 13:47:37 -07005272void MixerThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005273{
5274 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005275 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005276 FastMixerStateQueue *sq = mFastMixer->sq();
5277 FastMixerState *state = sq->begin();
5278 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08005279 // Report any frames trapped in the Monopipe
5280 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
5281 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
5282 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
5283 "monoPipeWritten:%lld monoPipeLeft:%lld",
5284 (long long)mFramesWritten, (long long)mSuspendedFrames,
5285 (long long)mPipeSink->framesWritten(), pipeFrames);
5286 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
5287
Eric Laurent81784c32012-11-19 14:55:58 -08005288 state->mCommand = FastMixerState::COLD_IDLE;
5289 state->mColdFutexAddr = &mFastMixerFutex;
5290 state->mColdGen++;
5291 mFastMixerFutex = 0;
5292 sq->end();
5293 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
5294 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
5295 if (kUseFastMixer == FastMixer_Dynamic) {
5296 mNormalSink = mOutputSink;
5297 }
5298#ifdef AUDIO_WATCHDOG
5299 if (mAudioWatchdog != 0) {
5300 mAudioWatchdog->pause();
5301 }
5302#endif
5303 } else {
5304 sq->end(false /*didModify*/);
5305 }
5306 }
5307 PlaybackThread::threadLoop_standby();
5308}
5309
Andy Hung71742ab2023-07-07 13:47:37 -07005310bool PlaybackThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005311{
5312 return false;
5313}
5314
Andy Hung71742ab2023-07-07 13:47:37 -07005315bool PlaybackThread::shouldStandby_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005316{
5317 return !mStandby;
5318}
5319
Andy Hung71742ab2023-07-07 13:47:37 -07005320bool PlaybackThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08005321{
Andy Hungf79092d2023-08-31 16:13:39 -07005322 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005323 return waitingAsyncCallback_l();
5324}
5325
Eric Laurent81784c32012-11-19 14:55:58 -08005326// shared by MIXER and DIRECT, overridden by DUPLICATING
Andy Hung71742ab2023-07-07 13:47:37 -07005327void PlaybackThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08005328{
5329 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08005330 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005331 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07005332 // discard any pending drain or write ack by incrementing sequence
5333 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
5334 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005335 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07005336 mCallbackThread->setWriteBlocked(mWriteAckSequence);
5337 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005338 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005339 mHwPaused = false;
Eric Laurent6f9534f2022-05-03 18:15:04 +02005340 setHalLatencyMode_l();
Eric Laurent81784c32012-11-19 14:55:58 -08005341}
5342
Andy Hung71742ab2023-07-07 13:47:37 -07005343void PlaybackThread::onAddNewTrack_l()
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08005344{
5345 ALOGV("signal playback thread");
5346 broadcast_l();
5347}
5348
Andy Hung71742ab2023-07-07 13:47:37 -07005349void PlaybackThread::onAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005350{
5351 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
5352 invalidateTracks((audio_stream_type_t)i);
5353 }
5354}
5355
Andy Hung71742ab2023-07-07 13:47:37 -07005356void MixerThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08005357{
Eric Laurent81784c32012-11-19 14:55:58 -08005358 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08005359 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08005360 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005361 // increase sleep time progressively when application underrun condition clears.
5362 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
5363 // that a steady state of alternating ready/not ready conditions keeps the sleep time
5364 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005365 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005366 sleepTimeShift--;
5367 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005368 mSleepTimeUs = 0;
5369 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005370 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07005371
Eric Laurent81784c32012-11-19 14:55:58 -08005372}
5373
Andy Hung71742ab2023-07-07 13:47:37 -07005374void MixerThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08005375{
5376 // If no tracks are ready, sleep once for the duration of an output
5377 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005378 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005379 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07005380 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
5381 // Using the Monopipe availableToWrite, we estimate the
5382 // sleep time to retry for more data (before we underrun).
5383 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
5384 const ssize_t availableToWrite = mPipeSink->availableToWrite();
5385 const size_t pipeFrames = monoPipe->maxFrames();
5386 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
5387 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
5388 const size_t framesDelay = std::min(
5389 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
5390 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
5391 pipeFrames, framesLeft, framesDelay);
5392 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
5393 } else {
5394 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
5395 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
5396 mSleepTimeUs = kMinThreadSleepTimeUs;
5397 }
5398 // reduce sleep time in case of consecutive application underruns to avoid
5399 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
5400 // duration we would end up writing less data than needed by the audio HAL if
5401 // the condition persists.
5402 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
5403 sleepTimeShift++;
5404 }
Eric Laurent81784c32012-11-19 14:55:58 -08005405 }
5406 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005407 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005408 }
5409 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08005410 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
5411 // before effects processing or output.
5412 if (mMixerBufferValid) {
5413 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02005414 if (mType == SPATIALIZER) {
5415 memset(mSinkBuffer, 0, mSinkBufferSize);
5416 }
Andy Hung98ef9782014-03-04 14:46:50 -08005417 } else {
5418 memset(mSinkBuffer, 0, mSinkBufferSize);
5419 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005420 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005421 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5422 "anticipated start");
5423 }
5424 // TODO add standby time extension fct of effect tail
5425}
5426
Andy Hung87e82412023-08-29 14:26:09 -07005427// prepareTracks_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07005428PlaybackThread::mixer_state MixerThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07005429 Vector<sp<IAfTrack>>* tracksToRemove)
Eric Laurent81784c32012-11-19 14:55:58 -08005430{
Andy Hungc0691382018-09-12 18:01:57 -07005431 // clean up deleted track ids in AudioMixer before allocating new tracks
5432 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5433 // for each trackId, destroy it in the AudioMixer
5434 if (mAudioMixer->exists(trackId)) {
5435 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005436 }
5437 });
Andy Hungc0691382018-09-12 18:01:57 -07005438 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005439
5440 mixer_state mixerStatus = MIXER_IDLE;
5441 // find out which tracks need to be processed
5442 size_t count = mActiveTracks.size();
5443 size_t mixedTracks = 0;
5444 size_t tracksWithEffect = 0;
5445 // counts only _active_ fast tracks
5446 size_t fastTracks = 0;
5447 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5448
5449 float masterVolume = mMasterVolume;
5450 bool masterMute = mMasterMute;
5451
5452 if (masterMute) {
5453 masterVolume = 0;
5454 }
5455 // Delegate master volume control to effect in output mix effect chain if needed
Andy Hungbd72c542023-06-20 18:56:17 -07005456 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
Eric Laurent81784c32012-11-19 14:55:58 -08005457 if (chain != 0) {
5458 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5459 chain->setVolume_l(&v, &v);
5460 masterVolume = (float)((v + (1 << 23)) >> 24);
5461 chain.clear();
5462 }
5463
5464 // prepare a new state to push
5465 FastMixerStateQueue *sq = NULL;
5466 FastMixerState *state = NULL;
5467 bool didModify = false;
5468 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005469 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005470 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005471 sq = mFastMixer->sq();
5472 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005473 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005474 }
5475
Andy Hung69aed5f2014-02-25 17:24:40 -08005476 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005477 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005478
Andy Hungbd3b2b02018-05-21 10:53:11 -07005479 // DeferredOperations handles statistics after setting mixerStatus.
5480 class DeferredOperations {
5481 public:
Andy Hungea840382020-05-05 21:50:17 -07005482 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5483 : mMixerStatus(mixerStatus)
5484 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005485
5486 // when leaving scope, tally frames properly.
5487 ~DeferredOperations() {
5488 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5489 // because that is when the underrun occurs.
5490 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005491 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005492 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005493 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005494 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005495 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005496 }
5497 }
Andy Hungea840382020-05-05 21:50:17 -07005498 // send the max underrun frames for this mixer period
5499 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005500 }
5501
5502 // tallyUnderrunFrames() is called to update the track counters
5503 // with the number of underrun frames for a particular mixer period.
5504 // We defer tallying until we know the final mixer status.
Andy Hung3ff4b552023-06-26 19:20:57 -07005505 void tallyUnderrunFrames(const sp<IAfTrack>& track, size_t underrunFrames) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005506 mUnderrunFrames.emplace_back(track, underrunFrames);
5507 }
5508
5509 private:
5510 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005511 ThreadMetrics * const mThreadMetrics;
Andy Hung3ff4b552023-06-26 19:20:57 -07005512 std::vector<std::pair<sp<IAfTrack>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005513 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005514 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005515
jiabin245cdd92018-12-07 17:55:15 -08005516 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005517 for (size_t i=0 ; i<count ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005518 const sp<IAfTrack> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005519
5520 // this const just means the local variable doesn't change
Andy Hung3ff4b552023-06-26 19:20:57 -07005521 IAfTrack* const track = t.get();
Eric Laurent81784c32012-11-19 14:55:58 -08005522
5523 // process fast tracks
5524 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005525 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5526 "%s(%d): FastTrack(%d) present without FastMixer",
5527 __func__, id(), track->id());
5528
jiabin245cdd92018-12-07 17:55:15 -08005529 if (track->getHapticPlaybackEnabled()) {
5530 noFastHapticTrack = false;
5531 }
Eric Laurent81784c32012-11-19 14:55:58 -08005532
5533 // It's theoretically possible (though unlikely) for a fast track to be created
5534 // and then removed within the same normal mix cycle. This is not a problem, as
5535 // the track never becomes active so it's fast mixer slot is never touched.
5536 // The converse, of removing an (active) track and then creating a new track
5537 // at the identical fast mixer slot within the same normal mix cycle,
5538 // is impossible because the slot isn't marked available until the end of each cycle.
Andy Hung3ff4b552023-06-26 19:20:57 -07005539 int j = track->fastIndex();
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005540 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005541 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5542 FastTrack *fastTrack = &state->mFastTracks[j];
5543
5544 // Determine whether the track is currently in underrun condition,
5545 // and whether it had a recent underrun.
5546 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5547 FastTrackUnderruns underruns = ftDump->mUnderruns;
5548 uint32_t recentFull = (underruns.mBitFields.mFull -
Andy Hung3ff4b552023-06-26 19:20:57 -07005549 track->fastTrackUnderruns().mBitFields.mFull) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005550 uint32_t recentPartial = (underruns.mBitFields.mPartial -
Andy Hung3ff4b552023-06-26 19:20:57 -07005551 track->fastTrackUnderruns().mBitFields.mPartial) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005552 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
Andy Hung3ff4b552023-06-26 19:20:57 -07005553 track->fastTrackUnderruns().mBitFields.mEmpty) & UNDERRUN_MASK;
Eric Laurent81784c32012-11-19 14:55:58 -08005554 uint32_t recentUnderruns = recentPartial + recentEmpty;
Andy Hung3ff4b552023-06-26 19:20:57 -07005555 track->fastTrackUnderruns() = underruns;
Eric Laurent81784c32012-11-19 14:55:58 -08005556 // don't count underruns that occur while stopping or pausing
5557 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005558 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005559 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5560 recentUnderruns > 0) {
5561 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005562 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005563 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005564 // Immediately account for FastTrack underruns.
Andy Hung3ff4b552023-06-26 19:20:57 -07005565 track->audioTrackServerProxy()->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005566
5567 // This is similar to the state machine for normal tracks,
5568 // with a few modifications for fast tracks.
5569 bool isActive = true;
Andy Hung3ff4b552023-06-26 19:20:57 -07005570 switch (track->state()) {
5571 case IAfTrackBase::STOPPING_1:
Eric Laurent81784c32012-11-19 14:55:58 -08005572 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005573 if (recentUnderruns > 0 || track->isTerminated()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005574 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08005575 }
5576 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005577 case IAfTrackBase::PAUSING:
Eric Laurent81784c32012-11-19 14:55:58 -08005578 // ramp down is not yet implemented
5579 track->setPaused();
5580 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005581 case IAfTrackBase::RESUMING:
Eric Laurent81784c32012-11-19 14:55:58 -08005582 // ramp up is not yet implemented
Andy Hung3ff4b552023-06-26 19:20:57 -07005583 track->setState(IAfTrackBase::ACTIVE);
Eric Laurent81784c32012-11-19 14:55:58 -08005584 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005585 case IAfTrackBase::ACTIVE:
Eric Laurent81784c32012-11-19 14:55:58 -08005586 if (recentFull > 0 || recentPartial > 0) {
5587 // track has provided at least some frames recently: reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07005588 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08005589 }
5590 if (recentUnderruns == 0) {
5591 // no recent underruns: stay active
5592 break;
5593 }
5594 // there has recently been an underrun of some kind
5595 if (track->sharedBuffer() == 0) {
5596 // were any of the recent underruns "empty" (no frames available)?
5597 if (recentEmpty == 0) {
5598 // no, then ignore the partial underruns as they are allowed indefinitely
5599 break;
5600 }
5601 // there has recently been an "empty" underrun: decrement the retry counter
Andy Hung3ff4b552023-06-26 19:20:57 -07005602 if (--(track->retryCount()) > 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005603 break;
5604 }
5605 // indicate to client process that the track was disabled because of underrun;
5606 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005607 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005608 // remove from active list, but state remains ACTIVE [confusing but true]
5609 isActive = false;
5610 break;
5611 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005612 FALLTHROUGH_INTENDED;
Andy Hung3ff4b552023-06-26 19:20:57 -07005613 case IAfTrackBase::STOPPING_2:
5614 case IAfTrackBase::PAUSED:
5615 case IAfTrackBase::STOPPED:
5616 case IAfTrackBase::FLUSHED: // flush() while active
Eric Laurent81784c32012-11-19 14:55:58 -08005617 // Check for presentation complete if track is inactive
5618 // We have consumed all the buffers of this track.
5619 // This would be incomplete if we auto-paused on underrun
5620 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005621 uint32_t latency = 0;
5622 status_t result = mOutput->stream->getLatency(&latency);
5623 ALOGE_IF(result != OK,
5624 "Error when retrieving output stream latency: %d", result);
5625 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005626 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005627 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5628 // track stays in active list until presentation is complete
5629 break;
5630 }
5631 }
5632 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005633 track->setState(IAfTrackBase::STOPPED);
Eric Laurent81784c32012-11-19 14:55:58 -08005634 }
5635 if (track->isStopped()) {
5636 // Can't reset directly, as fast mixer is still polling this track
5637 // track->reset();
5638 // So instead mark this track as needing to be reset after push with ack
5639 resetMask |= 1 << i;
5640 }
5641 isActive = false;
5642 break;
Andy Hung3ff4b552023-06-26 19:20:57 -07005643 case IAfTrackBase::IDLE:
Eric Laurent81784c32012-11-19 14:55:58 -08005644 default:
Andy Hung3ff4b552023-06-26 19:20:57 -07005645 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->state());
Eric Laurent81784c32012-11-19 14:55:58 -08005646 }
5647
5648 if (isActive) {
5649 // was it previously inactive?
5650 if (!(state->mTrackMask & (1 << j))) {
Andy Hung3ff4b552023-06-26 19:20:57 -07005651 ExtendedAudioBufferProvider *eabp = track->asExtendedAudioBufferProvider();
5652 VolumeProvider *vp = track->asVolumeProvider();
Eric Laurent81784c32012-11-19 14:55:58 -08005653 fastTrack->mBufferProvider = eabp;
5654 fastTrack->mVolumeProvider = vp;
Andy Hung3ff4b552023-06-26 19:20:57 -07005655 fastTrack->mChannelMask = track->channelMask();
5656 fastTrack->mFormat = track->format();
jiabin245cdd92018-12-07 17:55:15 -08005657 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005658 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005659 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005660 fastTrack->mGeneration++;
5661 state->mTrackMask |= 1 << j;
5662 didModify = true;
5663 // no acknowledgement required for newly active tracks
5664 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005665 sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Eric Laurenteab90452019-06-24 15:17:46 -07005666 float volume;
5667 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5668 volume = 0.f;
5669 } else {
5670 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5671 }
5672
5673 handleVoipVolume_l(&volume);
5674
Eric Laurent81784c32012-11-19 14:55:58 -08005675 // cache the combined master volume and stream type volume for fast mixer; this
5676 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005677 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005678 proxy->framesReleased()).first;
5679 volume *= vh;
Andy Hung3ff4b552023-06-26 19:20:57 -07005680 track->setCachedVolume(volume);
Kevin Rocard12381092018-04-11 09:19:59 -07005681 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Vlad Popae2f5aef2022-07-25 16:00:20 +02005682 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5683 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005684
Andy Hung2cbc2722023-07-17 17:05:00 -07005685 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005686 /*muteState=*/{masterVolume == 0.f,
5687 mStreamTypes[track->streamType()].volume == 0.f,
5688 mStreamTypes[track->streamType()].mute,
5689 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005690 vlf == 0.f && vrf == 0.f,
5691 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005692
5693 vlf *= volume;
5694 vrf *= volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005695
jiabin76d94692022-12-15 21:51:21 +00005696 track->setFinalVolume(vlf, vrf);
Eric Laurent81784c32012-11-19 14:55:58 -08005697 ++fastTracks;
5698 } else {
5699 // was it previously active?
5700 if (state->mTrackMask & (1 << j)) {
5701 fastTrack->mBufferProvider = NULL;
5702 fastTrack->mGeneration++;
5703 state->mTrackMask &= ~(1 << j);
5704 didModify = true;
5705 // If any fast tracks were removed, we must wait for acknowledgement
5706 // because we're about to decrement the last sp<> on those tracks.
5707 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5708 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005709 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5710 // AudioTrack may start (which may not be with a start() but with a write()
5711 // after underrun) and immediately paused or released. In that case the
5712 // FastTrack state hasn't had time to update.
5713 // TODO Remove the ALOGW when this theory is confirmed.
5714 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005715 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung3ff4b552023-06-26 19:20:57 -07005716 j, (int)track->state(), state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005717 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005718 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005719 }
5720 tracksToRemove->add(track);
5721 // Avoids a misleading display in dumpsys
Andy Hung3ff4b552023-06-26 19:20:57 -07005722 track->fastTrackUnderruns().mBitFields.mMostRecent = UNDERRUN_FULL;
Eric Laurent81784c32012-11-19 14:55:58 -08005723 }
jiabin245cdd92018-12-07 17:55:15 -08005724 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5725 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5726 didModify = true;
5727 }
Eric Laurent81784c32012-11-19 14:55:58 -08005728 continue;
5729 }
5730
5731 { // local variable scope to avoid goto warning
5732
5733 audio_track_cblk_t* cblk = track->cblk();
5734
5735 // The first time a track is added we wait
5736 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005737 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005738
5739 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005740 // use the trackId as the AudioMixer name.
5741 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005742 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005743 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005744 track->channelMask(),
5745 track->format(),
5746 track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005747 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005748 ALOGW("%s(): AudioMixer cannot create track(%d)"
5749 " mask %#x, format %#x, sessionId %d",
5750 __func__, trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07005751 track->channelMask(), track->format(), track->sessionId());
Andy Hung1bc088a2018-02-09 15:57:31 -08005752 tracksToRemove->add(track);
5753 track->invalidate(); // consider it dead.
5754 continue;
5755 }
5756 }
5757
Eric Laurent81784c32012-11-19 14:55:58 -08005758 // make sure that we have enough frames to mix one full buffer.
5759 // enforce this condition only once to enable draining the buffer in case the client
5760 // app does not call stop() and relies on underrun to stop:
5761 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5762 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005763 size_t desiredFrames;
Andy Hung3ff4b552023-06-26 19:20:57 -07005764 const uint32_t sampleRate = track->audioTrackServerProxy()->getSampleRate();
5765 const AudioPlaybackRate playbackRate = track->audioTrackServerProxy()->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005766
5767 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005768 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005769 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5770 // add frames already consumed but not yet released by the resampler
5771 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005772 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005773
Eric Laurent81784c32012-11-19 14:55:58 -08005774 uint32_t minFrames = 1;
5775 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5776 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005777 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005778 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005779
5780 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005781 if (ATRACE_ENABLED()) {
5782 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005783 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005784 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005785 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005786 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005787 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005788 !track->isPaused() && !track->isTerminated())
5789 {
Andy Hungc0691382018-09-12 18:01:57 -07005790 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005791
5792 mixedTracks++;
5793
Andy Hung69aed5f2014-02-25 17:24:40 -08005794 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5795 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005796 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005797 if (track->mainBuffer() != mSinkBuffer &&
5798 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005799 if (mEffectBufferEnabled) {
5800 mEffectBufferValid = true; // Later can set directly.
5801 }
Eric Laurent81784c32012-11-19 14:55:58 -08005802 chain = getEffectChain_l(track->sessionId());
5803 // Delegate volume control to effect in track effect chain if needed
5804 if (chain != 0) {
5805 tracksWithEffect++;
5806 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005807 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005808 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005809 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005810 }
5811 }
5812
5813
5814 int param = AudioMixer::VOLUME;
Andy Hung3ff4b552023-06-26 19:20:57 -07005815 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
Eric Laurent81784c32012-11-19 14:55:58 -08005816 // no ramp for the first volume setting
Andy Hung3ff4b552023-06-26 19:20:57 -07005817 track->fillingStatus() = IAfTrack::FS_ACTIVE;
5818 if (track->state() == IAfTrackBase::RESUMING) {
5819 track->setState(IAfTrackBase::ACTIVE);
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005820 // If a new track is paused immediately after start, do not ramp on resume.
5821 if (cblk->mServer != 0) {
5822 param = AudioMixer::RAMP_VOLUME;
5823 }
Eric Laurent81784c32012-11-19 14:55:58 -08005824 }
Andy Hungc0691382018-09-12 18:01:57 -07005825 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005826 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005827 // FIXME should not make a decision based on mServer
5828 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005829 // If the track is stopped before the first frame was mixed,
5830 // do not apply ramp
5831 param = AudioMixer::RAMP_VOLUME;
5832 }
5833
5834 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005835 uint32_t vl, vr; // in U8.24 integer format
5836 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005837 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005838 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005839 // Always fetch volumeshaper volume to ensure state is updated.
Andy Hung3ff4b552023-06-26 19:20:57 -07005840 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hung333ab962019-05-28 20:23:35 -07005841 const float vh = track->getVolumeHandler()->getVolume(
Andy Hung3ff4b552023-06-26 19:20:57 -07005842 track->audioTrackServerProxy()->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005843
Eric Laurenteab90452019-06-24 15:17:46 -07005844 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5845 v = 0;
5846 }
5847
5848 handleVoipVolume_l(&v);
5849
5850 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005851 vl = vr = 0;
5852 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005853 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005854 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005855 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005856 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5857 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005858 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005859 if (vlf > GAIN_FLOAT_UNITY) {
5860 ALOGV("Track left volume out of range: %.3g", vlf);
5861 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005862 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005863 if (vrf > GAIN_FLOAT_UNITY) {
5864 ALOGV("Track right volume out of range: %.3g", vrf);
5865 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005866 }
Vlad Popae2f5aef2022-07-25 16:00:20 +02005867
Andy Hung2cbc2722023-07-17 17:05:00 -07005868 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae2f5aef2022-07-25 16:00:20 +02005869 /*muteState=*/{masterVolume == 0.f,
5870 mStreamTypes[track->streamType()].volume == 0.f,
5871 mStreamTypes[track->streamType()].mute,
5872 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02005873 vlf == 0.f && vrf == 0.f,
5874 vh == 0.f});
Vlad Popae2f5aef2022-07-25 16:00:20 +02005875
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005876 // now apply the master volume and stream type volume and shaper volume
5877 vlf *= v * vh;
5878 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005879 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005880 // then derive vl and vr as U8.24 versions for the effect chain
5881 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5882 vl = (uint32_t) (scaleto8_24 * vlf);
5883 vr = (uint32_t) (scaleto8_24 * vrf);
5884 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005885 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005886 // send level comes from shared memory and so may be corrupt
5887 if (sendLevel > MAX_GAIN_INT) {
5888 ALOGV("Track send level out of range: %04X", sendLevel);
5889 sendLevel = MAX_GAIN_INT;
5890 }
Andy Hung6be49402014-05-30 10:42:03 -07005891 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5892 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005893 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005894
jiabin76d94692022-12-15 21:51:21 +00005895 track->setFinalVolume(vrf, vlf);
Kevin Rocard12381092018-04-11 09:19:59 -07005896
Eric Laurent81784c32012-11-19 14:55:58 -08005897 // Delegate volume control to effect in track effect chain if needed
5898 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5899 // Do not ramp volume if volume is controlled by effect
5900 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005901 // Update remaining floating point volume levels
5902 vlf = (float)vl / (1 << 24);
5903 vrf = (float)vr / (1 << 24);
Andy Hung3ff4b552023-06-26 19:20:57 -07005904 track->setHasVolumeController(true);
Eric Laurent81784c32012-11-19 14:55:58 -08005905 } else {
5906 // force no volume ramp when volume controller was just disabled or removed
5907 // from effect chain to avoid volume spike
Andy Hung3ff4b552023-06-26 19:20:57 -07005908 if (track->hasVolumeController()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005909 param = AudioMixer::VOLUME;
5910 }
Andy Hung3ff4b552023-06-26 19:20:57 -07005911 track->setHasVolumeController(false);
Eric Laurent81784c32012-11-19 14:55:58 -08005912 }
5913
Eric Laurent81784c32012-11-19 14:55:58 -08005914 // XXX: these things DON'T need to be done each time
Andy Hung3ff4b552023-06-26 19:20:57 -07005915 mAudioMixer->setBufferProvider(trackId, track->asExtendedAudioBufferProvider());
Andy Hungc0691382018-09-12 18:01:57 -07005916 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005917
Andy Hungc0691382018-09-12 18:01:57 -07005918 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5919 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5920 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005921 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005922 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005923 AudioMixer::TRACK,
5924 AudioMixer::FORMAT, (void *)track->format());
5925 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005926 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005927 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005928 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005929
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005930 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005931 mAudioMixer->setParameter(
5932 trackId,
5933 AudioMixer::TRACK,
5934 AudioMixer::MIXER_CHANNEL_MASK,
5935 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5936 } else {
5937 mAudioMixer->setParameter(
5938 trackId,
5939 AudioMixer::TRACK,
5940 AudioMixer::MIXER_CHANNEL_MASK,
5941 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5942 }
5943
Glenn Kastene3aa6592012-12-04 12:22:46 -08005944 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005945 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005946 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005947 if (reqSampleRate == 0) {
5948 reqSampleRate = mSampleRate;
5949 } else if (reqSampleRate > maxSampleRate) {
5950 reqSampleRate = maxSampleRate;
5951 }
Eric Laurent81784c32012-11-19 14:55:58 -08005952 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005953 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005954 AudioMixer::RESAMPLE,
5955 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005956 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005957
Andy Hung8edb8dc2015-03-26 19:13:55 -07005958 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005959 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005960 AudioMixer::TIMESTRETCH,
5961 AudioMixer::PLAYBACK_RATE,
Andy Hung71ba4b32022-10-06 12:09:49 -07005962 // cast away constness for this generic API.
5963 const_cast<void *>(reinterpret_cast<const void *>(&playbackRate)));
Andy Hung8edb8dc2015-03-26 19:13:55 -07005964
Andy Hung69aed5f2014-02-25 17:24:40 -08005965 /*
5966 * Select the appropriate output buffer for the track.
5967 *
Andy Hung98ef9782014-03-04 14:46:50 -08005968 * Tracks with effects go into their own effects chain buffer
5969 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005970 *
5971 * Other tracks can use mMixerBuffer for higher precision
5972 * channel accumulation. If this buffer is enabled
5973 * (mMixerBufferEnabled true), then selected tracks will accumulate
5974 * into it.
5975 *
5976 */
5977 if (mMixerBufferEnabled
5978 && (track->mainBuffer() == mSinkBuffer
5979 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005980 if (mType == SPATIALIZER && !track->isSpatialized()) {
Eric Laurent39095982021-08-24 18:29:27 +02005981 mAudioMixer->setParameter(
5982 trackId,
5983 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005984 AudioMixer::MIXER_FORMAT, (void *)mEffectBufferFormat);
Eric Laurent39095982021-08-24 18:29:27 +02005985 mAudioMixer->setParameter(
5986 trackId,
5987 AudioMixer::TRACK,
Eric Laurentb62d0362021-10-26 17:40:18 +02005988 AudioMixer::MAIN_BUFFER, (void *)mPostSpatializerBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02005989 } else {
5990 mAudioMixer->setParameter(
5991 trackId,
5992 AudioMixer::TRACK,
5993 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5994 mAudioMixer->setParameter(
5995 trackId,
5996 AudioMixer::TRACK,
5997 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5998 // TODO: override track->mainBuffer()?
5999 mMixerBufferValid = true;
6000 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006001 } else {
6002 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006003 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006004 AudioMixer::TRACK,
Andy Hung319587b2023-05-23 14:01:03 -07006005 AudioMixer::MIXER_FORMAT, (void *)AUDIO_FORMAT_PCM_FLOAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08006006 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006007 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08006008 AudioMixer::TRACK,
6009 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
6010 }
Eric Laurent81784c32012-11-19 14:55:58 -08006011 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07006012 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08006013 AudioMixer::TRACK,
6014 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08006015 mAudioMixer->setParameter(
6016 trackId,
6017 AudioMixer::TRACK,
6018 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08006019 mAudioMixer->setParameter(
6020 trackId,
6021 AudioMixer::TRACK,
6022 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Andy Hung3ff4b552023-06-26 19:20:57 -07006023 const float hapticMaxAmplitude = track->getHapticMaxAmplitude();
Lais Andradebc3f37a2021-07-02 00:13:19 +01006024 mAudioMixer->setParameter(
6025 trackId,
6026 AudioMixer::TRACK,
Andy Hung3ff4b552023-06-26 19:20:57 -07006027 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)&hapticMaxAmplitude);
Eric Laurent81784c32012-11-19 14:55:58 -08006028
6029 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006030 track->retryCount() = kMaxTrackRetries;
Eric Laurent81784c32012-11-19 14:55:58 -08006031
6032 // If one track is ready, set the mixer ready if:
6033 // - the mixer was not ready during previous round OR
6034 // - no other track is not ready
6035 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
6036 mixerStatus != MIXER_TRACKS_ENABLED) {
6037 mixerStatus = MIXER_TRACKS_READY;
6038 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08006039
6040 // Enable the next few lines to instrument a test for underrun log handling.
6041 // TODO: Remove when we have a better way of testing the underrun log.
6042#if 0
6043 static int i;
6044 if ((++i & 0xf) == 0) {
6045 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
6046 }
6047#endif
Eric Laurent81784c32012-11-19 14:55:58 -08006048 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07006049 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006050 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08006051 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
6052 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07006053 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08006054 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07006055 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08006056
Eric Laurent81784c32012-11-19 14:55:58 -08006057 // clear effect chain input buffer if an active track underruns to avoid sending
6058 // previous audio buffer again to effects
6059 chain = getEffectChain_l(track->sessionId());
6060 if (chain != 0) {
6061 chain->clearInputBuffer();
6062 }
6063
Andy Hungc0691382018-09-12 18:01:57 -07006064 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006065 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
6066 track->isStopped() || track->isPaused()) {
6067 // We have consumed all the buffers of this track.
6068 // Remove it from the list of active tracks.
6069 // TODO: use actual buffer filling status instead of latency when available from
6070 // audio HAL
6071 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006072 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006073 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
6074 if (track->isStopped()) {
6075 track->reset();
6076 }
6077 tracksToRemove->add(track);
6078 }
6079 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08006080 // No buffers for this track. Give it a few chances to
6081 // fill a buffer, then remove it from active list.
Andy Hung3ff4b552023-06-26 19:20:57 -07006082 if (--(track->retryCount()) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07006083 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
6084 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08006085 tracksToRemove->add(track);
6086 // indicate to client process that the track was disabled because of underrun;
6087 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006088 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08006089 // If one track is not ready, mark the mixer also not ready if:
6090 // - the mixer was ready during previous round OR
6091 // - no other track is ready
6092 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
6093 mixerStatus != MIXER_TRACKS_READY) {
6094 mixerStatus = MIXER_TRACKS_ENABLED;
6095 }
6096 }
Andy Hungc0691382018-09-12 18:01:57 -07006097 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08006098 }
6099
6100 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08006101
6102 }
6103
jiabin245cdd92018-12-07 17:55:15 -08006104 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
6105 // When there is no fast track playing haptic and FastMixer exists,
6106 // enabling the first FastTrack, which provides mixed data from normal
6107 // tracks, to play haptic data.
6108 FastTrack *fastTrack = &state->mFastTracks[0];
6109 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
6110 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
6111 didModify = true;
6112 }
6113 }
6114
Eric Laurent81784c32012-11-19 14:55:58 -08006115 // Push the new FastMixer state if necessary
Jing Mike537412f2023-03-12 11:01:47 +08006116 [[maybe_unused]] bool pauseAudioWatchdog = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006117 if (didModify) {
6118 state->mFastTracksGen++;
6119 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
6120 if (kUseFastMixer == FastMixer_Dynamic &&
6121 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
6122 state->mCommand = FastMixerState::COLD_IDLE;
6123 state->mColdFutexAddr = &mFastMixerFutex;
6124 state->mColdGen++;
6125 mFastMixerFutex = 0;
6126 if (kUseFastMixer == FastMixer_Dynamic) {
6127 mNormalSink = mOutputSink;
6128 }
6129 // If we go into cold idle, need to wait for acknowledgement
6130 // so that fast mixer stops doing I/O.
6131 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
6132 pauseAudioWatchdog = true;
6133 }
Eric Laurent81784c32012-11-19 14:55:58 -08006134 }
6135 if (sq != NULL) {
6136 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08006137 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
6138 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
6139 // when bringing the output sink into standby.)
6140 //
6141 // We will get the latest FastMixer state when we come out of COLD_IDLE.
6142 //
6143 // This occurs with BT suspend when we idle the FastMixer with
6144 // active tracks, which may be added or removed.
6145 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08006146 }
6147#ifdef AUDIO_WATCHDOG
6148 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
6149 mAudioWatchdog->pause();
6150 }
6151#endif
6152
6153 // Now perform the deferred reset on fast tracks that have stopped
6154 while (resetMask != 0) {
6155 size_t i = __builtin_ctz(resetMask);
6156 ALOG_ASSERT(i < count);
6157 resetMask &= ~(1 << i);
Andy Hung3ff4b552023-06-26 19:20:57 -07006158 sp<IAfTrack> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08006159 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
6160 track->reset();
6161 }
6162
Andy Hung80d03d22018-04-10 10:32:11 -07006163 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
6164 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
6165 // it ceases to be active, to allow safe removal from the AudioMixer at the start
6166 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
6167 // See also the implementation of destroyTrack_l().
6168 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07006169 const int trackId = track->id();
6170 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
6171 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07006172 }
6173 }
6174
Eric Laurent81784c32012-11-19 14:55:58 -08006175 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006176 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006177
Eric Laurentb3f315a2021-07-13 15:09:05 +02006178 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
6179 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07006180 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07006181 }
6182
6183 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07006184 // as long as there are effects we should clear the effects buffer, to avoid
6185 // passing a non-clean buffer to the effect chain
6186 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurentb62d0362021-10-26 17:40:18 +02006187 if (mType == SPATIALIZER) {
6188 memset(mPostSpatializerBuffer, 0, mPostSpatializerBufferSize);
6189 }
Eric Laurent97d547d2014-09-02 14:45:53 -07006190 }
Andy Hung69aed5f2014-02-25 17:24:40 -08006191 // sink or mix buffer must be cleared if all tracks are connected to an
6192 // effect chain as in this case the mixer will not write to the sink or mix buffer
6193 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02006194 // always clear sink buffer for spatializer output as the output of the spatializer
6195 // effect will be accumulated into it
6196 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6197 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08006198 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08006199 if (mMixerBufferValid) {
6200 memset(mMixerBuffer, 0, mMixerBufferSize);
6201 // TODO: In testing, mSinkBuffer below need not be cleared because
6202 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
6203 // after mixing.
6204 //
6205 // To enforce this guarantee:
6206 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
6207 // (mixedTracks == 0 && fastTracks > 0))
6208 // must imply MIXER_TRACKS_READY.
6209 // Later, we may clear buffers regardless, and skip much of this logic.
6210 }
Andy Hung98ef9782014-03-04 14:46:50 -08006211 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07006212 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006213 }
6214
6215 // if any fast tracks, then status is ready
6216 mMixerStatusIgnoringFastTracks = mixerStatus;
6217 if (fastTracks > 0) {
6218 mixerStatus = MIXER_TRACKS_READY;
6219 }
6220 return mixerStatus;
6221}
6222
Andy Hung87e82412023-08-29 14:26:09 -07006223// trackCountForUid_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07006224uint32_t PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07006225{
6226 uint32_t trackCount = 0;
6227 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08006228 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07006229 trackCount++;
6230 }
6231 }
6232 return trackCount;
6233}
6234
Andy Hung71742ab2023-07-07 13:47:37 -07006235bool PlaybackThread::IsTimestampAdvancing::check(AudioStreamOut* output)
ziyangch8f194f12021-12-01 13:48:04 -08006236{
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006237 // Check the timestamp to see if it's advancing once every 150ms. If we check too frequently, we
6238 // could falsely detect that the frame position has stalled due to underrun because we haven't
6239 // given the Audio HAL enough time to update.
6240 const nsecs_t nowNs = systemTime();
6241 if (nowNs - mPreviousNs < mMinimumTimeBetweenChecksNs) {
6242 return mLatchedValue;
6243 }
6244 mPreviousNs = nowNs;
6245 mLatchedValue = false;
6246 // Determine if the presentation position is still advancing.
ziyangch8f194f12021-12-01 13:48:04 -08006247 uint64_t position = 0;
6248 struct timespec unused;
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006249 const status_t ret = output->getPresentationPosition(&position, &unused);
ziyangch8f194f12021-12-01 13:48:04 -08006250 if (ret == NO_ERROR) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006251 if (position != mPreviousPosition) {
6252 mPreviousPosition = position;
6253 mLatchedValue = true;
ziyangch8f194f12021-12-01 13:48:04 -08006254 }
6255 }
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006256 return mLatchedValue;
6257}
6258
Andy Hung71742ab2023-07-07 13:47:37 -07006259void PlaybackThread::IsTimestampAdvancing::clear()
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006260{
6261 mLatchedValue = true;
6262 mPreviousPosition = 0;
6263 mPreviousNs = 0;
ziyangch8f194f12021-12-01 13:48:04 -08006264}
6265
Andy Hung87e82412023-08-29 14:26:09 -07006266// isTrackAllowed_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07006267bool MixerThread::isTrackAllowed_l(
Andy Hung1bc088a2018-02-09 15:57:31 -08006268 audio_channel_mask_t channelMask, audio_format_t format,
6269 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08006270{
Andy Hung1bc088a2018-02-09 15:57:31 -08006271 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
6272 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07006273 }
Andy Hung1bc088a2018-02-09 15:57:31 -08006274 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006275 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006276 ALOGW("%s: invalid format: %#x", __func__, format);
6277 return false;
6278 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07006279 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08006280 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
6281 return false;
6282 }
6283 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08006284}
6285
Andy Hung87e82412023-08-29 14:26:09 -07006286// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07006287bool MixerThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006288 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006289{
Eric Laurent81784c32012-11-19 14:55:58 -08006290 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006291 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006292
Glenn Kastenc05b8d72016-03-24 09:48:17 -07006293 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08006294
Eric Laurent10351942014-05-08 18:49:52 -07006295 AudioParameter param = AudioParameter(keyValuePair);
6296 int value;
6297 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
6298 reconfig = true;
6299 }
6300 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hungf8ab4692023-07-20 21:44:14 -07006301 if (!isValidPcmSinkFormat(static_cast<audio_format_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006302 status = BAD_VALUE;
6303 } else {
6304 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08006305 reconfig = true;
6306 }
Eric Laurent10351942014-05-08 18:49:52 -07006307 }
6308 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hungf8ab4692023-07-20 21:44:14 -07006309 if (!isValidPcmSinkChannelMask(static_cast<audio_channel_mask_t>(value))) {
Eric Laurent10351942014-05-08 18:49:52 -07006310 status = BAD_VALUE;
6311 } else {
6312 // no need to save value, since it's constant
6313 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006314 }
Eric Laurent10351942014-05-08 18:49:52 -07006315 }
6316 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6317 // do not accept frame count changes if tracks are open as the track buffer
6318 // size depends on frame count and correct behavior would not be guaranteed
6319 // if frame count is changed after track creation
6320 if (!mTracks.isEmpty()) {
6321 status = INVALID_OPERATION;
6322 } else {
6323 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08006324 }
Eric Laurent10351942014-05-08 18:49:52 -07006325 }
6326 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006327 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07006328 }
Eric Laurent81784c32012-11-19 14:55:58 -08006329
Eric Laurent10351942014-05-08 18:49:52 -07006330 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006331 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006332 if (!mStandby && status == INVALID_OPERATION) {
Andy Hungb72a5502023-03-27 15:53:06 -07006333 ALOGW("%s: setParameters failed with keyValuePair %s, entering standby",
6334 __func__, keyValuePair.c_str());
Phil Burk062e67a2015-02-11 13:40:50 -08006335 mOutput->standby();
Andy Hungb72a5502023-03-27 15:53:06 -07006336 mThreadMetrics.logEndInterval();
6337 mThreadSnapshot.onEnd();
Andy Hungdda7aed2023-03-27 15:53:06 -07006338 setStandby_l();
Eric Laurent10351942014-05-08 18:49:52 -07006339 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006340 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08006341 }
Eric Laurent10351942014-05-08 18:49:52 -07006342 if (status == NO_ERROR && reconfig) {
6343 readOutputParameters_l();
6344 delete mAudioMixer;
6345 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08006346 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07006347 const int trackId = track->id();
Andy Hung71ba4b32022-10-06 12:09:49 -07006348 const status_t createStatus = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07006349 trackId,
Andy Hung3ff4b552023-06-26 19:20:57 -07006350 track->channelMask(),
6351 track->format(),
6352 track->sessionId());
Andy Hung71ba4b32022-10-06 12:09:49 -07006353 ALOGW_IF(createStatus != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07006354 "%s(): AudioMixer cannot create track(%d)"
6355 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08006356 __func__,
Andy Hung3ff4b552023-06-26 19:20:57 -07006357 trackId, track->channelMask(), track->format(), track->sessionId());
Eric Laurent10351942014-05-08 18:49:52 -07006358 }
Eric Laurent73e26b62015-04-27 16:55:58 -07006359 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006360 }
Eric Laurent81784c32012-11-19 14:55:58 -08006361 }
6362
Dean Wheatley68918102021-03-19 22:09:19 +11006363 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006364}
6365
6366
Andy Hung71742ab2023-07-07 13:47:37 -07006367void MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08006368{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006369 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07006370 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08006371 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08006372 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006373 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
6374 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
6375 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006376 if (hasFastMixer()) {
6377 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
6378
6379 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
6380 // while we are dumping it. It may be inconsistent, but it won't mutate!
6381 // This is a large object so we place it on the heap.
6382 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07006383 const std::unique_ptr<FastMixerDumpState> copy =
6384 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006385 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006386
6387#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006388 // Similar for state queue
6389 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
6390 observerCopy.dump(fd);
6391 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
6392 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08006393#endif
6394
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08006395#ifdef AUDIO_WATCHDOG
6396 if (mAudioWatchdog != 0) {
6397 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
6398 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
6399 wdCopy.dump(fd);
6400 }
6401#endif
6402
6403 } else {
6404 dprintf(fd, " No FastMixer\n");
6405 }
Eric Laurent90cea102023-05-15 15:08:27 +02006406
6407 dprintf(fd, "Bluetooth latency modes are %senabled\n",
6408 mBluetoothLatencyModesEnabled ? "" : "not ");
6409 dprintf(fd, "HAL does %ssupport Bluetooth latency modes\n", mOutput != nullptr &&
6410 mOutput->audioHwDev->supportsBluetoothVariableLatency() ? "" : "not ");
6411 dprintf(fd, "Supported latency modes: %s\n", toString(mSupportedLatencyModes).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -08006412}
6413
Andy Hung71742ab2023-07-07 13:47:37 -07006414uint32_t MixerThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006415{
6416 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
6417}
6418
Andy Hung71742ab2023-07-07 13:47:37 -07006419uint32_t MixerThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08006420{
6421 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
6422}
6423
Andy Hung71742ab2023-07-07 13:47:37 -07006424void MixerThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08006425{
6426 PlaybackThread::cacheParameters_l();
6427
6428 // FIXME: Relaxed timing because of a certain device that can't meet latency
6429 // Should be reduced to 2x after the vendor fixes the driver issue
6430 // increase threshold again due to low power audio mode. The way this warning
6431 // threshold is calculated and its usefulness should be reconsidered anyway.
6432 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
6433}
6434
Andy Hung71742ab2023-07-07 13:47:37 -07006435void MixerThread::onHalLatencyModesChanged_l() {
Andy Hung2cbc2722023-07-17 17:05:00 -07006436 mAfThreadCallback->onSupportedLatencyModesChanged(mId, mSupportedLatencyModes);
Eric Laurentb0463942022-12-20 16:31:10 +01006437}
6438
Andy Hung71742ab2023-07-07 13:47:37 -07006439void MixerThread::setHalLatencyMode_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006440 // Only handle latency mode if:
6441 // - mBluetoothLatencyModesEnabled is true
6442 // - the HAL supports latency modes
6443 // - the selected device is Bluetooth LE or A2DP
6444 if (!mBluetoothLatencyModesEnabled.load() || mSupportedLatencyModes.empty()) {
6445 return;
6446 }
6447 if (mOutDeviceTypeAddrs.size() != 1
6448 || !(audio_is_a2dp_out_device(mOutDeviceTypeAddrs[0].mType)
6449 || audio_is_ble_out_device(mOutDeviceTypeAddrs[0].mType))) {
6450 return;
6451 }
6452
6453 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
6454 if (mSupportedLatencyModes.size() == 1) {
6455 // If the HAL only support one latency mode currently, confirm the choice
6456 latencyMode = mSupportedLatencyModes[0];
6457 } else if (mSupportedLatencyModes.size() > 1) {
6458 // Request low latency if:
6459 // - At least one active track is either:
6460 // - a fast track with gaming usage or
6461 // - a track with acessibility usage
6462 for (const auto& track : mActiveTracks) {
6463 if ((track->isFastTrack() && track->attributes().usage == AUDIO_USAGE_GAME)
6464 || track->attributes().usage == AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) {
6465 latencyMode = AUDIO_LATENCY_MODE_LOW;
6466 break;
6467 }
6468 }
6469 }
6470
6471 if (latencyMode != mSetLatencyMode) {
6472 status_t status = mOutput->stream->setLatencyMode(latencyMode);
6473 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
6474 __func__, mId, toString(latencyMode).c_str(), status);
6475 if (status == NO_ERROR) {
6476 mSetLatencyMode = latencyMode;
6477 }
6478 }
6479}
6480
Andy Hung71742ab2023-07-07 13:47:37 -07006481void MixerThread::updateHalSupportedLatencyModes_l() {
Eric Laurentb0463942022-12-20 16:31:10 +01006482
6483 if (mOutput == nullptr || mOutput->stream == nullptr) {
6484 return;
6485 }
6486 std::vector<audio_latency_mode_t> latencyModes;
6487 const status_t status = mOutput->stream->getRecommendedLatencyModes(&latencyModes);
6488 if (status != NO_ERROR) {
6489 latencyModes.clear();
6490 }
6491 if (latencyModes != mSupportedLatencyModes) {
6492 ALOGD("%s: thread(%d) status %d supported latency modes: %s",
6493 __func__, mId, status, toString(latencyModes).c_str());
6494 mSupportedLatencyModes.swap(latencyModes);
6495 sendHalLatencyModesChangedEvent_l();
6496 }
6497}
6498
Andy Hung71742ab2023-07-07 13:47:37 -07006499status_t MixerThread::getSupportedLatencyModes(
Eric Laurentb0463942022-12-20 16:31:10 +01006500 std::vector<audio_latency_mode_t>* modes) {
6501 if (modes == nullptr) {
6502 return BAD_VALUE;
6503 }
Andy Hungf79092d2023-08-31 16:13:39 -07006504 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006505 *modes = mSupportedLatencyModes;
6506 return NO_ERROR;
6507}
6508
Andy Hung71742ab2023-07-07 13:47:37 -07006509void MixerThread::onRecommendedLatencyModeChanged(
Eric Laurentb0463942022-12-20 16:31:10 +01006510 std::vector<audio_latency_mode_t> modes) {
Andy Hungf79092d2023-08-31 16:13:39 -07006511 audio_utils::lock_guard _l(mutex());
Eric Laurentb0463942022-12-20 16:31:10 +01006512 if (modes != mSupportedLatencyModes) {
6513 ALOGD("%s: thread(%d) supported latency modes: %s",
6514 __func__, mId, toString(modes).c_str());
6515 mSupportedLatencyModes.swap(modes);
6516 sendHalLatencyModesChangedEvent_l();
6517 }
6518}
6519
Andy Hung71742ab2023-07-07 13:47:37 -07006520status_t MixerThread::setBluetoothVariableLatencyEnabled(bool enabled) {
Eric Laurentb0463942022-12-20 16:31:10 +01006521 if (mOutput == nullptr || mOutput->audioHwDev == nullptr
6522 || !mOutput->audioHwDev->supportsBluetoothVariableLatency()) {
6523 return INVALID_OPERATION;
6524 }
6525 mBluetoothLatencyModesEnabled.store(enabled);
6526 return NO_ERROR;
6527}
6528
Eric Laurent81784c32012-11-19 14:55:58 -08006529// ----------------------------------------------------------------------------
6530
Andy Hung71742ab2023-07-07 13:47:37 -07006531/* static */
6532sp<IAfPlaybackThread> IAfPlaybackThread::createDirectOutputThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07006533 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07006534 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
6535 const audio_offload_info_t& offloadInfo) {
6536 return sp<DirectOutputThread>::make(
Andy Hung2cbc2722023-07-17 17:05:00 -07006537 afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07006538}
6539
Andy Hung2cbc2722023-07-17 17:05:00 -07006540DirectOutputThread::DirectOutputThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07006541 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady,
6542 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07006543 : PlaybackThread(afThreadCallback, output, id, type, systemReady)
Gareth Fenn56576722022-10-05 13:42:36 -07006544 , mOffloadInfo(offloadInfo)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006545{
Andy Hung2cbc2722023-07-17 17:05:00 -07006546 setMasterBalance(afThreadCallback->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006547}
6548
Andy Hung71742ab2023-07-07 13:47:37 -07006549DirectOutputThread::~DirectOutputThread()
Eric Laurent81784c32012-11-19 14:55:58 -08006550{
6551}
6552
Andy Hung71742ab2023-07-07 13:47:37 -07006553void DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006554{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006555 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006556 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
6557 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
6558}
6559
Andy Hung71742ab2023-07-07 13:47:37 -07006560void DirectOutputThread::setMasterBalance(float balance)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006561{
Andy Hungf79092d2023-08-31 16:13:39 -07006562 audio_utils::lock_guard _l(mutex());
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006563 if (mMasterBalance != balance) {
6564 mMasterBalance.store(balance);
6565 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
6566 broadcast_l();
6567 }
6568}
6569
Andy Hung71742ab2023-07-07 13:47:37 -07006570void DirectOutputThread::processVolume_l(IAfTrack* track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006571{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006572 float left, right;
6573
Andy Hung333ab962019-05-28 20:23:35 -07006574 // Ensure volumeshaper state always advances even when muted.
Andy Hung3ff4b552023-06-26 19:20:57 -07006575 const sp<AudioTrackServerProxy> proxy = track->audioTrackServerProxy();
Andy Hungee86cee2022-12-13 19:19:53 -08006576
Andy Hungee86cee2022-12-13 19:19:53 -08006577 const int64_t frames = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
6578 const int64_t time = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
6579
Dean Wheatleyb11b0022023-09-12 04:07:35 +10006580 ALOGVV("%s: Direct/Offload bufferConsumed:%zu timestamp frames:%lld time:%lld",
6581 __func__, proxy->framesReleased(), (long long)frames, (long long)time);
Andy Hungee86cee2022-12-13 19:19:53 -08006582
6583 const int64_t volumeShaperFrames =
6584 mMonotonicFrameCounter.updateAndGetMonotonicFrameCount(frames, time);
6585 const auto [shaperVolume, shaperActive] =
6586 track->getVolumeHandler()->getVolume(volumeShaperFrames);
Andy Hung333ab962019-05-28 20:23:35 -07006587 mVolumeShaperActive = shaperActive;
6588
Vlad Popae2f5aef2022-07-25 16:00:20 +02006589 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
6590 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6591 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6592
6593 const bool clientVolumeMute = (left == 0.f && right == 0.f);
6594
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08006595 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006596 left = right = 0;
6597 } else {
6598 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07006599 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08006600
Glenn Kastenc56f3422014-03-21 17:53:17 -07006601 if (left > GAIN_FLOAT_UNITY) {
6602 left = GAIN_FLOAT_UNITY;
6603 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07006604 if (right > GAIN_FLOAT_UNITY) {
6605 right = GAIN_FLOAT_UNITY;
6606 }
zhangjincheng73e73872023-01-16 17:17:38 +08006607 left *= v;
6608 right *= v;
Andy Hung2cbc2722023-07-17 17:05:00 -07006609 if (mAfThreadCallback->getMode() != AUDIO_MODE_IN_COMMUNICATION
zhangjincheng73e73872023-01-16 17:17:38 +08006610 || audio_channel_count_from_out_mask(mChannelMask) > 1) {
6611 left *= mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
6612 right *= mMasterBalanceRight;
6613 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006614 }
6615
Andy Hung2cbc2722023-07-17 17:05:00 -07006616 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popae8d99472022-06-30 16:02:48 +02006617 /*muteState=*/{mMasterMute,
6618 mStreamTypes[track->streamType()].volume == 0.f,
6619 mStreamTypes[track->streamType()].mute,
Vlad Popae2f5aef2022-07-25 16:00:20 +02006620 track->isPlaybackRestricted(),
Vlad Popa436c9172022-08-02 15:25:08 +02006621 clientVolumeMute,
6622 shaperVolume == 0.f});
Vlad Popae8d99472022-06-30 16:02:48 +02006623
Eric Laurentbfb1b832013-01-07 09:53:42 -08006624 if (lastTrack) {
jiabin76d94692022-12-15 21:51:21 +00006625 track->setFinalVolume(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006626 if (left != mLeftVolFloat || right != mRightVolFloat) {
6627 mLeftVolFloat = left;
6628 mRightVolFloat = right;
6629
Eric Laurentbfb1b832013-01-07 09:53:42 -08006630 // Delegate volume control to effect in track effect chain if needed
6631 // only one effect chain can be present on DirectOutputThread, so if
6632 // there is one, the track is connected to it
6633 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006634 // if effect chain exists, volume is handled by it.
6635 // Convert volumes from float to 8.24
6636 uint32_t vl = (uint32_t)(left * (1 << 24));
6637 uint32_t vr = (uint32_t)(right * (1 << 24));
6638 // Direct/Offload effect chains set output volume in setVolume_l().
6639 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6640 } else {
6641 // otherwise we directly set the volume.
6642 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006643 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006644 }
6645 }
6646}
6647
Andy Hung71742ab2023-07-07 13:47:37 -07006648void DirectOutputThread::onAddNewTrack_l()
Phil Burk43b4dcc2015-06-09 16:53:44 -07006649{
Andy Hung3ff4b552023-06-26 19:20:57 -07006650 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
6651 sp<IAfTrack> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006652
Eric Laurent0f0631e2015-07-06 18:01:25 -07006653 if (previousTrack != 0 && latestTrack != 0) {
6654 if (mType == DIRECT) {
6655 if (previousTrack.get() != latestTrack.get()) {
6656 mFlushPending = true;
6657 }
6658 } else /* mType == OFFLOAD */ {
Dean Wheatley0f51fd02022-08-31 16:41:40 +10006659 if (previousTrack->sessionId() != latestTrack->sessionId() ||
6660 previousTrack->isFlushPending()) {
Eric Laurent0f0631e2015-07-06 18:01:25 -07006661 mFlushPending = true;
6662 }
6663 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006664 } else if (previousTrack == 0) {
6665 // there could be an old track added back during track transition for direct
6666 // output, so always issues flush to flush data of the previous track if it
6667 // was already destroyed with HAL paused, then flush can resume the playback
6668 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006669 }
6670 PlaybackThread::onAddNewTrack_l();
6671}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006672
Andy Hung71742ab2023-07-07 13:47:37 -07006673PlaybackThread::mixer_state DirectOutputThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07006674 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurent81784c32012-11-19 14:55:58 -08006675)
6676{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006677 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006678 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006679 bool doHwPause = false;
6680 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006681
6682 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07006683 for (const sp<IAfTrack>& t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006684 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006685 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006686 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006687 continue;
6688 }
6689
Andy Hung3ff4b552023-06-26 19:20:57 -07006690 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006691#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006692 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006693#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006694 // Only consider last track started for volume and mixer state control.
6695 // In theory an older track could underrun and restart after the new one starts
6696 // but as we only care about the transition phase between two tracks on a
6697 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07006698 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006699 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006700
Kuowei Li23666472021-01-20 10:23:25 +08006701 if (track->isPausePending()) {
6702 track->pauseAck();
6703 // It is possible a track might have been flushed or stopped.
6704 // Other operations such as flush pending might occur on the next prepare.
6705 if (track->isPausing()) {
6706 track->setPaused();
6707 }
6708 // Always perform pause, as an immediate flush will change
6709 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006710 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006711 doHwPause = true;
6712 mHwPaused = true;
6713 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006714 } else if (track->isFlushPending()) {
6715 track->flushAck();
6716 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006717 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006718 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006719 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006720 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006721 if (last) {
6722 mLeftVolFloat = mRightVolFloat = -1.0;
6723 if (mHwPaused) {
6724 doHwResume = true;
6725 mHwPaused = false;
6726 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006727 }
6728 }
6729
Eric Laurent81784c32012-11-19 14:55:58 -08006730 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006731 // for all its buffers to be filled before processing it.
6732 // Allow draining the buffer in case the client
6733 // app does not call stop() and relies on underrun to stop:
Andy Hung3ff4b552023-06-26 19:20:57 -07006734 // hence the test on (track->retryCount() > 1).
6735 // If track->retryCount() <= 1 then track is about to be disabled, paused, removed,
Andy Hung455982f2021-04-27 17:46:12 -07006736 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6737 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006738 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006739
6740 // target retry count that we will use is based on the time we wait for retries.
6741 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6742 // the retry threshold is when we accept any size for PCM data. This is slightly
6743 // smaller than the retry count so we can push small bits of data without a glitch.
6744 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006745 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006746 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung3ff4b552023-06-26 19:20:57 -07006747 && (track->retryCount() > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006748 minFrames = mNormalFrameCount;
6749 } else {
6750 minFrames = 1;
6751 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006752
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006753 const size_t framesReady = track->framesReady();
6754 const int trackId = track->id();
6755 if (ATRACE_ENABLED()) {
6756 std::string traceName("nRdy");
6757 traceName += std::to_string(trackId);
6758 ATRACE_INT(traceName.c_str(), framesReady);
6759 }
6760 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006761 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006762 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006763 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006764
Andy Hung3ff4b552023-06-26 19:20:57 -07006765 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
6766 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006767 if (last) {
6768 // make sure processVolume_l() will apply new volume even if 0
6769 mLeftVolFloat = mRightVolFloat = -1.0;
6770 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006771 if (!mHwSupportsPause) {
6772 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006773 }
6774 }
6775
6776 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006777 processVolume_l(track, last);
6778 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006779 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006780 if (previousTrack != 0) {
6781 if (track != previousTrack.get()) {
6782 // Flush any data still being written from last track
6783 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006784 // Invalidate previous track to force a seek when resuming.
6785 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006786 }
6787 }
6788 mPreviousTrack = track;
6789
Eric Laurentd595b7c2013-04-03 17:27:56 -07006790 // reset retry count
Andy Hung3ff4b552023-06-26 19:20:57 -07006791 track->retryCount() = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006792 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006793 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006794 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006795 doHwResume = true;
6796 mHwPaused = false;
6797 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006798 }
Eric Laurent81784c32012-11-19 14:55:58 -08006799 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006800 // clear effect chain input buffer if the last active track started underruns
6801 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006802 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006803 mEffectChains[0]->clearInputBuffer();
6804 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006805 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006806 track->setState(IAfTrackBase::STOPPING_2);
Eric Laurentb369caf2015-03-30 20:51:47 -07006807 if (last && mHwPaused) {
6808 doHwResume = true;
6809 mHwPaused = false;
6810 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006811 }
6812 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6813 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006814 // We have consumed all the buffers of this track.
6815 // Remove it from the list of active tracks.
Atneya Nair0cae0432022-05-10 18:12:12 -04006816 bool presComplete = false;
Eric Laurentfd477972013-10-25 18:10:40 -07006817 if (mStandby || !last ||
Atneya Nair0cae0432022-05-10 18:12:12 -04006818 (presComplete = track->presentationComplete(latency_l())) ||
Jindong32dc26e2019-11-11 18:10:01 +08006819 track->isPaused() || mHwPaused) {
Atneya Nair0cae0432022-05-10 18:12:12 -04006820 if (presComplete) {
6821 mOutput->presentationComplete();
6822 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006823 if (track->isStopping_2()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07006824 track->setState(IAfTrackBase::STOPPED);
Eric Laurentab5cdba2014-06-09 17:22:27 -07006825 }
Eric Laurent81784c32012-11-19 14:55:58 -08006826 if (track->isStopped()) {
6827 track->reset();
6828 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006829 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006830 }
6831 } else {
6832 // No buffers for this track. Give it a few chances to
6833 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006834 // Only consider last track started for mixer state control
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006835 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07006836 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07006837 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02006838 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07006839 track->retryCount() = kMaxTrackRetriesOffload;
ziyangch8f194f12021-12-01 13:48:04 -08006840 } else {
6841 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
6842 tracksToRemove->add(track);
6843 // indicate to client process that the track was disabled because of
6844 // underrun; it will then automatically call start() when data is available
6845 track->disable();
6846 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6847 // unlike mixerthread, HAL can be paused for direct output
6848 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6849 "minFrames = %u, mFormat = %#x",
6850 framesReady, minFrames, mFormat);
6851 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
6852 doHwPause = true;
6853 mHwPaused = true;
6854 }
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006855 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006856 } else if (last) {
6857 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006858 }
6859 }
6860 }
6861 }
6862
Eric Laurentd1f69b02014-12-15 14:33:13 -08006863 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006864 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006865 for (size_t i = 0; i < mTracks.size(); i++) {
6866 if (mTracks[i]->isFlushPending()) {
6867 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006868 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006869 }
6870 }
6871 }
6872
6873 // make sure the pause/flush/resume sequence is executed in the right order.
6874 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6875 // before flush and then resume HW. This can happen in case of pause/flush/resume
6876 // if resume is received before pause is executed.
6877 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006878 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006879 status_t result = mOutput->stream->pause();
6880 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07006881 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurentd1f69b02014-12-15 14:33:13 -08006882 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006883 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006884 flushHw_l();
6885 }
6886 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006887 status_t result = mOutput->stream->resume();
6888 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006889 }
Eric Laurent81784c32012-11-19 14:55:58 -08006890 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006891 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006892
6893 return mixerStatus;
6894}
6895
Andy Hung71742ab2023-07-07 13:47:37 -07006896void DirectOutputThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08006897{
Eric Laurent81784c32012-11-19 14:55:58 -08006898 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006899 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006900 // output audio to hardware
6901 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006902 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006903 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006904 status_t status = mActiveTrack->getNextBuffer(&buffer);
6905 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006906 // no need to pad with 0 for compressed audio
6907 if (audio_has_proportional_frames(mFormat)) {
6908 memset(curBuf, 0, frameCount * mFrameSize);
6909 }
Eric Laurent81784c32012-11-19 14:55:58 -08006910 break;
6911 }
6912 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6913 frameCount -= buffer.frameCount;
6914 curBuf += buffer.frameCount * mFrameSize;
6915 mActiveTrack->releaseBuffer(&buffer);
6916 }
Andy Hung2098f272014-02-27 14:00:06 -08006917 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006918 mSleepTimeUs = 0;
6919 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006920 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006921}
6922
Andy Hung71742ab2023-07-07 13:47:37 -07006923void DirectOutputThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08006924{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006925 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006926 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006927 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006928 return;
6929 }
Andy Hung85ba3332021-04-27 17:40:26 -07006930 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6931 mSleepTimeUs = mActiveSleepTimeUs;
6932 } else {
6933 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006934 }
Andy Hung85ba3332021-04-27 17:40:26 -07006935 // Note: In S or later, we do not write zeroes for
6936 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006937}
6938
Andy Hung71742ab2023-07-07 13:47:37 -07006939void DirectOutputThread::threadLoop_exit()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006940{
6941 {
Andy Hungf79092d2023-08-31 16:13:39 -07006942 audio_utils::lock_guard _l(mutex());
Eric Laurentd1f69b02014-12-15 14:33:13 -08006943 for (size_t i = 0; i < mTracks.size(); i++) {
6944 if (mTracks[i]->isFlushPending()) {
6945 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006946 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006947 }
6948 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006949 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006950 flushHw_l();
6951 }
6952 }
6953 PlaybackThread::threadLoop_exit();
6954}
6955
6956// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07006957bool DirectOutputThread::shouldStandby_l()
Eric Laurentd1f69b02014-12-15 14:33:13 -08006958{
6959 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006960 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006961
6962 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6963 // after a timeout and we will enter standby then.
6964 if (mTracks.size() > 0) {
6965 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006966 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
Andy Hung3ff4b552023-06-26 19:20:57 -07006967 mTracks[mTracks.size() - 1]->state() == IAfTrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006968 }
6969
Eric Laurent5cff4032015-05-26 13:49:58 -07006970 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006971}
6972
Andy Hung87e82412023-08-29 14:26:09 -07006973// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07006974bool DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07006975 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006976{
6977 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006978 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006979
Eric Laurent10351942014-05-08 18:49:52 -07006980 AudioParameter param = AudioParameter(keyValuePair);
6981 int value;
6982 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006983 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006984 }
Eric Laurent10351942014-05-08 18:49:52 -07006985 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6986 // do not accept frame count changes if tracks are open as the track buffer
6987 // size depends on frame count and correct behavior would not be garantied
6988 // if frame count is changed after track creation
6989 if (!mTracks.isEmpty()) {
6990 status = INVALID_OPERATION;
6991 } else {
6992 reconfig = true;
6993 }
6994 }
6995 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006996 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006997 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006998 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006999 if (!mStandby) {
7000 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007001 mThreadSnapshot.onEnd();
Eric Laurent19952e12023-04-20 10:08:29 +02007002 setStandby_l();
Andy Hungcf10d742020-04-28 15:38:24 -07007003 }
Eric Laurent10351942014-05-08 18:49:52 -07007004 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007005 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07007006 }
7007 if (status == NO_ERROR && reconfig) {
7008 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07007009 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07007010 }
7011 }
7012
Dean Wheatley68918102021-03-19 22:09:19 +11007013 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08007014}
7015
Andy Hung71742ab2023-07-07 13:47:37 -07007016uint32_t DirectOutputThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007017{
7018 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007019 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007020 time = PlaybackThread::activeSleepTimeUs();
7021 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007022 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007023 }
7024 return time;
7025}
7026
Andy Hung71742ab2023-07-07 13:47:37 -07007027uint32_t DirectOutputThread::idleSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007028{
7029 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007030 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007031 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
7032 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007033 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007034 }
7035 return time;
7036}
7037
Andy Hung71742ab2023-07-07 13:47:37 -07007038uint32_t DirectOutputThread::suspendSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007039{
7040 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08007041 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08007042 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
7043 } else {
Eric Laurent51716182016-02-29 18:00:56 -08007044 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007045 }
7046 return time;
7047}
7048
Andy Hung71742ab2023-07-07 13:47:37 -07007049void DirectOutputThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007050{
7051 PlaybackThread::cacheParameters_l();
7052
7053 // use shorter standby delay as on normal output to release
7054 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07007055 // no delay on outputs with HW A/V sync
7056 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007057 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08007058 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007059 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07007060 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007061 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07007062 }
Eric Laurent81784c32012-11-19 14:55:58 -08007063}
7064
Andy Hung71742ab2023-07-07 13:47:37 -07007065void DirectOutputThread::flushHw_l()
Eric Laurente659ef42014-09-29 13:06:46 -07007066{
ziyangch8f194f12021-12-01 13:48:04 -08007067 PlaybackThread::flushHw_l();
Phil Burk062e67a2015-02-11 13:40:50 -08007068 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08007069 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07007070 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11007071 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11007072 mTimestamp.clear();
Andy Hungee86cee2022-12-13 19:19:53 -08007073 mMonotonicFrameCounter.onFlush();
Eric Laurente659ef42014-09-29 13:06:46 -07007074}
7075
Andy Hung71742ab2023-07-07 13:47:37 -07007076int64_t DirectOutputThread::computeWaitTimeNs_l() const {
Andy Hung10cbff12017-02-21 17:30:14 -08007077 // If a VolumeShaper is active, we must wake up periodically to update volume.
7078 const int64_t NS_PER_MS = 1000000;
7079 return mVolumeShaperActive ?
7080 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
7081}
7082
Eric Laurent81784c32012-11-19 14:55:58 -08007083// ----------------------------------------------------------------------------
7084
Andy Hung71742ab2023-07-07 13:47:37 -07007085AsyncCallbackThread::AsyncCallbackThread(
7086 const wp<PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007087 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07007088 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07007089 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007090 mDrainSequence(0),
7091 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007092{
7093}
7094
Andy Hung71742ab2023-07-07 13:47:37 -07007095void AsyncCallbackThread::onFirstRef()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007096{
7097 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
7098}
7099
Andy Hung71742ab2023-07-07 13:47:37 -07007100bool AsyncCallbackThread::threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007101{
7102 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007103 uint32_t writeAckSequence;
7104 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007105 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007106
7107 {
Andy Hung87e82412023-08-29 14:26:09 -07007108 audio_utils::unique_lock _l(mutex());
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007109 while (!((mWriteAckSequence & 1) ||
7110 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007111 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007112 exitPending())) {
Andy Hung87e82412023-08-29 14:26:09 -07007113 mWaitWorkCV.wait(_l);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08007114 }
7115
Eric Laurentbfb1b832013-01-07 09:53:42 -08007116 if (exitPending()) {
7117 break;
7118 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007119 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
7120 mWriteAckSequence, mDrainSequence);
7121 writeAckSequence = mWriteAckSequence;
7122 mWriteAckSequence &= ~1;
7123 drainSequence = mDrainSequence;
7124 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007125 asyncError = mAsyncError;
7126 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007127 }
7128 {
Andy Hung71742ab2023-07-07 13:47:37 -07007129 const sp<PlaybackThread> playbackThread = mPlaybackThread.promote();
Eric Laurent4de95592013-09-26 15:28:21 -07007130 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007131 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007132 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007133 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07007134 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07007135 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007136 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007137 if (asyncError) {
7138 playbackThread->onAsyncError();
7139 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007140 }
7141 }
7142 }
7143 return false;
7144}
7145
Andy Hung71742ab2023-07-07 13:47:37 -07007146void AsyncCallbackThread::exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007147{
7148 ALOGV("AsyncCallbackThread::exit");
Andy Hungf79092d2023-08-31 16:13:39 -07007149 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007150 requestExit();
Andy Hung87e82412023-08-29 14:26:09 -07007151 mWaitWorkCV.notify_all();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007152}
7153
Andy Hung71742ab2023-07-07 13:47:37 -07007154void AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007155{
Andy Hungf79092d2023-08-31 16:13:39 -07007156 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007157 // bit 0 is cleared
7158 mWriteAckSequence = sequence << 1;
7159}
7160
Andy Hung71742ab2023-07-07 13:47:37 -07007161void AsyncCallbackThread::resetWriteBlocked()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007162{
Andy Hungf79092d2023-08-31 16:13:39 -07007163 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007164 // ignore unexpected callbacks
7165 if (mWriteAckSequence & 2) {
7166 mWriteAckSequence |= 1;
Andy Hung87e82412023-08-29 14:26:09 -07007167 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007168 }
7169}
7170
Andy Hung71742ab2023-07-07 13:47:37 -07007171void AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007172{
Andy Hungf79092d2023-08-31 16:13:39 -07007173 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007174 // bit 0 is cleared
7175 mDrainSequence = sequence << 1;
7176}
7177
Andy Hung71742ab2023-07-07 13:47:37 -07007178void AsyncCallbackThread::resetDraining()
Eric Laurent3b4529e2013-09-05 18:09:19 -07007179{
Andy Hungf79092d2023-08-31 16:13:39 -07007180 audio_utils::lock_guard _l(mutex());
Eric Laurent3b4529e2013-09-05 18:09:19 -07007181 // ignore unexpected callbacks
7182 if (mDrainSequence & 2) {
7183 mDrainSequence |= 1;
Andy Hung87e82412023-08-29 14:26:09 -07007184 mWaitWorkCV.notify_one();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007185 }
7186}
7187
Andy Hung71742ab2023-07-07 13:47:37 -07007188void AsyncCallbackThread::setAsyncError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007189{
Andy Hungf79092d2023-08-31 16:13:39 -07007190 audio_utils::lock_guard _l(mutex());
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007191 mAsyncError = true;
Andy Hung87e82412023-08-29 14:26:09 -07007192 mWaitWorkCV.notify_one();
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07007193}
7194
Eric Laurentbfb1b832013-01-07 09:53:42 -08007195
7196// ----------------------------------------------------------------------------
Andy Hung71742ab2023-07-07 13:47:37 -07007197
7198/* static */
7199sp<IAfPlaybackThread> IAfPlaybackThread::createOffloadThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007200 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007201 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7202 const audio_offload_info_t& offloadInfo) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007203 return sp<OffloadThread>::make(afThreadCallback, output, id, systemReady, offloadInfo);
Andy Hung71742ab2023-07-07 13:47:37 -07007204}
7205
Andy Hung2cbc2722023-07-17 17:05:00 -07007206OffloadThread::OffloadThread(const sp<IAfThreadCallback>& afThreadCallback,
Gareth Fenn56576722022-10-05 13:42:36 -07007207 AudioStreamOut* output, audio_io_handle_t id, bool systemReady,
7208 const audio_offload_info_t& offloadInfo)
Andy Hung2cbc2722023-07-17 17:05:00 -07007209 : DirectOutputThread(afThreadCallback, output, id, OFFLOAD, systemReady, offloadInfo),
ziyangch8f194f12021-12-01 13:48:04 -08007210 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true)
Eric Laurentbfb1b832013-01-07 09:53:42 -08007211{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07007212 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07007213 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07007214 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007215}
7216
Andy Hung71742ab2023-07-07 13:47:37 -07007217void OffloadThread::threadLoop_exit()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007218{
7219 if (mFlushPending || mHwPaused) {
7220 // If a flush is pending or track was paused, just discard buffered data
7221 flushHw_l();
7222 } else {
7223 mMixerStatus = MIXER_DRAIN_ALL;
7224 threadLoop_drain();
7225 }
Uday Gupta56604aa2014-05-13 11:19:17 -07007226 if (mUseAsyncWrite) {
7227 ALOG_ASSERT(mCallbackThread != 0);
7228 mCallbackThread->exit();
7229 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007230 PlaybackThread::threadLoop_exit();
7231}
7232
Andy Hung71742ab2023-07-07 13:47:37 -07007233PlaybackThread::mixer_state OffloadThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -07007234 Vector<sp<IAfTrack>>* tracksToRemove
Eric Laurentbfb1b832013-01-07 09:53:42 -08007235)
7236{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007237 size_t count = mActiveTracks.size();
7238
7239 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07007240 bool doHwPause = false;
7241 bool doHwResume = false;
7242
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007243 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07007244
Eric Laurentbfb1b832013-01-07 09:53:42 -08007245 // find out which tracks need to be processed
Andy Hung3ff4b552023-06-26 19:20:57 -07007246 for (const sp<IAfTrack>& t : mActiveTracks) {
7247 IAfTrack* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007248#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08007249 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007250#endif
Eric Laurentfd477972013-10-25 18:10:40 -07007251 // Only consider last track started for volume and mixer state control.
7252 // In theory an older track could underrun and restart after the new one starts
7253 // but as we only care about the transition phase between two tracks on a
7254 // direct output, it is not a problem to ignore the underrun case.
Andy Hung3ff4b552023-06-26 19:20:57 -07007255 sp<IAfTrack> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08007256 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07007257
Haynes Mathew George7844f672014-01-15 12:32:55 -08007258 if (track->isInvalid()) {
7259 ALOGW("An invalidated track shouldn't be in active list");
7260 tracksToRemove->add(track);
7261 continue;
7262 }
7263
Andy Hung3ff4b552023-06-26 19:20:57 -07007264 if (track->state() == IAfTrackBase::IDLE) {
Haynes Mathew George7844f672014-01-15 12:32:55 -08007265 ALOGW("An idle track shouldn't be in active list");
7266 continue;
7267 }
7268
Kuowei Li23666472021-01-20 10:23:25 +08007269 if (track->isPausePending()) {
7270 track->pauseAck();
7271 // It is possible a track might have been flushed or stopped.
7272 // Other operations such as flush pending might occur on the next prepare.
7273 if (track->isPausing()) {
7274 track->setPaused();
7275 }
7276 // Always perform pause if last, as an immediate flush will change
7277 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08007278 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07007279 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07007280 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007281 mHwPaused = true;
7282 }
7283 // If we were part way through writing the mixbuffer to
7284 // the HAL we must save this until we resume
7285 // BUG - this will be wrong if a different track is made active,
7286 // in that case we want to discard the pending data in the
7287 // mixbuffer and tell the client to present it again when the
7288 // track is resumed
7289 mPausedWriteLength = mCurrentWriteLength;
7290 mPausedBytesRemaining = mBytesRemaining;
7291 mBytesRemaining = 0; // stop writing
7292 }
7293 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08007294 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07007295 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007296 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007297 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007298 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007299 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08007300 track->flushAck();
7301 if (last) {
7302 mFlushPending = true;
7303 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007304 } else if (track->isResumePending()){
7305 track->resumeAck();
7306 if (last) {
7307 if (mPausedBytesRemaining) {
7308 // Need to continue write that was interrupted
7309 mCurrentWriteLength = mPausedWriteLength;
7310 mBytesRemaining = mPausedBytesRemaining;
7311 mPausedBytesRemaining = 0;
7312 }
7313 if (mHwPaused) {
7314 doHwResume = true;
7315 mHwPaused = false;
7316 // threadLoop_mix() will handle the case that we need to
7317 // resume an interrupted write
7318 }
7319 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007320 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007321
Eric Laurent3df841a2016-07-15 15:15:40 -07007322 mLeftVolFloat = mRightVolFloat = -1.0;
7323
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08007324 // Do not handle new data in this iteration even if track->framesReady()
7325 mixerStatus = MIXER_TRACKS_ENABLED;
7326 }
7327 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07007328 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07007329 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Andy Hung3ff4b552023-06-26 19:20:57 -07007330 if (track->fillingStatus() == IAfTrack::FS_FILLED) {
7331 track->fillingStatus() = IAfTrack::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07007332 if (last) {
7333 // make sure processVolume_l() will apply new volume even if 0
7334 mLeftVolFloat = mRightVolFloat = -1.0;
7335 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007336 }
7337
7338 if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007339 sp<IAfTrack> previousTrack = mPreviousTrack.promote();
Eric Laurentd7e59222013-11-15 12:02:28 -08007340 if (previousTrack != 0) {
7341 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08007342 // Flush any data still being written from last track
7343 mBytesRemaining = 0;
7344 if (mPausedBytesRemaining) {
7345 // Last track was paused so we also need to flush saved
7346 // mixbuffer state and invalidate track so that it will
7347 // re-submit that unwritten data when it is next resumed
7348 mPausedBytesRemaining = 0;
7349 // Invalidate is a bit drastic - would be more efficient
7350 // to have a flag to tell client that some of the
7351 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08007352 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007353 }
7354 // flush data already sent to the DSP if changing audio session as audio
7355 // comes from a different source. Also invalidate previous track to force a
7356 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08007357 if (previousTrack->sessionId() != track->sessionId()) {
7358 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08007359 }
7360 }
7361 }
7362 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007363 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07007364 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007365 track->retryCount() = kMaxTrackStopRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007366 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07007367 track->retryCount() = kMaxTrackRetriesOffload;
Eric Laurente93cc032016-05-05 10:15:10 -07007368 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08007369 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007370 mixerStatus = MIXER_TRACKS_READY;
7371 }
7372 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007373 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007374 if (track->isStopping_1()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007375 if (--(track->retryCount()) <= 0) {
Eric Laurente93cc032016-05-05 10:15:10 -07007376 // Hardware buffer can hold a large amount of audio so we must
7377 // wait for all current track's data to drain before we say
7378 // that the track is stopped.
7379 if (mBytesRemaining == 0) {
7380 // Only start draining when all data in mixbuffer
7381 // has been written
7382 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
Andy Hung3ff4b552023-06-26 19:20:57 -07007383 track->setState(IAfTrackBase::STOPPING_2);
7384 // so presentation completes after
Eric Laurente93cc032016-05-05 10:15:10 -07007385 // drain do not drain if no data was ever sent to HAL (mStandby == true)
7386 if (last && !mStandby) {
7387 // do not modify drain sequence if we are already draining. This happens
7388 // when resuming from pause after drain.
7389 if ((mDrainSequence & 1) == 0) {
7390 mSleepTimeUs = 0;
7391 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
7392 mixerStatus = MIXER_DRAIN_TRACK;
7393 mDrainSequence += 2;
7394 }
7395 if (mHwPaused) {
7396 // It is possible to move from PAUSED to STOPPING_1 without
7397 // a resume so we must ensure hardware is running
7398 doHwResume = true;
7399 mHwPaused = false;
7400 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007401 }
7402 }
Eric Laurente93cc032016-05-05 10:15:10 -07007403 } else if (last) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007404 ALOGV("stopping1 underrun retries left %d", track->retryCount());
Eric Laurente93cc032016-05-05 10:15:10 -07007405 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007406 }
7407 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07007408 // Drain has completed or we are in standby, signal presentation complete
7409 if (!(mDrainSequence & 1) || !last || mStandby) {
Andy Hung3ff4b552023-06-26 19:20:57 -07007410 track->setState(IAfTrackBase::STOPPED);
Atneya Nair0cae0432022-05-10 18:12:12 -04007411 mOutput->presentationComplete();
7412 track->presentationComplete(latency_l()); // always returns true
Eric Laurentbfb1b832013-01-07 09:53:42 -08007413 track->reset();
7414 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11007415 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07007416 if (!mUseAsyncWrite) {
7417 // If we don't get explicit drain notification we must
7418 // register discontinuity regardless of whether this is
7419 // the previous (!last) or the upcoming (last) track
7420 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11007421 mTimestampVerifier.discontinuity(
7422 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07007423 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007424 }
7425 } else {
7426 // No buffers for this track. Give it a few chances to
7427 // fill a buffer, then remove it from active list.
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007428 bool isTimestampAdvancing = mIsTimestampAdvancing.check(mOutput);
Gareth Fenn56576722022-10-05 13:42:36 -07007429 if (!isTunerStream() // tuner streams remain active in underrun
Andy Hung3ff4b552023-06-26 19:20:57 -07007430 && --(track->retryCount()) <= 0) {
Brian Lindahl9e661ad2022-07-27 18:01:07 +02007431 if (isTimestampAdvancing) { // HAL is still playing audio, give us more time.
Andy Hung3ff4b552023-06-26 19:20:57 -07007432 track->retryCount() = kMaxTrackRetriesOffload;
Andy Hungf8044752016-07-27 14:58:11 -07007433 } else {
Andy Hungc0691382018-09-12 18:01:57 -07007434 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
7435 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07007436 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08007437 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07007438 // it will then automatically call start() when data is available
7439 track->disable();
7440 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007441 } else if (last){
7442 mixerStatus = MIXER_TRACKS_ENABLED;
7443 }
7444 }
7445 }
7446 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08007447 if (track->isReady()) { // check ready to prevent premature start.
7448 processVolume_l(track, last);
7449 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08007450 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007451
Eric Laurentea0fade2013-10-04 16:23:48 -07007452 // make sure the pause/flush/resume sequence is executed in the right order.
7453 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
7454 // before flush and then resume HW. This can happen in case of pause/flush/resume
7455 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07007456 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007457 status_t result = mOutput->stream->pause();
7458 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Gareth Fenncd1e1622022-10-05 11:45:45 -07007459 doHwResume = !doHwPause; // resume if pause is due to flush.
Eric Laurent972a1732013-09-04 09:42:59 -07007460 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007461 if (mFlushPending) {
7462 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007463 }
Eric Laurentfd477972013-10-25 18:10:40 -07007464 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007465 status_t result = mOutput->stream->resume();
7466 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07007467 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07007468
Eric Laurentbfb1b832013-01-07 09:53:42 -08007469 // remove all the tracks that need to be...
7470 removeTracks_l(*tracksToRemove);
7471
7472 return mixerStatus;
7473}
7474
Eric Laurentbfb1b832013-01-07 09:53:42 -08007475// must be called with thread mutex locked
Andy Hung71742ab2023-07-07 13:47:37 -07007476bool OffloadThread::waitingAsyncCallback_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007477{
Eric Laurent3b4529e2013-09-05 18:09:19 -07007478 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
7479 mWriteAckSequence, mDrainSequence);
7480 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08007481 return true;
7482 }
7483 return false;
7484}
7485
Andy Hung71742ab2023-07-07 13:47:37 -07007486bool OffloadThread::waitingAsyncCallback()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007487{
Andy Hungf79092d2023-08-31 16:13:39 -07007488 audio_utils::lock_guard _l(mutex());
Eric Laurentbfb1b832013-01-07 09:53:42 -08007489 return waitingAsyncCallback_l();
7490}
7491
Andy Hung71742ab2023-07-07 13:47:37 -07007492void OffloadThread::flushHw_l()
Eric Laurentbfb1b832013-01-07 09:53:42 -08007493{
Eric Laurente659ef42014-09-29 13:06:46 -07007494 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08007495 // Flush anything still waiting in the mixbuffer
7496 mCurrentWriteLength = 0;
7497 mBytesRemaining = 0;
7498 mPausedWriteLength = 0;
7499 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07007500 // reset bytes written count to reflect that DSP buffers are empty after flush.
7501 mBytesWritten = 0;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08007502
Eric Laurentbfb1b832013-01-07 09:53:42 -08007503 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07007504 // discard any pending drain or write ack by incrementing sequence
7505 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
7506 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08007507 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07007508 mCallbackThread->setWriteBlocked(mWriteAckSequence);
7509 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08007510 }
7511}
7512
Andy Hung71742ab2023-07-07 13:47:37 -07007513void OffloadThread::invalidateTracks(audio_stream_type_t streamType)
Haynes Mathew George05317d22016-05-03 16:34:26 -07007514{
Andy Hungf79092d2023-08-31 16:13:39 -07007515 audio_utils::lock_guard _l(mutex());
Eric Laurent13084622016-05-17 10:51:49 -07007516 if (PlaybackThread::invalidateTracks_l(streamType)) {
7517 mFlushPending = true;
7518 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07007519}
7520
Andy Hung71742ab2023-07-07 13:47:37 -07007521void OffloadThread::invalidateTracks(std::set<audio_port_handle_t>& portIds) {
Andy Hungf79092d2023-08-31 16:13:39 -07007522 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -08007523 if (PlaybackThread::invalidateTracks_l(portIds)) {
7524 mFlushPending = true;
7525 }
7526}
7527
Eric Laurentbfb1b832013-01-07 09:53:42 -08007528// ----------------------------------------------------------------------------
7529
Andy Hung71742ab2023-07-07 13:47:37 -07007530/* static */
7531sp<IAfDuplicatingThread> IAfDuplicatingThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -07007532 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007533 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007534 return sp<DuplicatingThread>::make(afThreadCallback, mainThread, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -07007535}
7536
Andy Hung2cbc2722023-07-17 17:05:00 -07007537DuplicatingThread::DuplicatingThread(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007538 IAfPlaybackThread* mainThread, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -07007539 : MixerThread(afThreadCallback, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007540 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08007541 mWaitTimeMs(UINT_MAX)
7542{
7543 addOutputTrack(mainThread);
7544}
7545
Andy Hung71742ab2023-07-07 13:47:37 -07007546DuplicatingThread::~DuplicatingThread()
Eric Laurent81784c32012-11-19 14:55:58 -08007547{
7548 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7549 mOutputTracks[i]->destroy();
7550 }
7551}
7552
Andy Hung71742ab2023-07-07 13:47:37 -07007553void DuplicatingThread::threadLoop_mix()
Eric Laurent81784c32012-11-19 14:55:58 -08007554{
7555 // mix buffers...
Andy Hung71ba4b32022-10-06 12:09:49 -07007556 if (outputsReady()) {
Glenn Kastend79072e2016-01-06 08:41:20 -08007557 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08007558 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08007559 if (mMixerBufferValid) {
7560 memset(mMixerBuffer, 0, mMixerBufferSize);
7561 } else {
7562 memset(mSinkBuffer, 0, mSinkBufferSize);
7563 }
Eric Laurent81784c32012-11-19 14:55:58 -08007564 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007565 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007566 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007567 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007568 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08007569}
7570
Andy Hung71742ab2023-07-07 13:47:37 -07007571void DuplicatingThread::threadLoop_sleepTime()
Eric Laurent81784c32012-11-19 14:55:58 -08007572{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007573 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007574 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007575 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007576 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007577 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08007578 }
7579 } else if (mBytesWritten != 0) {
7580 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
7581 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08007582 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08007583 } else {
7584 // flush remaining overflow buffers in output tracks
7585 writeFrames = 0;
7586 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07007587 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08007588 }
7589}
7590
Andy Hung71742ab2023-07-07 13:47:37 -07007591ssize_t DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08007592{
7593 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07007594 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
7595
7596 // Consider the first OutputTrack for timestamp and frame counting.
7597
7598 // The threadLoop() generally assumes writing a full sink buffer size at a time.
7599 // Here, we correct for writeFrames of 0 (a stop) or underruns because
7600 // we always claim success.
7601 if (i == 0) {
7602 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
7603 ALOGD_IF(correction != 0 && writeFrames != 0,
7604 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
7605 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
7606 mFramesWritten -= correction;
7607 }
7608
7609 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08007610 }
Andy Hungcf10d742020-04-28 15:38:24 -07007611 if (mStandby) {
7612 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07007613 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07007614 mStandby = false;
7615 }
Andy Hung25c2dac2014-02-27 14:56:00 -08007616 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08007617}
7618
Andy Hung71742ab2023-07-07 13:47:37 -07007619void DuplicatingThread::threadLoop_standby()
Eric Laurent81784c32012-11-19 14:55:58 -08007620{
7621 // DuplicatingThread implements standby by stopping all tracks
7622 for (size_t i = 0; i < outputTracks.size(); i++) {
7623 outputTracks[i]->stop();
7624 }
7625}
7626
Andy Hung71742ab2023-07-07 13:47:37 -07007627void DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args)
Andy Hung1bc088a2018-02-09 15:57:31 -08007628{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007629 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08007630
7631 std::stringstream ss;
7632 const size_t numTracks = mOutputTracks.size();
7633 ss << " " << numTracks << " OutputTracks";
7634 if (numTracks > 0) {
7635 ss << ":";
7636 for (const auto &track : mOutputTracks) {
Andy Hung44f27182023-07-06 20:56:16 -07007637 const auto thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07007638 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007639 if (thread.get() != nullptr) {
7640 ss << thread.get() << ", " << thread->id();
7641 } else {
7642 ss << "null";
7643 }
7644 ss << ")";
7645 }
7646 }
7647 ss << "\n";
7648 std::string result = ss.str();
7649 write(fd, result.c_str(), result.size());
7650}
7651
Andy Hung71742ab2023-07-07 13:47:37 -07007652void DuplicatingThread::saveOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007653{
7654 outputTracks = mOutputTracks;
7655}
7656
Andy Hung71742ab2023-07-07 13:47:37 -07007657void DuplicatingThread::clearOutputTracks()
Eric Laurent81784c32012-11-19 14:55:58 -08007658{
7659 outputTracks.clear();
7660}
7661
Andy Hung71742ab2023-07-07 13:47:37 -07007662void DuplicatingThread::addOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007663{
Andy Hungf79092d2023-08-31 16:13:39 -07007664 audio_utils::lock_guard _l(mutex());
Andy Hungc25b84a2015-01-14 19:04:10 -08007665 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7666 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7667 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7668 const size_t frameCount =
7669 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7670 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7671 // from different OutputTracks and their associated MixerThreads (e.g. one may
7672 // nearly empty and the other may be dropping data).
7673
Svet Ganov33761132021-05-13 22:51:08 +00007674 // TODO b/182392769: use attribution source util, move to server edge
7675 AttributionSourceState attributionSource = AttributionSourceState();
7676 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007677 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007678 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007679 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007680 attributionSource.token = sp<BBinder>::make();
Andy Hung3ff4b552023-06-26 19:20:57 -07007681 sp<IAfOutputTrack> outputTrack = IAfOutputTrack::create(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007682 this,
7683 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007684 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007685 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007686 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007687 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007688 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7689 if (status != NO_ERROR) {
7690 ALOGE("addOutputTrack() initCheck failed %d", status);
7691 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007692 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007693 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7694 mOutputTracks.add(outputTrack);
7695 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7696 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007697}
7698
Andy Hung71742ab2023-07-07 13:47:37 -07007699void DuplicatingThread::removeOutputTrack(IAfPlaybackThread* thread)
Eric Laurent81784c32012-11-19 14:55:58 -08007700{
Andy Hungf79092d2023-08-31 16:13:39 -07007701 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08007702 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7703 if (mOutputTracks[i]->thread() == thread) {
7704 mOutputTracks[i]->destroy();
7705 mOutputTracks.removeAt(i);
7706 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007707 if (thread->getOutput() == mOutput) {
7708 mOutput = NULL;
7709 }
Eric Laurent81784c32012-11-19 14:55:58 -08007710 return;
7711 }
7712 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007713 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007714}
7715
Andy Hung87e82412023-08-29 14:26:09 -07007716// caller must hold mutex()
Andy Hung71742ab2023-07-07 13:47:37 -07007717void DuplicatingThread::updateWaitTime_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007718{
7719 mWaitTimeMs = UINT_MAX;
7720 for (size_t i = 0; i < mOutputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007721 const auto strong = mOutputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007722 if (strong != 0) {
7723 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7724 if (waitTimeMs < mWaitTimeMs) {
7725 mWaitTimeMs = waitTimeMs;
7726 }
7727 }
7728 }
7729}
7730
Andy Hung71742ab2023-07-07 13:47:37 -07007731bool DuplicatingThread::outputsReady()
Eric Laurent81784c32012-11-19 14:55:58 -08007732{
7733 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung44f27182023-07-06 20:56:16 -07007734 const auto thread = outputTracks[i]->thread().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08007735 if (thread == 0) {
7736 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7737 outputTracks[i].get());
7738 return false;
7739 }
Andy Hung44f27182023-07-06 20:56:16 -07007740 IAfPlaybackThread* const playbackThread = thread->asIAfPlaybackThread().get();
Eric Laurent81784c32012-11-19 14:55:58 -08007741 // see note at standby() declaration
Andy Hung4989d312023-06-29 21:19:25 -07007742 if (playbackThread->inStandby() && !playbackThread->isSuspended()) {
Eric Laurent81784c32012-11-19 14:55:58 -08007743 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7744 thread.get());
7745 return false;
7746 }
7747 }
7748 return true;
7749}
7750
Andy Hung71742ab2023-07-07 13:47:37 -07007751void DuplicatingThread::sendMetadataToBackend_l(
Kevin Rocard12381092018-04-11 09:19:59 -07007752 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007753{
Kevin Rocard12381092018-04-11 09:19:59 -07007754 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7755 outputTrack->setMetadatas(metadata.tracks);
7756 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007757}
7758
Andy Hung71742ab2023-07-07 13:47:37 -07007759uint32_t DuplicatingThread::activeSleepTimeUs() const
Eric Laurent81784c32012-11-19 14:55:58 -08007760{
7761 return (mWaitTimeMs * 1000) / 2;
7762}
7763
Andy Hung71742ab2023-07-07 13:47:37 -07007764void DuplicatingThread::cacheParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08007765{
7766 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7767 updateWaitTime_l();
7768
7769 MixerThread::cacheParameters_l();
7770}
7771
Eric Laurentb3f315a2021-07-13 15:09:05 +02007772// ----------------------------------------------------------------------------
7773
Andy Hung71742ab2023-07-07 13:47:37 -07007774/* static */
7775sp<IAfPlaybackThread> IAfPlaybackThread::createSpatializerThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07007776 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -07007777 AudioStreamOut* output,
7778 audio_io_handle_t id,
7779 bool systemReady,
7780 audio_config_base_t* mixerConfig) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007781 return sp<SpatializerThread>::make(afThreadCallback, output, id, systemReady, mixerConfig);
Andy Hung71742ab2023-07-07 13:47:37 -07007782}
7783
Andy Hung2cbc2722023-07-17 17:05:00 -07007784SpatializerThread::SpatializerThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007785 AudioStreamOut* output,
7786 audio_io_handle_t id,
7787 bool systemReady,
7788 audio_config_base_t *mixerConfig)
Andy Hung2cbc2722023-07-17 17:05:00 -07007789 : MixerThread(afThreadCallback, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007790{
7791}
7792
Andy Hung71742ab2023-07-07 13:47:37 -07007793void SpatializerThread::setHalLatencyMode_l() {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007794 // if mSupportedLatencyModes is empty, the HAL stream does not support
7795 // latency mode control and we can exit.
7796 if (mSupportedLatencyModes.empty()) {
7797 return;
7798 }
7799 audio_latency_mode_t latencyMode = AUDIO_LATENCY_MODE_FREE;
7800 if (mSupportedLatencyModes.size() == 1) {
7801 // If the HAL only support one latency mode currently, confirm the choice
7802 latencyMode = mSupportedLatencyModes[0];
7803 } else if (mSupportedLatencyModes.size() > 1) {
7804 // Request low latency if:
7805 // - The low latency mode is requested by the spatializer controller
7806 // (mRequestedLatencyMode = AUDIO_LATENCY_MODE_LOW)
7807 // AND
7808 // - At least one active track is spatialized
7809 bool hasSpatializedActiveTrack = false;
7810 for (const auto& track : mActiveTracks) {
7811 if (track->isSpatialized()) {
7812 hasSpatializedActiveTrack = true;
7813 break;
7814 }
7815 }
7816 if (hasSpatializedActiveTrack && mRequestedLatencyMode == AUDIO_LATENCY_MODE_LOW) {
7817 latencyMode = AUDIO_LATENCY_MODE_LOW;
7818 }
7819 }
7820
7821 if (latencyMode != mSetLatencyMode) {
7822 status_t status = mOutput->stream->setLatencyMode(latencyMode);
Andy Hung4bd53e72022-11-17 17:21:45 -08007823 ALOGD("%s: thread(%d) setLatencyMode(%s) returned %d",
7824 __func__, mId, toString(latencyMode).c_str(), status);
Eric Laurent6f9534f2022-05-03 18:15:04 +02007825 if (status == NO_ERROR) {
7826 mSetLatencyMode = latencyMode;
7827 }
7828 }
7829}
7830
Andy Hung71742ab2023-07-07 13:47:37 -07007831status_t SpatializerThread::setRequestedLatencyMode(audio_latency_mode_t mode) {
Eric Laurent6f9534f2022-05-03 18:15:04 +02007832 if (mode != AUDIO_LATENCY_MODE_LOW && mode != AUDIO_LATENCY_MODE_FREE) {
7833 return BAD_VALUE;
7834 }
Andy Hungf79092d2023-08-31 16:13:39 -07007835 audio_utils::lock_guard _l(mutex());
Eric Laurent6f9534f2022-05-03 18:15:04 +02007836 mRequestedLatencyMode = mode;
7837 return NO_ERROR;
7838}
7839
Andy Hung71742ab2023-07-07 13:47:37 -07007840void SpatializerThread::checkOutputStageEffects()
Andy Hungf79092d2023-08-31 16:13:39 -07007841NO_THREAD_SAFETY_ANALYSIS
7842// 'createEffect_l' requires holding mutex 'AudioFlinger_Mutex' exclusively
Eric Laurentb3f315a2021-07-13 15:09:05 +02007843{
7844 bool hasVirtualizer = false;
7845 bool hasDownMixer = false;
Andy Hungbd72c542023-06-20 18:56:17 -07007846 sp<IAfEffectHandle> finalDownMixer;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007847 {
Andy Hungf79092d2023-08-31 16:13:39 -07007848 audio_utils::lock_guard _l(mutex());
Andy Hungbd72c542023-06-20 18:56:17 -07007849 sp<IAfEffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007850 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007851 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007852 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7853 }
7854
7855 finalDownMixer = mFinalDownMixer;
7856 mFinalDownMixer.clear();
7857 }
7858
7859 if (hasVirtualizer) {
7860 if (finalDownMixer != nullptr) {
7861 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007862 finalDownMixer->asIEffect()->disable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007863 }
7864 finalDownMixer.clear();
7865 } else if (!hasDownMixer) {
7866 std::vector<effect_descriptor_t> descriptors;
Andy Hung2cbc2722023-07-17 17:05:00 -07007867 status_t status = mAfThreadCallback->getEffectsFactoryHal()->getDescriptors(
Eric Laurentb3f315a2021-07-13 15:09:05 +02007868 EFFECT_UIID_DOWNMIX, &descriptors);
7869 if (status != NO_ERROR) {
7870 return;
7871 }
7872 ALOG_ASSERT(!descriptors.empty(),
7873 "%s getDescriptors() returned no error but empty list", __func__);
7874
7875 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7876 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007877 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007878
7879 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7880 ALOGW("%s error creating downmixer %d", __func__, status);
7881 finalDownMixer.clear();
7882 } else {
7883 int32_t ret;
Andy Hungbd72c542023-06-20 18:56:17 -07007884 finalDownMixer->asIEffect()->enable(&ret);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007885 }
7886 }
7887
7888 {
Andy Hungf79092d2023-08-31 16:13:39 -07007889 audio_utils::lock_guard _l(mutex());
Eric Laurentb3f315a2021-07-13 15:09:05 +02007890 mFinalDownMixer = finalDownMixer;
7891 }
7892}
7893
Eric Laurent81784c32012-11-19 14:55:58 -08007894// ----------------------------------------------------------------------------
7895// Record
7896// ----------------------------------------------------------------------------
7897
Andy Hung2cbc2722023-07-17 17:05:00 -07007898sp<IAfRecordThread> IAfRecordThread::create(const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung44f27182023-07-06 20:56:16 -07007899 AudioStreamIn* input,
7900 audio_io_handle_t id,
7901 bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -07007902 return sp<RecordThread>::make(afThreadCallback, input, id, systemReady);
Andy Hung44f27182023-07-06 20:56:16 -07007903}
7904
Andy Hung2cbc2722023-07-17 17:05:00 -07007905RecordThread::RecordThread(const sp<IAfThreadCallback>& afThreadCallback,
Eric Laurent81784c32012-11-19 14:55:58 -08007906 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007907 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007908 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007909 ) :
Andy Hung2cbc2722023-07-17 17:05:00 -07007910 ThreadBase(afThreadCallback, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007911 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007912 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007913 mActiveTracks(&this->mLocalLog),
7914 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007915 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007916 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007917 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7918 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007919 // mFastCapture below
7920 , mFastCaptureFutex(0)
7921 // mInputSource
7922 // mPipeSink
7923 // mPipeSource
7924 , mPipeFramesP2(0)
7925 // mPipeMemory
7926 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007927 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007928 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007929{
Glenn Kastend7dca052015-03-05 16:05:54 -08007930 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
Andy Hung2cbc2722023-07-17 17:05:00 -07007931 mNBLogWriter = afThreadCallback->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007932
George Burgess IVa8f90c12020-05-14 11:27:19 -07007933 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007934 mIsMsdDevice = strcmp(
7935 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7936 }
7937
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007938 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007939
Andy Hungc8fddf32018-08-08 18:32:37 -07007940 // TODO: We may also match on address as well as device type for
7941 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007942 // TODO: This property should be ensure that only contains one single device type.
7943 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7944 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007945 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7946 : AUDIO_DEVICE_NONE));
7947
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007948 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007949 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007950 size_t numCounterOffers = 0;
7951 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007952#if !LOG_NDEBUG
Jing Mike537412f2023-03-12 11:01:47 +08007953 [[maybe_unused]] ssize_t index =
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007954#else
7955 (void)
7956#endif
7957 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007958 ALOG_ASSERT(index == 0);
7959
7960 // initialize fast capture depending on configuration
7961 bool initFastCapture;
7962 switch (kUseFastCapture) {
7963 case FastCapture_Never:
7964 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007965 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007966 break;
7967 case FastCapture_Always:
7968 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007969 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007970 break;
7971 case FastCapture_Static:
Sampath6fac2332022-12-16 17:34:37 +11007972 initFastCapture = !mIsMsdDevice // Disable fast capture for MSD BUS devices.
7973 && (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
7974 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d "
7975 "mIsMsdDevice = %d", this, (long long)mFrameCount, mSampleRate,
7976 kMinNormalCaptureBufferSizeMs, initFastCapture, mIsMsdDevice);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007977 break;
7978 // case FastCapture_Dynamic:
7979 }
7980
7981 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007982 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007983 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007984 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7985 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007986 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007987 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007988 const sp<MemoryDealer> roHeap(readOnlyHeap());
7989 sp<IMemory> pipeMemory;
7990 if ((roHeap == 0) ||
7991 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007992 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007993 ALOGE("not enough memory for pipe buffer size=%zu; "
7994 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7995 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7996 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007997 goto failed;
7998 }
7999 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
8000 memset(pipeBuffer, 0, pipeSize);
8001 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008002 const NBAIO_Format offersFast[1] = {format};
8003 size_t numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008004 [[maybe_unused]] ssize_t index2 = pipe->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07008005 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008006 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008007 mPipeSink = pipe;
8008 PipeReader *pipeReader = new PipeReader(*pipe);
Andy Hung71ba4b32022-10-06 12:09:49 -07008009 numCounterOffersFast = 0;
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008010 index2 = pipeReader->negotiate(offersFast, std::size(offersFast),
Andy Hung71ba4b32022-10-06 12:09:49 -07008011 nullptr /* counterOffers */, numCounterOffersFast);
Eric Laurent1e28aaa2023-04-16 19:34:23 +02008012 ALOG_ASSERT(index2 == 0);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008013 mPipeSource = pipeReader;
8014 mPipeFramesP2 = pipeFramesP2;
8015 mPipeMemory = pipeMemory;
8016
8017 // create fast capture
8018 mFastCapture = new FastCapture();
8019 FastCaptureStateQueue *sq = mFastCapture->sq();
8020#ifdef STATE_QUEUE_DUMP
8021 // FIXME
8022#endif
8023 FastCaptureState *state = sq->begin();
8024 state->mCblk = NULL;
8025 state->mInputSource = mInputSource.get();
8026 state->mInputSourceGen++;
8027 state->mPipeSink = pipe;
8028 state->mPipeSinkGen++;
8029 state->mFrameCount = mFrameCount;
8030 state->mCommand = FastCaptureState::COLD_IDLE;
8031 // already done in constructor initialization list
8032 //mFastCaptureFutex = 0;
8033 state->mColdFutexAddr = &mFastCaptureFutex;
8034 state->mColdGen++;
8035 state->mDumpState = &mFastCaptureDumpState;
8036#ifdef TEE_SINK
8037 // FIXME
8038#endif
Andy Hung2cbc2722023-07-17 17:05:00 -07008039 mFastCaptureNBLogWriter =
8040 afThreadCallback->newWriter_l(kFastCaptureLogSize, "FastCapture");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008041 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
8042 sq->end();
8043 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8044
8045 // start the fast capture
8046 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
8047 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07008048 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08008049 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008050#ifdef AUDIO_WATCHDOG
8051 // FIXME
8052#endif
8053
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008054 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008055 }
Andy Hung8946a282018-04-19 20:04:56 -07008056#ifdef TEE_SINK
8057 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
8058 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
8059#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008060failed: ;
8061
8062 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08008063}
8064
Andy Hung71742ab2023-07-07 13:47:37 -07008065RecordThread::~RecordThread()
Eric Laurent81784c32012-11-19 14:55:58 -08008066{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008067 if (mFastCapture != 0) {
8068 FastCaptureStateQueue *sq = mFastCapture->sq();
8069 FastCaptureState *state = sq->begin();
8070 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8071 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8072 if (old == -1) {
8073 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8074 }
8075 }
8076 state->mCommand = FastCaptureState::EXIT;
8077 sq->end();
8078 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
8079 mFastCapture->join();
8080 mFastCapture.clear();
8081 }
Andy Hung2cbc2722023-07-17 17:05:00 -07008082 mAfThreadCallback->unregisterWriter(mFastCaptureNBLogWriter);
8083 mAfThreadCallback->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07008084 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08008085}
8086
Andy Hung71742ab2023-07-07 13:47:37 -07008087void RecordThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08008088{
Glenn Kastend7dca052015-03-05 16:05:54 -08008089 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08008090}
8091
Andy Hung71742ab2023-07-07 13:47:37 -07008092void RecordThread::preExit()
Eric Laurent555530a2017-02-07 18:17:24 -08008093{
8094 ALOGV(" preExit()");
Andy Hungf79092d2023-08-31 16:13:39 -07008095 audio_utils::lock_guard _l(mutex());
Eric Laurent555530a2017-02-07 18:17:24 -08008096 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008097 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent555530a2017-02-07 18:17:24 -08008098 track->invalidate();
8099 }
8100 mActiveTracks.clear();
Andy Hung87e82412023-08-29 14:26:09 -07008101 mStartStopCV.notify_all();
Eric Laurent555530a2017-02-07 18:17:24 -08008102}
8103
Andy Hung71742ab2023-07-07 13:47:37 -07008104bool RecordThread::threadLoop()
Eric Laurent81784c32012-11-19 14:55:58 -08008105{
Eric Laurent81784c32012-11-19 14:55:58 -08008106 nsecs_t lastWarning = 0;
8107
8108 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08008109
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008110reacquire_wakelock:
Andy Hung3ff4b552023-06-26 19:20:57 -07008111 sp<IAfRecordTrack> activeTrack;
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008112 {
Andy Hungf79092d2023-08-31 16:13:39 -07008113 audio_utils::lock_guard _l(mutex());
Andy Hungdae27702016-10-31 14:01:16 -07008114 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008115 }
8116
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008117 // used to request a deferred sleep, to be executed later while mutex is unlocked
8118 uint32_t sleepUs = 0;
8119
Andy Hung446f4df2019-02-21 12:26:41 -08008120 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
8121
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008122 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08008123 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Andy Hungbd72c542023-06-20 18:56:17 -07008124 Vector<sp<IAfEffectChain>> effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07008125
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008126 // activeTracks accumulates a copy of a subset of mActiveTracks
Andy Hung3ff4b552023-06-26 19:20:57 -07008127 Vector<sp<IAfRecordTrack>> activeTracks;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008128
Glenn Kasten735f45f2014-08-18 15:51:59 -07008129 // reference to the (first and only) active fast track
Andy Hung3ff4b552023-06-26 19:20:57 -07008130 sp<IAfRecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07008131
Glenn Kasten735f45f2014-08-18 15:51:59 -07008132 // reference to a fast track which is about to be removed
Andy Hung3ff4b552023-06-26 19:20:57 -07008133 sp<IAfRecordTrack> fastTrackToRemove;
Glenn Kasten735f45f2014-08-18 15:51:59 -07008134
Eric Laurent33403f02020-05-29 18:35:06 -07008135 bool silenceFastCapture = false;
8136
Andy Hung87e82412023-08-29 14:26:09 -07008137 { // scope for mutex()
8138 audio_utils::unique_lock _l(mutex());
Eric Laurent000a4192014-01-29 15:17:32 -08008139
Eric Laurent021cf962014-05-13 10:18:14 -07008140 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008141
Eric Laurent000a4192014-01-29 15:17:32 -08008142 // check exitPending here because checkForNewParameters_l() and
Andy Hung87e82412023-08-29 14:26:09 -07008143 // checkForNewParameters_l() can temporarily release mutex()
Eric Laurent000a4192014-01-29 15:17:32 -08008144 if (exitPending()) {
8145 break;
8146 }
8147
Eric Laurent5c25d562016-07-13 17:17:45 -07008148 // sleep with mutex unlocked
8149 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07008150 ATRACE_BEGIN("sleepC");
Andy Hung87e82412023-08-29 14:26:09 -07008151 (void)mWaitWorkCV.wait_for(_l, std::chrono::microseconds(sleepUs));
Eric Laurent5c25d562016-07-13 17:17:45 -07008152 ATRACE_END();
8153 sleepUs = 0;
8154 continue;
8155 }
8156
Glenn Kasten2b806402013-11-20 16:37:38 -08008157 // if no active track(s), then standby and release wakelock
8158 size_t size = mActiveTracks.size();
8159 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07008160 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07008161 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08008162 releaseWakeLock_l();
8163 ALOGV("RecordThread: loop stopping");
8164 // go to sleep
Andy Hung87e82412023-08-29 14:26:09 -07008165 mWaitWorkCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08008166 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008167 goto reacquire_wakelock;
8168 }
8169
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008170 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07008171 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008172 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07008173
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008174 activeTrack = mActiveTracks[i];
8175 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07008176 if (activeTrack->isFastTrack()) {
8177 ALOG_ASSERT(fastTrackToRemove == 0);
8178 fastTrackToRemove = activeTrack;
8179 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008180 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08008181 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008182 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07008183 continue;
8184 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008185
Andy Hung3ff4b552023-06-26 19:20:57 -07008186 IAfTrackBase::track_state activeTrackState = activeTrack->state();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008187 switch (activeTrackState) {
8188
Andy Hung3ff4b552023-06-26 19:20:57 -07008189 case IAfTrackBase::PAUSING:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008190 mActiveTracks.remove(activeTrack);
Andy Hung3ff4b552023-06-26 19:20:57 -07008191 activeTrack->setState(IAfTrackBase::PAUSED);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008192 doBroadcast = true;
8193 size--;
8194 continue;
8195
Andy Hung3ff4b552023-06-26 19:20:57 -07008196 case IAfTrackBase::STARTING_1:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008197 sleepUs = 10000;
8198 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07008199 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008200 continue;
8201
Andy Hung3ff4b552023-06-26 19:20:57 -07008202 case IAfTrackBase::STARTING_2:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008203 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07008204 if (mStandby) {
8205 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008206 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -07008207 mStandby = false;
8208 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008209 activeTrack->setState(IAfTrackBase::ACTIVE);
Eric Laurent5c25d562016-07-13 17:17:45 -07008210 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008211 break;
8212
Andy Hung3ff4b552023-06-26 19:20:57 -07008213 case IAfTrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07008214 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008215 break;
8216
Andy Hung3ff4b552023-06-26 19:20:57 -07008217 case IAfTrackBase::IDLE: // cannot be on ActiveTracks if idle
8218 case IAfTrackBase::PAUSED: // cannot be on ActiveTracks if paused
8219 case IAfTrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008220 default:
Andy Hungce685402018-10-05 17:23:27 -07008221 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
8222 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07008223 }
Glenn Kasten9e982352013-08-14 14:39:50 -07008224
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008225 if (activeTrack->isFastTrack()) {
8226 ALOG_ASSERT(!mFastTrackAvail);
8227 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07008228 // if the active fast track is silenced either:
8229 // 1) silence the whole capture from fast capture buffer if this is
8230 // the only active track
8231 // 2) invalidate this track: this will cause the client to reconnect and possibly
8232 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008233 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07008234 if (activeTrack->isSilenced()) {
8235 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008236 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07008237 } else {
8238 silenceFastCapture = true;
8239 }
8240 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008241 // Invalidate fast tracks if access to audio history is required as this is not
8242 // possible with fast tracks. Once the fast track has been invalidated, no new
8243 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
8244 if (mMaxSharedAudioHistoryMs != 0) {
8245 invalidate = true;
8246 }
8247 if (invalidate) {
8248 activeTrack->invalidate();
8249 ALOG_ASSERT(fastTrackToRemove == 0);
8250 fastTrackToRemove = activeTrack;
8251 removeTrack_l(activeTrack);
8252 mActiveTracks.remove(activeTrack);
8253 size--;
8254 continue;
8255 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008256 fastTrack = activeTrack;
8257 }
Eric Laurent33403f02020-05-29 18:35:06 -07008258
8259 activeTracks.add(activeTrack);
8260 i++;
8261
Glenn Kasten9e982352013-08-14 14:39:50 -07008262 }
Eric Laurent5c25d562016-07-13 17:17:45 -07008263
Andy Hungdae27702016-10-31 14:01:16 -07008264 mActiveTracks.updatePowerState(this);
8265
Kevin Rocard069c2712018-03-29 19:09:14 -07008266 updateMetadata_l();
8267
Eric Laurent5c25d562016-07-13 17:17:45 -07008268 if (allStopped) {
8269 standbyIfNotAlreadyInStandby();
8270 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008271 if (doBroadcast) {
Andy Hung87e82412023-08-29 14:26:09 -07008272 mStartStopCV.notify_all();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008273 }
8274
8275 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07008276 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008277 if (sleepUs == 0) {
8278 sleepUs = kRecordThreadSleepUs;
8279 }
8280 continue;
8281 }
8282 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07008283
Eric Laurent81784c32012-11-19 14:55:58 -08008284 lockEffectChains_l(effectChains);
8285 }
8286
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008287 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07008288
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008289 size_t size = effectChains.size();
8290 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008291 // thread mutex is not locked, but effect chain is locked
8292 effectChains[i]->process_l();
8293 }
8294
Glenn Kasten735f45f2014-08-18 15:51:59 -07008295 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008296 if (mFastCapture != 0) {
8297 FastCaptureStateQueue *sq = mFastCapture->sq();
8298 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07008299 bool didModify = false;
8300 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008301 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
8302 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
8303 if (state->mCommand == FastCaptureState::COLD_IDLE) {
8304 int32_t old = android_atomic_inc(&mFastCaptureFutex);
8305 if (old == -1) {
8306 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
8307 }
8308 }
8309 state->mCommand = FastCaptureState::READ_WRITE;
8310#if 0 // FIXME
Andy Hung2cbc2722023-07-17 17:05:00 -07008311 mFastCaptureDumpState.increaseSamplingN(mAfThreadCallback->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08008312 FastThreadDumpState::kSamplingNforLowRamDevice :
8313 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008314#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07008315 didModify = true;
8316 }
8317 audio_track_cblk_t *cblkOld = state->mCblk;
8318 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
8319 if (cblkNew != cblkOld) {
8320 state->mCblk = cblkNew;
8321 // block until acked if removing a fast track
8322 if (cblkOld != NULL) {
8323 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
8324 }
8325 didModify = true;
8326 }
jiabin01c8f562018-07-19 17:47:28 -07008327 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
8328 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
8329 if (state->mFastPatchRecordBufferProvider != abp) {
8330 state->mFastPatchRecordBufferProvider = abp;
8331 state->mFastPatchRecordFormat = fastTrack == 0 ?
8332 AUDIO_FORMAT_INVALID : fastTrack->format();
8333 didModify = true;
8334 }
Eric Laurent33403f02020-05-29 18:35:06 -07008335 if (state->mSilenceCapture != silenceFastCapture) {
8336 state->mSilenceCapture = silenceFastCapture;
8337 didModify = true;
8338 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07008339 sq->end(didModify);
8340 if (didModify) {
8341 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008342#if 0
8343 if (kUseFastCapture == FastCapture_Dynamic) {
8344 mNormalSource = mPipeSource;
8345 }
8346#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008347 }
8348 }
8349
Glenn Kasten735f45f2014-08-18 15:51:59 -07008350 // now run the fast track destructor with thread mutex unlocked
8351 fastTrackToRemove.clear();
8352
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008353 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
8354 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
8355 // slow, then this RecordThread will overrun by not calling HAL read often enough.
8356 // If destination is non-contiguous, first read past the nominal end of buffer, then
8357 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008358
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008359 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Andy Hung71ba4b32022-10-06 12:09:49 -07008360 ssize_t framesRead = 0; // not needed, remove clang-tidy warning.
Andy Hung446f4df2019-02-21 12:26:41 -08008361 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008362
8363 // If an NBAIO source is present, use it to read the normal capture's data
8364 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07008365 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07008366
8367 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
8368 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
8369 // we immediately retry the read() to get data and prevent another overflow.
8370 for (int retries = 0; retries <= 2; ++retries) {
8371 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
8372 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
8373 framesToRead);
8374 if (framesRead != OVERRUN) break;
8375 }
8376
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008377 const ssize_t availableToRead = mPipeSource->availableToRead();
8378 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00008379 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07008380 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07008381 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
8382 "more frames to read than fifo size, %zd > %zu",
8383 availableToRead, mPipeFramesP2);
8384 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
8385 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
8386 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
8387 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07008388 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
8389 }
8390 if (framesRead < 0) {
8391 status_t status = (status_t) framesRead;
8392 switch (status) {
8393 case OVERRUN:
8394 ALOGW("overrun on read from pipe");
8395 framesRead = 0;
8396 break;
8397 case NEGOTIATE:
8398 ALOGE("re-negotiation is needed");
8399 framesRead = -1; // Will cause an attempt to recover.
8400 break;
8401 default:
8402 ALOGE("unknown error %d on read from pipe", status);
8403 break;
8404 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008405 }
8406 // otherwise use the HAL / AudioStreamIn directly
8407 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07008408 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008409 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07008410 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008411 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07008412 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008413 if (result < 0) {
8414 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008415 } else {
8416 framesRead = bytesRead / mFrameSize;
8417 }
8418 }
8419
Andy Hung446f4df2019-02-21 12:26:41 -08008420 const int64_t lastIoEndNs = systemTime(); // end IO timing
8421
Andy Hung3f0c9022016-01-15 17:49:46 -08008422 // Update server timestamp with server stats
8423 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07008424 if (framesRead >= 0) {
8425 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
8426 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
8427 }
Andy Hung3f0c9022016-01-15 17:49:46 -08008428
8429 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008430 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08008431 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008432 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11008433 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
8434 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
8435 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07008436 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07008437 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
8438
8439 mTimestampVerifier.add(position, time, mSampleRate);
8440
8441 // Correct timestamps
8442 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10008443 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008444 id(), (long long)time, (long long)position);
8445 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
8446 position = correctedTimestamp.mFrames;
8447 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10008448 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07008449 id(), (long long)time, (long long)position);
8450 }
8451
Andy Hung3f0c9022016-01-15 17:49:46 -08008452 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
8453 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
8454 // Note: In general record buffers should tend to be empty in
8455 // a properly running pipeline.
8456 //
8457 // Also, it is not advantageous to call get_presentation_position during the read
8458 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07008459 } else {
8460 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08008461 }
8462 }
Andy Hunge6c37112019-02-26 17:38:10 -08008463
8464 // From the timestamp, input read latency is negative output write latency.
8465 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
Andy Hung3ff4b552023-06-26 19:20:57 -07008466 const double latencyMs = IAfRecordTrack::checkServerLatencySupported(mFormat, flags)
Andy Hunge6c37112019-02-26 17:38:10 -08008467 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
8468 if (latencyMs != 0.) { // note 0. means timestamp is empty.
8469 mLatencyMs.add(latencyMs);
8470 }
8471
Andy Hung3f0c9022016-01-15 17:49:46 -08008472 // Use this to track timestamp information
8473 // ALOGD("%s", mTimestamp.toString().c_str());
8474
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008475 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008476 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008477 // Force input into standby so that it tries to recover at next read attempt
8478 inputStandBy();
8479 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008480 }
8481 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008482 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008483 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008484 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07008485 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008486
Andy Hung8946a282018-04-19 20:04:56 -07008487#ifdef TEE_SINK
8488 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
8489#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008490 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008491 {
8492 size_t part1 = mRsmpInFramesP2 - rear;
8493 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07008494 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008495 (framesRead - part1) * mFrameSize);
8496 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008497 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11008498 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008499
8500 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008501
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008502 // loop over each active track
8503 for (size_t i = 0; i < size; i++) {
8504 activeTrack = activeTracks[i];
8505
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008506 // skip fast tracks, as those are handled directly by FastCapture
8507 if (activeTrack->isFastTrack()) {
8508 continue;
8509 }
8510
Andy Hung73c02e42015-03-29 01:13:58 -07008511 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07008512 // TODO: Update the activeTrack buffer converter in case of reconfigure.
8513
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008514 enum {
8515 OVERRUN_UNKNOWN,
8516 OVERRUN_TRUE,
8517 OVERRUN_FALSE
8518 } overrun = OVERRUN_UNKNOWN;
8519
8520 // loop over getNextBuffer to handle circular sink
8521 for (;;) {
8522
Andy Hung3ff4b552023-06-26 19:20:57 -07008523 activeTrack->sinkBuffer().frameCount = ~0;
8524 status_t status = activeTrack->getNextBuffer(&activeTrack->sinkBuffer());
8525 size_t framesOut = activeTrack->sinkBuffer().frameCount;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008526 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
8527
Andy Hung73c02e42015-03-29 01:13:58 -07008528 // check available frames and handle overrun conditions
8529 // if the record track isn't draining fast enough.
8530 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008531 size_t framesIn;
Andy Hung3ff4b552023-06-26 19:20:57 -07008532 activeTrack->resamplerBufferProvider()->sync(&framesIn, &hasOverrun);
Andy Hung73c02e42015-03-29 01:13:58 -07008533 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008534 overrun = OVERRUN_TRUE;
8535 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008536 if (framesOut == 0 || framesIn == 0) {
8537 break;
8538 }
8539
Andy Hung6770c6f2015-04-07 13:43:36 -07008540 // Don't allow framesOut to be larger than what is possible with resampling
8541 // from framesIn.
8542 // This isn't strictly necessary but helps limit buffer resizing in
8543 // RecordBufferConverter. TODO: remove when no longer needed.
Dean Wheatleydea650c2023-11-01 22:49:01 +11008544 if (audio_is_linear_pcm(activeTrack->format())) {
8545 framesOut = min(framesOut,
8546 destinationFramesPossible(
8547 framesIn, mSampleRate, activeTrack->sampleRate()));
8548 }
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008549
8550 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10008551 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008552 // straight from RecordThread buffer to RecordTrack buffer.
8553 AudioBufferProvider::Buffer buffer;
8554 buffer.frameCount = framesOut;
Andy Hung71ba4b32022-10-06 12:09:49 -07008555 const status_t getNextBufferStatus =
Andy Hung3ff4b552023-06-26 19:20:57 -07008556 activeTrack->resamplerBufferProvider()->getNextBuffer(&buffer);
Andy Hung71ba4b32022-10-06 12:09:49 -07008557 if (getNextBufferStatus == OK && buffer.frameCount != 0) {
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008558 ALOGV_IF(buffer.frameCount != framesOut,
8559 "%s() read less than expected (%zu vs %zu)",
8560 __func__, buffer.frameCount, framesOut);
8561 framesOut = buffer.frameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008562 memcpy(activeTrack->sinkBuffer().raw,
8563 buffer.raw, buffer.frameCount * mFrameSize);
8564 activeTrack->resamplerBufferProvider()->releaseBuffer(&buffer);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008565 } else {
8566 framesOut = 0;
8567 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
Andy Hung71ba4b32022-10-06 12:09:49 -07008568 __func__, getNextBufferStatus, buffer.frameCount);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008569 }
8570 } else {
8571 // process frames from the RecordThread buffer provider to the RecordTrack
8572 // buffer
Andy Hung3ff4b552023-06-26 19:20:57 -07008573 framesOut = activeTrack->recordBufferConverter()->convert(
8574 activeTrack->sinkBuffer().raw,
8575 activeTrack->resamplerBufferProvider(),
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008576 framesOut);
8577 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008578
8579 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
8580 overrun = OVERRUN_FALSE;
8581 }
8582
Andy Hung93bb5732023-05-04 21:16:34 -07008583 // MediaSyncEvent handling: Synchronize AudioRecord to AudioTrack completion.
8584 const ssize_t framesToDrop =
Andy Hung3ff4b552023-06-26 19:20:57 -07008585 activeTrack->synchronizedRecordState().updateRecordFrames(framesOut);
Andy Hung93bb5732023-05-04 21:16:34 -07008586 if (framesToDrop == 0) {
8587 // no sync event, process normally, otherwise ignore.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008588 if (framesOut > 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008589 activeTrack->sinkBuffer().frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008590 // Sanitize before releasing if the track has no access to the source data
8591 // An idle UID receives silence from non virtual devices until active
8592 if (activeTrack->isSilenced()) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008593 memset(activeTrack->sinkBuffer().raw,
8594 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008595 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008596 activeTrack->releaseBuffer(&activeTrack->sinkBuffer());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008597 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008598 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008599 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008600 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008601 }
8602 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008603
8604 switch (overrun) {
8605 case OVERRUN_TRUE:
8606 // client isn't retrieving buffers fast enough
8607 if (!activeTrack->setOverflow()) {
8608 nsecs_t now = systemTime();
8609 // FIXME should lastWarning per track?
8610 if ((now - lastWarning) > kWarningThrottleNs) {
8611 ALOGW("RecordThread: buffer overflow");
8612 lastWarning = now;
8613 }
8614 }
8615 break;
8616 case OVERRUN_FALSE:
8617 activeTrack->clearOverflow();
8618 break;
8619 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008620 break;
8621 }
8622
Andy Hung3f0c9022016-01-15 17:49:46 -08008623 // update frame information and push timestamp out
8624 activeTrack->updateTrackFrameInfo(
Andy Hung3ff4b552023-06-26 19:20:57 -07008625 activeTrack->serverProxy()->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08008626 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
8627 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07008628 }
8629
Glenn Kasten3d61bc12014-06-16 10:25:20 -07008630unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08008631 // enable changes in effect chain
8632 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07008633 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07008634 if (audio_has_proportional_frames(mFormat)
8635 && loopCount == lastLoopCountRead + 1) {
8636 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
8637 const double jitterMs =
8638 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
8639 {framesRead, readPeriodNs},
8640 {0, 0} /* lastTimestamp */, mSampleRate);
8641 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
8642
Andy Hungf79092d2023-08-31 16:13:39 -07008643 audio_utils::lock_guard _l(mutex());
Eric Laurentcccbc762019-04-05 14:20:05 -07008644 mIoJitterMs.add(jitterMs);
8645 mProcessTimeMs.add(processMs);
8646 }
8647 // update timing info.
8648 mLastIoBeginNs = lastIoBeginNs;
8649 mLastIoEndNs = lastIoEndNs;
8650 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008651 }
8652
Glenn Kasten93e471f2013-08-19 08:40:07 -07008653 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08008654
8655 {
Andy Hungf79092d2023-08-31 16:13:39 -07008656 audio_utils::lock_guard _l(mutex());
Eric Laurent9a54bc22013-09-09 09:08:44 -07008657 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008658 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent9a54bc22013-09-09 09:08:44 -07008659 track->invalidate();
8660 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008661 mActiveTracks.clear();
Andy Hung87e82412023-08-29 14:26:09 -07008662 mStartStopCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08008663 }
8664
8665 releaseWakeLock();
8666
8667 ALOGV("RecordThread %p exiting", this);
8668 return false;
8669}
8670
Andy Hung71742ab2023-07-07 13:47:37 -07008671void RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08008672{
8673 if (!mStandby) {
8674 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07008675 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -07008676 mThreadSnapshot.onEnd();
Eric Laurent81784c32012-11-19 14:55:58 -08008677 mStandby = true;
8678 }
8679}
8680
Andy Hung71742ab2023-07-07 13:47:37 -07008681void RecordThread::inputStandBy()
Eric Laurent81784c32012-11-19 14:55:58 -08008682{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008683 // Idle the fast capture if it's currently running
8684 if (mFastCapture != 0) {
8685 FastCaptureStateQueue *sq = mFastCapture->sq();
8686 FastCaptureState *state = sq->begin();
8687 if (!(state->mCommand & FastCaptureState::IDLE)) {
8688 state->mCommand = FastCaptureState::COLD_IDLE;
8689 state->mColdFutexAddr = &mFastCaptureFutex;
8690 state->mColdGen++;
8691 mFastCaptureFutex = 0;
8692 sq->end();
8693 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
8694 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
8695#if 0
8696 if (kUseFastCapture == FastCapture_Dynamic) {
8697 // FIXME
8698 }
8699#endif
8700#ifdef AUDIO_WATCHDOG
8701 // FIXME
8702#endif
8703 } else {
8704 sq->end(false /*didModify*/);
8705 }
8706 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008707 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008708 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008709
8710 // If going into standby, flush the pipe source.
8711 if (mPipeSource.get() != nullptr) {
8712 const ssize_t flushed = mPipeSource->flush();
8713 if (flushed > 0) {
8714 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8715 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8716 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8717 }
8718 }
Eric Laurent81784c32012-11-19 14:55:58 -08008719}
8720
Andy Hung87e82412023-08-29 14:26:09 -07008721// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07008722sp<IAfRecordTrack> RecordThread::createRecordTrack_l(
Andy Hungd65869f2023-06-27 17:05:02 -07008723 const sp<Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008724 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008725 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008726 audio_format_t format,
8727 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008728 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008729 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008730 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008731 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008732 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008733 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008734 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008735 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008736 audio_port_handle_t portId,
8737 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008738{
Glenn Kasten74935e42013-12-19 08:56:45 -08008739 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008740 size_t notificationFrameCount = *pNotificationFrameCount;
Andy Hung3ff4b552023-06-26 19:20:57 -07008741 sp<IAfRecordTrack> track;
Eric Laurent81784c32012-11-19 14:55:58 -08008742 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008743 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008744 audio_input_flags_t requestedFlags = *flags;
8745 uint32_t sampleRate;
8746
8747 lStatus = initCheck();
8748 if (lStatus != NO_ERROR) {
8749 ALOGE("createRecordTrack_l() audio driver not initialized");
8750 goto Exit;
8751 }
8752
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008753 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8754 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8755 lStatus = BAD_VALUE;
8756 goto Exit;
8757 }
8758
Eric Laurentec376dc2021-04-08 20:41:22 +02008759 if (maxSharedAudioHistoryMs != 0) {
Eric Laurent9ff3e532022-11-10 16:04:44 +01008760 if (!captureHotwordAllowed(attributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008761 lStatus = PERMISSION_DENIED;
8762 goto Exit;
8763 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008764 if (maxSharedAudioHistoryMs < 0
Andy Hung4d693a32023-07-19 12:47:35 -07008765 || maxSharedAudioHistoryMs > kMaxSharedAudioHistoryMs) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008766 lStatus = BAD_VALUE;
8767 goto Exit;
8768 }
8769 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008770 if (*pSampleRate == 0) {
8771 *pSampleRate = mSampleRate;
8772 }
8773 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008774
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008775 // special case for FAST flag considered OK if fast capture is present and access to
8776 // audio history is not required
8777 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008778 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8779 }
8780
Eric Laurentf14db3c2017-12-08 14:20:36 -08008781 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008782 if ((*flags & inputFlags) != *flags) {
8783 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8784 " input flags (%08x)",
8785 *flags, inputFlags);
8786 *flags = (audio_input_flags_t)(*flags & inputFlags);
8787 }
Eric Laurent81784c32012-11-19 14:55:58 -08008788
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008789 // client expresses a preference for FAST and no access to audio history,
8790 // but we get the final say
8791 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008792 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008793 // we formerly checked for a callback handler (non-0 tid),
8794 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008795 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008796 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008797 // Frame count is not specified (0), or is less than or equal the pipe depth.
8798 // It is OK to provide a higher capacity than requested.
8799 // We will force it to mPipeFramesP2 below.
8800 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008801 // PCM data
8802 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008803 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008804 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008805 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008806 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008807 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008808 hasFastCapture() &&
8809 // there are sufficient fast track slots available
8810 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008811 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008812 // check compatibility with audio effects.
Andy Hungf79092d2023-08-31 16:13:39 -07008813 audio_utils::lock_guard _l(mutex());
Eric Laurent4c415062016-06-17 16:14:16 -07008814 // Do not accept FAST flag if the session has software effects
Andy Hungbd72c542023-06-20 18:56:17 -07008815 sp<IAfEffectChain> chain = getEffectChain_l(sessionId);
Eric Laurent4c415062016-06-17 16:14:16 -07008816 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008817 audio_input_flags_t old = *flags;
8818 chain->checkInputFlagCompatibility(flags);
8819 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008820 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8821 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008822 }
8823 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008824 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008825 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8826 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008827 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008828 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8829 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008830 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008831 this, frameCount, mFrameCount, mPipeFramesP2,
8832 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008833 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008834 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008835 }
8836 }
8837
Eric Laurentf14db3c2017-12-08 14:20:36 -08008838 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8839 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8840 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8841 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8842 lStatus = BAD_TYPE;
8843 goto Exit;
8844 }
8845
Glenn Kasten74105912014-07-03 12:28:53 -07008846 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008847 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008848 // fast track: frame count is exactly the pipe depth
8849 frameCount = mPipeFramesP2;
8850 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008851 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008852 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008853 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8854 // or 20 ms if there is a fast capture
8855 // TODO This could be a roundupRatio inline, and const
8856 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8857 * sampleRate + mSampleRate - 1) / mSampleRate;
8858 // minimum number of notification periods is at least kMinNotifications,
8859 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8860 static const size_t kMinNotifications = 3;
8861 static const uint32_t kMinMs = 30;
8862 // TODO This could be a roundupRatio inline
8863 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8864 // TODO This could be a roundupRatio inline
8865 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8866 maxNotificationFrames;
8867 const size_t minFrameCount = maxNotificationFrames *
8868 max(kMinNotifications, minNotificationsByMs);
8869 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008870 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8871 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008872 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008873 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008874 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008875 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008876
Andy Hung87e82412023-08-29 14:26:09 -07008877 { // scope for mutex()
Andy Hungf79092d2023-08-31 16:13:39 -07008878 audio_utils::lock_guard _l(mutex());
Eric Laurent2407ce32021-04-26 14:56:03 +02008879 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008880 if (!mSharedAudioPackageName.empty()
Eric Laurent9ff3e532022-11-10 16:04:44 +01008881 && mSharedAudioPackageName == attributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008882 && mSharedAudioSessionId == sessionId
Eric Laurent9ff3e532022-11-10 16:04:44 +01008883 && captureHotwordAllowed(attributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008884 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008885 }
Eric Laurent81784c32012-11-19 14:55:58 -08008886
Andy Hung3ff4b552023-06-26 19:20:57 -07008887 track = IAfRecordTrack::create(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008888 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008889 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Andy Hung3ff4b552023-06-26 19:20:57 -07008890 attributionSource, *flags, IAfTrackBase::TYPE_DEFAULT, portId,
Svet Ganov33761132021-05-13 22:51:08 +00008891 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008892
Glenn Kasten03003332013-08-06 15:40:54 -07008893 lStatus = track->initCheck();
8894 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008895 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008896 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008897 goto Exit;
8898 }
8899 mTracks.add(track);
8900
Eric Laurent05067782016-06-01 18:27:28 -07008901 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008902 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8903 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8904 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008905 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008906 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008907
8908 if (maxSharedAudioHistoryMs != 0) {
8909 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8910 }
Eric Laurent81784c32012-11-19 14:55:58 -08008911 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008912
Eric Laurent81784c32012-11-19 14:55:58 -08008913 lStatus = NO_ERROR;
8914
8915Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008916 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008917 return track;
8918}
8919
Andy Hung71742ab2023-07-07 13:47:37 -07008920status_t RecordThread::start(IAfRecordTrack* recordTrack,
Eric Laurent81784c32012-11-19 14:55:58 -08008921 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008922 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008923{
8924 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8925 sp<ThreadBase> strongMe = this;
8926 status_t status = NO_ERROR;
8927
8928 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008929 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008930 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008931 recordTrack->synchronizedRecordState().startRecording(
Andy Hung2cbc2722023-07-17 17:05:00 -07008932 mAfThreadCallback->createSyncEvent(
Andy Hung93bb5732023-05-04 21:16:34 -07008933 event, triggerSession,
8934 recordTrack->sessionId(), syncStartEventCallback, recordTrack));
Eric Laurent81784c32012-11-19 14:55:58 -08008935 }
8936
8937 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008938 // This section is a rendezvous between binder thread executing start() and RecordThread
Andy Hungf79092d2023-08-31 16:13:39 -07008939 audio_utils::lock_guard lock(mutex());
Andy Hungce685402018-10-05 17:23:27 -07008940 if (recordTrack->isInvalid()) {
8941 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008942 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8943 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008944 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008945 if (mActiveTracks.indexOf(recordTrack) >= 0) {
Andy Hung3ff4b552023-06-26 19:20:57 -07008946 if (recordTrack->state() == IAfTrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008947 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8948 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008949 ALOGV("active record track PAUSING -> ACTIVE");
Andy Hung3ff4b552023-06-26 19:20:57 -07008950 recordTrack->setState(IAfTrackBase::ACTIVE);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008951 } else {
Andy Hung3ff4b552023-06-26 19:20:57 -07008952 ALOGV("active record track state %d", (int)recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08008953 }
8954 return status;
8955 }
8956
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008957 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8958 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8959 // or using a separate command thread
Andy Hung3ff4b552023-06-26 19:20:57 -07008960 recordTrack->setState(IAfTrackBase::STARTING_1);
Glenn Kasten2b806402013-11-20 16:37:38 -08008961 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008962 if (recordTrack->isExternalTrack()) {
Andy Hung87e82412023-08-29 14:26:09 -07008963 mutex().unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008964 status = AudioSystem::startInput(recordTrack->portId());
Andy Hung87e82412023-08-29 14:26:09 -07008965 mutex().lock();
Andy Hungce685402018-10-05 17:23:27 -07008966 if (recordTrack->isInvalid()) {
8967 recordTrack->clearSyncStartEvent();
Andy Hung3ff4b552023-06-26 19:20:57 -07008968 if (status == NO_ERROR && recordTrack->state() == IAfTrackBase::STARTING_1) {
8969 recordTrack->setState(IAfTrackBase::STARTING_2);
Andy Hungce685402018-10-05 17:23:27 -07008970 // STARTING_2 forces destroy to call stopInput.
8971 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008972 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8973 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008974 }
Andy Hung3ff4b552023-06-26 19:20:57 -07008975 if (recordTrack->state() != IAfTrackBase::STARTING_1) {
Andy Hungce685402018-10-05 17:23:27 -07008976 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung3ff4b552023-06-26 19:20:57 -07008977 __func__, recordTrack->id(), (int)recordTrack->state());
Andy Hungce685402018-10-05 17:23:27 -07008978 // Someone else has changed state, let them take over,
8979 // leave mState in the new state.
8980 recordTrack->clearSyncStartEvent();
8981 return INVALID_OPERATION;
8982 }
8983 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008984 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008985 ALOGW("%s(%d): startInput failed, status %d",
8986 __func__, recordTrack->id(), status);
8987 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8988 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008989 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008990 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008991 return status;
8992 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008993 sendIoConfigEvent_l(
8994 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008995 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008996
8997 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8998
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008999 // Catch up with current buffer indices if thread is already running.
9000 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
9001 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
9002 // see previously buffered data before it called start(), but with greater risk of overrun.
9003
Andy Hung3ff4b552023-06-26 19:20:57 -07009004 recordTrack->resamplerBufferProvider()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009005 if (!recordTrack->isDirect()) {
9006 // clear any converter state as new data will be discontinuous
Andy Hung3ff4b552023-06-26 19:20:57 -07009007 recordTrack->recordBufferConverter()->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07009008 }
Andy Hung3ff4b552023-06-26 19:20:57 -07009009 recordTrack->setState(IAfTrackBase::STARTING_2);
Eric Laurent81784c32012-11-19 14:55:58 -08009010 // signal thread to start
Andy Hung87e82412023-08-29 14:26:09 -07009011 mWaitWorkCV.notify_all();
Eric Laurent81784c32012-11-19 14:55:58 -08009012 return status;
9013 }
Eric Laurent81784c32012-11-19 14:55:58 -08009014}
9015
Andy Hung71742ab2023-07-07 13:47:37 -07009016void RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
Eric Laurent81784c32012-11-19 14:55:58 -08009017{
Andy Hung71742ab2023-07-07 13:47:37 -07009018 const sp<SyncEvent> strongEvent = event.promote();
Eric Laurent81784c32012-11-19 14:55:58 -08009019
9020 if (strongEvent != 0) {
Andy Hung02a6c4e2023-06-23 19:27:19 -07009021 sp<IAfTrackBase> ptr =
9022 std::any_cast<const wp<IAfTrackBase>>(strongEvent->cookie()).promote();
9023 if (ptr != nullptr) {
Andy Hung56126702023-07-14 11:00:08 -07009024 // TODO(b/291317898) handleSyncStartEvent is in IAfTrackBase not IAfRecordTrack.
Andy Hung02a6c4e2023-06-23 19:27:19 -07009025 ptr->handleSyncStartEvent(strongEvent);
Eric Laurent8ea16e42014-02-20 16:26:11 -08009026 }
Eric Laurent81784c32012-11-19 14:55:58 -08009027 }
9028}
9029
Andy Hung71742ab2023-07-07 13:47:37 -07009030bool RecordThread::stop(IAfRecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08009031 ALOGV("RecordThread::stop");
Andy Hung87e82412023-08-29 14:26:09 -07009032 audio_utils::unique_lock _l(mutex());
Andy Hungce685402018-10-05 17:23:27 -07009033 // if we're invalid, we can't be on the ActiveTracks.
Andy Hung3ff4b552023-06-26 19:20:57 -07009034 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->state() == IAfTrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08009035 return false;
9036 }
Glenn Kasten47c20702013-08-13 15:37:35 -07009037 // note that threadLoop may still be processing the track at this point [without lock]
Andy Hung3ff4b552023-06-26 19:20:57 -07009038 recordTrack->setState(IAfTrackBase::PAUSING);
Andy Hungce685402018-10-05 17:23:27 -07009039
Andy Hungabfab202019-03-07 19:45:54 -08009040 // NOTE: Waiting here is important to keep stop synchronous.
9041 // This is needed for proper patchRecord peer release.
Andy Hung3ff4b552023-06-26 19:20:57 -07009042 while (recordTrack->state() == IAfTrackBase::PAUSING && !recordTrack->isInvalid()) {
Andy Hung87e82412023-08-29 14:26:09 -07009043 mWaitWorkCV.notify_all(); // signal thread to stop
9044 mStartStopCV.wait(_l);
Eric Laurent81784c32012-11-19 14:55:58 -08009045 }
Andy Hungce685402018-10-05 17:23:27 -07009046
Andy Hung3ff4b552023-06-26 19:20:57 -07009047 if (recordTrack->state() == IAfTrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08009048 ALOGV("Record stopped OK");
9049 return true;
9050 }
Andy Hungce685402018-10-05 17:23:27 -07009051
9052 // don't handle anything - we've been invalidated or restarted and in a different state
9053 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
Andy Hung3ff4b552023-06-26 19:20:57 -07009054 __func__, recordTrack->id(), recordTrack->state());
Eric Laurent81784c32012-11-19 14:55:58 -08009055 return false;
9056}
9057
Andy Hung71742ab2023-07-07 13:47:37 -07009058bool RecordThread::isValidSyncEvent(const sp<SyncEvent>& /* event */) const
Eric Laurent81784c32012-11-19 14:55:58 -08009059{
9060 return false;
9061}
9062
Andy Hung71742ab2023-07-07 13:47:37 -07009063status_t RecordThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent81784c32012-11-19 14:55:58 -08009064{
9065#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
9066 if (!isValidSyncEvent(event)) {
9067 return BAD_VALUE;
9068 }
9069
Glenn Kastend848eb42016-03-08 13:42:11 -08009070 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08009071 status_t ret = NAME_NOT_FOUND;
9072
Andy Hungf79092d2023-08-31 16:13:39 -07009073 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009074
9075 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009076 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08009077 if (eventSession == track->sessionId()) {
9078 (void) track->setSyncEvent(event);
9079 ret = NO_ERROR;
9080 }
9081 }
9082 return ret;
9083#else
9084 return BAD_VALUE;
9085#endif
9086}
9087
Andy Hung71742ab2023-07-07 13:47:37 -07009088status_t RecordThread::getActiveMicrophones(
Andy Hung44f27182023-07-06 20:56:16 -07009089 std::vector<media::MicrophoneInfoFw>* activeMicrophones) const
jiabin653cc0a2018-01-17 17:54:10 -08009090{
9091 ALOGV("RecordThread::getActiveMicrophones");
Andy Hungf79092d2023-08-31 16:13:39 -07009092 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009093 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009094 return NO_INIT;
9095 }
jiabin9ff780e2018-03-19 18:19:52 -07009096 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
9097 return status;
jiabin653cc0a2018-01-17 17:54:10 -08009098}
9099
Andy Hung71742ab2023-07-07 13:47:37 -07009100status_t RecordThread::setPreferredMicrophoneDirection(
Paul McLean12340082019-03-19 09:35:05 -06009101 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009102{
Paul McLean12340082019-03-19 09:35:05 -06009103 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Andy Hungf79092d2023-08-31 16:13:39 -07009104 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009105 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009106 return NO_INIT;
9107 }
Paul McLean12340082019-03-19 09:35:05 -06009108 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009109}
9110
Andy Hung71742ab2023-07-07 13:47:37 -07009111status_t RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07009112{
Paul McLean12340082019-03-19 09:35:05 -06009113 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Andy Hungf79092d2023-08-31 16:13:39 -07009114 audio_utils::lock_guard _l(mutex());
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009115 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06009116 return NO_INIT;
9117 }
Paul McLean12340082019-03-19 09:35:05 -06009118 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07009119}
9120
Andy Hung71742ab2023-07-07 13:47:37 -07009121status_t RecordThread::shareAudioHistory(
Eric Laurentec376dc2021-04-08 20:41:22 +02009122 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9123 int64_t sharedAudioStartMs) {
Andy Hungf79092d2023-08-31 16:13:39 -07009124 audio_utils::lock_guard _l(mutex());
Eric Laurentec376dc2021-04-08 20:41:22 +02009125 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
9126}
9127
Andy Hung71742ab2023-07-07 13:47:37 -07009128status_t RecordThread::shareAudioHistory_l(
Eric Laurentec376dc2021-04-08 20:41:22 +02009129 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
9130 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009131
Eric Laurentec376dc2021-04-08 20:41:22 +02009132 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
9133 return BAD_VALUE;
9134 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009135
9136 if (sharedAudioStartMs < 0
9137 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009138 return BAD_VALUE;
9139 }
9140
Eric Laurent2407ce32021-04-26 14:56:03 +02009141 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
9142 // As we cannot detect more than one wraparound, only accept values up current write position
9143 // after one wraparound
9144 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
9145 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02009146 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02009147 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
9148 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02009149 // Bring the start frame position within the input buffer to match the documented
9150 // "best effort" behavior of the API.
9151 if (sharedOffset < 0) {
9152 sharedAudioStartFrames = mRsmpInRear;
Andy Hung71ba4b32022-10-06 12:09:49 -07009153 } else if (sharedOffset > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009154 sharedAudioStartFrames =
9155 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02009156 }
9157
Eric Laurentec376dc2021-04-08 20:41:22 +02009158 mSharedAudioPackageName = sharedAudioPackageName;
9159 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009160 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02009161 } else {
9162 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02009163 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02009164 }
9165 return NO_ERROR;
9166}
9167
Andy Hung71742ab2023-07-07 13:47:37 -07009168void RecordThread::resetAudioHistory_l() {
Eric Laurent92d0a322021-07-16 15:32:33 +02009169 mSharedAudioSessionId = AUDIO_SESSION_NONE;
9170 mSharedAudioStartFrames = -1;
9171 mSharedAudioPackageName = "";
9172}
9173
Andy Hung71742ab2023-07-07 13:47:37 -07009174ThreadBase::MetadataUpdate RecordThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -07009175{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08009176 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +01009177 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07009178 }
9179 StreamInHalInterface::SinkMetadata metadata;
Eric Laurent78b07302022-10-07 16:20:34 +02009180 auto backInserter = std::back_inserter(metadata.tracks);
Andy Hung3ff4b552023-06-26 19:20:57 -07009181 for (const sp<IAfRecordTrack>& track : mActiveTracks) {
Eric Laurent78b07302022-10-07 16:20:34 +02009182 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07009183 }
9184 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +01009185 MetadataUpdate change;
9186 change.recordMetadataUpdate = metadata.tracks;
9187 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -07009188}
9189
Andy Hung87e82412023-08-29 14:26:09 -07009190// destroyTrack_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -07009191void RecordThread::destroyTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009192{
Eric Laurentbfb1b832013-01-07 09:53:42 -08009193 track->terminate();
Andy Hung3ff4b552023-06-26 19:20:57 -07009194 track->setState(IAfTrackBase::STOPPED);
Eric Laurentec376dc2021-04-08 20:41:22 +02009195
Eric Laurent81784c32012-11-19 14:55:58 -08009196 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08009197 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08009198 removeTrack_l(track);
9199 }
9200}
9201
Andy Hung71742ab2023-07-07 13:47:37 -07009202void RecordThread::removeTrack_l(const sp<IAfRecordTrack>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08009203{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009204 String8 result;
9205 track->appendDump(result, false /* active */);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009206 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.c_str());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009207
Eric Laurent81784c32012-11-19 14:55:58 -08009208 mTracks.remove(track);
9209 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009210 if (track->isFastTrack()) {
9211 ALOG_ASSERT(!mFastTrackAvail);
9212 mFastTrackAvail = true;
9213 }
Eric Laurent81784c32012-11-19 14:55:58 -08009214}
9215
Andy Hung71742ab2023-07-07 13:47:37 -07009216void RecordThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009217{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07009218 AudioStreamIn *input = mInput;
9219 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
9220 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08009221 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07009222 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07009223 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009224 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009225 }
Andy Hungbfa64962017-06-12 14:43:19 -07009226
9227 if (input != nullptr) {
9228 dprintf(fd, " Hal stream dump:\n");
9229 (void)input->stream->dump(fd);
9230 }
9231
Glenn Kasten6e6704c2014-07-03 10:20:00 -07009232 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07009233 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08009234
Glenn Kasten2f90c512015-12-02 11:40:09 -08009235 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
9236 // while we are dumping it. It may be inconsistent, but it won't mutate!
9237 // This is a large object so we place it on the heap.
9238 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07009239 const std::unique_ptr<FastCaptureDumpState> copy =
9240 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08009241 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08009242}
9243
Andy Hung71742ab2023-07-07 13:47:37 -07009244void RecordThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent81784c32012-11-19 14:55:58 -08009245{
Eric Laurent81784c32012-11-19 14:55:58 -08009246 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08009247 size_t numtracks = mTracks.size();
9248 size_t numactive = mActiveTracks.size();
9249 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009250 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009251 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08009252 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07009253 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009254 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009255 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009256 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009257 sp<IAfRecordTrack> track = mTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009258 if (track != 0) {
9259 bool active = mActiveTracks.indexOf(track) >= 0;
9260 if (active) {
9261 numactiveseen++;
9262 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009263 result.append(prefix);
9264 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08009265 }
Eric Laurent81784c32012-11-19 14:55:58 -08009266 }
Marco Nelissenb2208842014-02-07 14:00:50 -08009267 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07009268 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08009269 }
9270
Marco Nelissenb2208842014-02-07 14:00:50 -08009271 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009272 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08009273 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009274 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07009275 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08009276 for (size_t i = 0; i < numactive; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009277 sp<IAfRecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08009278 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009279 result.append(prefix);
9280 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08009281 }
Glenn Kasten2b806402013-11-20 16:37:38 -08009282 }
Eric Laurent81784c32012-11-19 14:55:58 -08009283
9284 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +00009285 write(fd, result.c_str(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08009286}
9287
Andy Hung71742ab2023-07-07 13:47:37 -07009288void RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009289{
Andy Hungf79092d2023-08-31 16:13:39 -07009290 audio_utils::lock_guard _l(mutex());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009291 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009292 sp<IAfRecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07009293 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08009294 track->setSilenced(silenced);
9295 }
9296 }
9297}
Andy Hung73c02e42015-03-29 01:13:58 -07009298
Andy Hung3ff4b552023-06-26 19:20:57 -07009299void ResamplerBufferProvider::reset()
Andy Hung73c02e42015-03-29 01:13:58 -07009300{
Andy Hung44f27182023-07-06 20:56:16 -07009301 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009302 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009303 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009304 const int32_t rear = recordThread->mRsmpInRear;
9305 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02009306 if (mRecordTrack->startFrames() >= 0) {
9307 int32_t startFrames = mRecordTrack->startFrames();
9308 // Accept a recent wraparound of mRsmpInRear
9309 if (startFrames <= rear) {
9310 deltaFrames = rear - startFrames;
9311 } else {
9312 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02009313 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009314 // start frame cannot be further in the past than start of resampling buffer
9315 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
9316 deltaFrames = recordThread->mRsmpInFrames;
9317 }
9318 }
9319 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07009320}
9321
Andy Hung3ff4b552023-06-26 19:20:57 -07009322void ResamplerBufferProvider::sync(
Andy Hung73c02e42015-03-29 01:13:58 -07009323 size_t *framesAvailable, bool *hasOverrun)
9324{
Andy Hung44f27182023-07-06 20:56:16 -07009325 const auto threadBase = mRecordTrack->thread().promote();
Andy Hung71742ab2023-07-07 13:47:37 -07009326 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Andy Hung73c02e42015-03-29 01:13:58 -07009327 const int32_t rear = recordThread->mRsmpInRear;
9328 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009329 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07009330
9331 size_t framesIn;
9332 bool overrun = false;
9333 if (filled < 0) {
9334 // should not happen, but treat like a massive overrun and re-sync
9335 framesIn = 0;
9336 mRsmpInFront = rear;
9337 overrun = true;
9338 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
9339 framesIn = (size_t) filled;
9340 } else {
9341 // client is not keeping up with server, but give it latest data
9342 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07009343 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
9344 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07009345 overrun = true;
9346 }
9347 if (framesAvailable != NULL) {
9348 *framesAvailable = framesIn;
9349 }
9350 if (hasOverrun != NULL) {
9351 *hasOverrun = overrun;
9352 }
9353}
9354
Eric Laurent81784c32012-11-19 14:55:58 -08009355// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009356status_t ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08009357 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009358{
Andy Hung44f27182023-07-06 20:56:16 -07009359 const auto threadBase = mRecordTrack->thread().promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009360 if (threadBase == 0) {
9361 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009362 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009363 return NOT_ENOUGH_DATA;
9364 }
Andy Hung71742ab2023-07-07 13:47:37 -07009365 auto* const recordThread = static_cast<RecordThread *>(threadBase->asIAfRecordThread().get());
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009366 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07009367 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07009368 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009369 // FIXME should not be P2 (don't want to increase latency)
9370 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08009371 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07009372 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009373
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009374 front &= recordThread->mRsmpInFramesP2 - 1;
9375 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07009376 if (part1 > (size_t) filled) {
9377 part1 = filled;
9378 }
9379 size_t ask = buffer->frameCount;
9380 ALOG_ASSERT(ask > 0);
9381 if (part1 > ask) {
9382 part1 = ask;
9383 }
9384 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07009385 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07009386 buffer->raw = NULL;
9387 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07009388 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07009389 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08009390 }
9391
Andy Hung57446612015-04-19 23:56:46 -07009392 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07009393 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07009394 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08009395 return NO_ERROR;
9396}
9397
9398// AudioBufferProvider interface
Andy Hung3ff4b552023-06-26 19:20:57 -07009399void ResamplerBufferProvider::releaseBuffer(
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08009400 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08009401{
Hongwei Wang95e37682019-04-12 11:13:36 -07009402 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009403 if (stepCount == 0) {
9404 return;
9405 }
Eric Laurent1e28aaa2023-04-16 19:34:23 +02009406 ALOG_ASSERT(stepCount <= (int32_t)mRsmpInUnrel);
Andy Hung73c02e42015-03-29 01:13:58 -07009407 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07009408 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07009409 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08009410 buffer->frameCount = 0;
9411}
9412
Andy Hung71742ab2023-07-07 13:47:37 -07009413void RecordThread::checkBtNrec()
Eric Laurentd8365c52017-07-16 15:27:05 -07009414{
Andy Hungf79092d2023-08-31 16:13:39 -07009415 audio_utils::lock_guard _l(mutex());
Eric Laurentd8365c52017-07-16 15:27:05 -07009416 checkBtNrec_l();
9417}
9418
Andy Hung71742ab2023-07-07 13:47:37 -07009419void RecordThread::checkBtNrec_l()
Eric Laurentd8365c52017-07-16 15:27:05 -07009420{
9421 // disable AEC and NS if the device is a BT SCO headset supporting those
9422 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07009423 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Andy Hung2cbc2722023-07-17 17:05:00 -07009424 mAfThreadCallback->btNrecIsOff();
Eric Laurentd8365c52017-07-16 15:27:05 -07009425 if (mBtNrecSuspended.exchange(suspend) != suspend) {
9426 for (size_t i = 0; i < mEffectChains.size(); i++) {
9427 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
9428 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
9429 }
9430 }
9431}
9432
Andy Hung97a893e2015-03-29 01:03:07 -07009433
Andy Hung71742ab2023-07-07 13:47:37 -07009434bool RecordThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent10351942014-05-08 18:49:52 -07009435 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08009436{
9437 bool reconfig = false;
9438
Eric Laurent10351942014-05-08 18:49:52 -07009439 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08009440
Eric Laurent10351942014-05-08 18:49:52 -07009441 audio_format_t reqFormat = mFormat;
9442 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07009443 // 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 +08009444 [[maybe_unused]] audio_channel_mask_t channelMask =
9445 audio_channel_in_mask_from_count(mChannelCount);
Eric Laurent10351942014-05-08 18:49:52 -07009446
9447 AudioParameter param = AudioParameter(keyValuePair);
9448 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07009449
9450 // scope for AutoPark extends to end of method
9451 AutoPark<FastCapture> park(mFastCapture);
9452
Eric Laurent10351942014-05-08 18:49:52 -07009453 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
9454 // channel count change can be requested. Do we mandate the first client defines the
9455 // HAL sampling rate and channel count or do we allow changes on the fly?
9456 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
9457 samplingRate = value;
9458 reconfig = true;
9459 }
9460 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07009461 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07009462 status = BAD_VALUE;
9463 } else {
9464 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08009465 reconfig = true;
9466 }
Eric Laurent10351942014-05-08 18:49:52 -07009467 }
9468 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
9469 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07009470 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07009471 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07009472 status = BAD_VALUE;
9473 } else {
9474 channelMask = mask;
9475 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009476 }
Eric Laurent10351942014-05-08 18:49:52 -07009477 }
9478 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
9479 // do not accept frame count changes if tracks are open as the track buffer
9480 // size depends on frame count and correct behavior would not be guaranteed
9481 // if frame count is changed after track creation
9482 if (mActiveTracks.size() > 0) {
9483 status = INVALID_OPERATION;
9484 } else {
9485 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08009486 }
Eric Laurent10351942014-05-08 18:49:52 -07009487 }
9488 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009489 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009490 }
9491 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
9492 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07009493 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07009494 }
Glenn Kastene198c362013-08-13 09:13:36 -07009495
Eric Laurent10351942014-05-08 18:49:52 -07009496 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009497 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009498 if (status == INVALID_OPERATION) {
9499 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009500 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07009501 }
9502 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009503 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00009504 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
9505 if (mInput->stream->getAudioProperties(&config) == OK &&
9506 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
9507 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07009508 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009509 status = NO_ERROR;
9510 }
Eric Laurent81784c32012-11-19 14:55:58 -08009511 }
Eric Laurent10351942014-05-08 18:49:52 -07009512 if (status == NO_ERROR) {
9513 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07009514 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08009515 }
9516 }
Eric Laurent81784c32012-11-19 14:55:58 -08009517 }
Eric Laurent10351942014-05-08 18:49:52 -07009518
Eric Laurent81784c32012-11-19 14:55:58 -08009519 return reconfig;
9520}
9521
Andy Hung71742ab2023-07-07 13:47:37 -07009522String8 RecordThread::getParameters(const String8& keys)
Eric Laurent81784c32012-11-19 14:55:58 -08009523{
Andy Hungf79092d2023-08-31 16:13:39 -07009524 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009525 if (initCheck() == NO_ERROR) {
9526 String8 out_s8;
9527 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
9528 return out_s8;
9529 }
Eric Laurent81784c32012-11-19 14:55:58 -08009530 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009531 return {};
Eric Laurent81784c32012-11-19 14:55:58 -08009532}
9533
Andy Hung71742ab2023-07-07 13:47:37 -07009534void RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009535 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009536 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08009537 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07009538 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009539 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07009540 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009541 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
9542 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08009543 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07009544 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009545 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07009546 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07009547 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08009548 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009549 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08009550 break;
9551 }
Andy Hung2cbc2722023-07-17 17:05:00 -07009552 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08009553}
9554
Andy Hung71742ab2023-07-07 13:47:37 -07009555void RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08009556{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009557 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9558 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07009559 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009560 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9561 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07009562 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
9563 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009564 } else {
Andy Hung936845a2021-06-08 00:09:06 -07009565 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07009566 ALOGI("HAL format %#x is not linear pcm", mFormat);
9567 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009568 result = mInput->stream->getFrameSize(&mFrameSize);
9569 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009570 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9571 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009572 result = mInput->stream->getBufferSize(&mBufferSize);
9573 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08009574 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009575 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
9576 "mBufferSize=%zu, mFrameCount=%zu",
9577 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07009578
Eric Laurentec376dc2021-04-08 20:41:22 +02009579 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
9580 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009581 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08009582
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08009583 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
9584 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07009585
9586 audio_input_flags_t flags = mInput->flags;
9587 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
9588 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung4d693a32023-07-19 12:47:35 -07009589 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungea840382020-05-05 21:50:17 -07009590 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9591 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9592 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9593 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9594 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9595 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08009596}
9597
Andy Hung71742ab2023-07-07 13:47:37 -07009598uint32_t RecordThread::getInputFramesLost() const
Eric Laurent81784c32012-11-19 14:55:58 -08009599{
Andy Hungf79092d2023-08-31 16:13:39 -07009600 audio_utils::lock_guard _l(mutex());
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009601 uint32_t result;
9602 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
9603 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08009604 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009605 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08009606}
9607
Andy Hung71742ab2023-07-07 13:47:37 -07009608KeyedVector<audio_session_t, bool> RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08009609{
Glenn Kastend848eb42016-03-08 13:42:11 -08009610 KeyedVector<audio_session_t, bool> ids;
Andy Hungf79092d2023-08-31 16:13:39 -07009611 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009612 for (size_t j = 0; j < mTracks.size(); ++j) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009613 sp<IAfRecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08009614 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08009615 if (ids.indexOfKey(sessionId) < 0) {
9616 ids.add(sessionId, true);
9617 }
9618 }
9619 return ids;
9620}
9621
Andy Hung71742ab2023-07-07 13:47:37 -07009622AudioStreamIn* RecordThread::clearInput()
Eric Laurent81784c32012-11-19 14:55:58 -08009623{
Andy Hungf79092d2023-08-31 16:13:39 -07009624 audio_utils::lock_guard _l(mutex());
Eric Laurent81784c32012-11-19 14:55:58 -08009625 AudioStreamIn *input = mInput;
9626 mInput = NULL;
Mikhail Naganov49aecf02023-09-08 15:14:34 -07009627 mInputSource.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08009628 return input;
9629}
9630
Andy Hung87e82412023-08-29 14:26:09 -07009631// this method must always be called either with ThreadBase mutex() held or inside the thread loop
Andy Hung71742ab2023-07-07 13:47:37 -07009632sp<StreamHalInterface> RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08009633{
9634 if (mInput == NULL) {
9635 return NULL;
9636 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009637 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08009638}
9639
Andy Hung71742ab2023-07-07 13:47:37 -07009640status_t RecordThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009641{
Eric Laurent81784c32012-11-19 14:55:58 -08009642 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07009643 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08009644 chain->setInBuffer(NULL);
9645 chain->setOutBuffer(NULL);
9646
9647 checkSuspendOnAddEffectChain_l(chain);
9648
Eric Laurent1b928682014-10-02 19:41:47 -07009649 // make sure enabled pre processing effects state is communicated to the HAL as we
9650 // just moved them to a new input stream.
9651 chain->syncHalEffectsState();
9652
Eric Laurent81784c32012-11-19 14:55:58 -08009653 mEffectChains.add(chain);
9654
9655 return NO_ERROR;
9656}
9657
Andy Hung71742ab2023-07-07 13:47:37 -07009658size_t RecordThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent81784c32012-11-19 14:55:58 -08009659{
9660 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009661
9662 for (size_t i = 0; i < mEffectChains.size(); i++) {
9663 if (chain == mEffectChains[i]) {
9664 mEffectChains.removeAt(i);
9665 break;
9666 }
Eric Laurent81784c32012-11-19 14:55:58 -08009667 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07009668 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08009669}
9670
Andy Hung71742ab2023-07-07 13:47:37 -07009671status_t RecordThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent1c333e22014-05-20 10:48:17 -07009672 audio_patch_handle_t *handle)
9673{
9674 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009675
9676 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009677 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009678 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009679 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009680 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009681 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009682 }
9683
Eric Laurentd8365c52017-07-16 15:27:05 -07009684 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009685
9686 // store new source and send to effects
9687 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9688 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009689 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009690 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009691 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009692 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009693
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009694 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009695 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9696 status = hwDevice->createAudioPatch(patch->num_sources,
9697 patch->sources,
9698 patch->num_sinks,
9699 patch->sinks,
9700 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009701 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009702 status = mInput->stream->legacyCreateAudioPatch(patch->sources[0],
9703 patch->sinks[0].ext.mix.usecase.source,
9704 patch->sources[0].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07009705 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009706 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009707
jiabinc52b1ff2019-10-31 17:20:42 -07009708 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009709 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009710 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009711 }
Eric Laurent296fb132015-05-01 11:38:42 -07009712
Andy Hungc2b11cb2020-04-22 09:04:01 -07009713 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009714 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009715 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009716 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009717 // also dispatch to active AudioRecords
9718 for (const auto &track : mActiveTracks) {
9719 track->logEndInterval();
9720 track->logBeginInterval(pathSourcesAsString);
9721 }
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 Hung71742ab2023-07-07 13:47:37 -07009728status_t RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent1c333e22014-05-20 10:48:17 -07009729{
9730 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009731
jiabinc52b1ff2019-10-31 17:20:42 -07009732 mPatch = audio_patch{};
9733 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009734
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009735 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009736 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9737 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009738 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -08009739 status = mInput->stream->legacyReleaseAudioPatch();
Eric Laurent1c333e22014-05-20 10:48:17 -07009740 }
Eric Laurentdda206a2022-07-08 17:28:35 +02009741 // Force meteadata update after a route change
9742 mActiveTracks.setHasChanged();
9743
Eric Laurent1c333e22014-05-20 10:48:17 -07009744 return status;
9745}
9746
Andy Hung71742ab2023-07-07 13:47:37 -07009747void RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
jiabinc52b1ff2019-10-31 17:20:42 -07009748{
Andy Hungf79092d2023-08-31 16:13:39 -07009749 audio_utils::lock_guard _l(mutex());
jiabinc52b1ff2019-10-31 17:20:42 -07009750 mOutDevices = outDevices;
9751 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9752 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009753 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009754 }
9755}
9756
Andy Hung71742ab2023-07-07 13:47:37 -07009757int32_t RecordThread::getOldestFront_l()
Eric Laurentec376dc2021-04-08 20:41:22 +02009758{
9759 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009760 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009761 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009762 int32_t oldestFront = mRsmpInRear;
9763 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009764 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009765 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurent2407ce32021-04-26 14:56:03 +02009766 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009767 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009768 if (filled > maxFilled) {
9769 oldestFront = front;
9770 maxFilled = filled;
9771 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009772 }
Andy Hung71ba4b32022-10-06 12:09:49 -07009773 if (maxFilled > static_cast<signed>(mRsmpInFrames)) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009774 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9775 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009776 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009777}
9778
Andy Hung71742ab2023-07-07 13:47:37 -07009779void RecordThread::updateFronts_l(int32_t offset)
Eric Laurentec376dc2021-04-08 20:41:22 +02009780{
9781 if (offset == 0) {
9782 return;
9783 }
9784 for (size_t i = 0; i < mTracks.size(); i++) {
Andy Hung3ff4b552023-06-26 19:20:57 -07009785 int32_t front = mTracks[i]->resamplerBufferProvider()->getFront();
Eric Laurentec376dc2021-04-08 20:41:22 +02009786 front = audio_utils::safe_sub_overflow(front, offset);
Andy Hung3ff4b552023-06-26 19:20:57 -07009787 mTracks[i]->resamplerBufferProvider()->setFront(front);
Eric Laurentec376dc2021-04-08 20:41:22 +02009788 }
9789}
9790
Andy Hung71742ab2023-07-07 13:47:37 -07009791void RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
Eric Laurentec376dc2021-04-08 20:41:22 +02009792{
9793 // This is the formula for calculating the temporary buffer size.
9794 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9795 // 1 full output buffer, regardless of the alignment of the available input.
9796 // The value is somewhat arbitrary, and could probably be even larger.
9797 // A larger value should allow more old data to be read after a track calls start(),
9798 // without increasing latency.
9799 //
9800 // Note this is independent of the maximum downsampling ratio permitted for capture.
9801 size_t minRsmpInFrames = mFrameCount * 7;
9802
9803 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9804 // capture history available to another client using the same session ID:
9805 // dimension the resampler input buffer accordingly.
9806
9807 // Get oldest client read position: getOldestFront_l() must be called before altering
9808 // mRsmpInRear, or mRsmpInFrames
9809 int32_t previousFront = getOldestFront_l();
9810 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9811 int32_t previousRear = mRsmpInRear;
9812 mRsmpInRear = 0;
9813
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009814 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
Andy Hung71742ab2023-07-07 13:47:37 -07009815 && maxSharedAudioHistoryMs <= kMaxSharedAudioHistoryMs,
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009816 "resizeInputBuffer_l() called with invalid max shared history %d",
9817 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009818 if (maxSharedAudioHistoryMs != 0) {
9819 // resizeInputBuffer_l should never be called with a non zero shared history if the
9820 // buffer was not already allocated
9821 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9822 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9823 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9824 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009825 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009826 return;
9827 }
9828 mRsmpInFrames = rsmpInFrames;
9829 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009830 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009831 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9832 // initialized
9833 if (mRsmpInFrames < minRsmpInFrames) {
9834 mRsmpInFrames = minRsmpInFrames;
9835 }
9836 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9837
9838 // TODO optimize audio capture buffer sizes ...
9839 // Here we calculate the size of the sliding buffer used as a source
9840 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9841 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9842 // be better to have it derived from the pipe depth in the long term.
9843 // The current value is higher than necessary. However it should not add to latency.
9844
9845 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9846 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9847
9848 void *rsmpInBuffer;
9849 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9850 // if posix_memalign fails, will segv here.
9851 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9852
9853 // Copy audio history if any from old buffer before freeing it
9854 if (previousRear != 0) {
9855 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9856 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9857
9858 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9859 previousFront &= previousRsmpInFramesP2 - 1;
9860 size_t part1 = previousRsmpInFramesP2 - previousFront;
9861 if (part1 > (size_t) unread) {
9862 part1 = unread;
9863 }
9864 if (part1 != 0) {
9865 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9866 part1 * mFrameSize);
9867 mRsmpInRear = part1;
9868 part1 = unread - part1;
9869 if (part1 != 0) {
9870 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9871 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9872 mRsmpInRear += part1;
9873 }
9874 }
9875 // Update front for all clients according to new rear
9876 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9877 } else {
9878 mRsmpInRear = 0;
9879 }
9880 free(mRsmpInBuffer);
9881 mRsmpInBuffer = rsmpInBuffer;
9882}
9883
Andy Hung71742ab2023-07-07 13:47:37 -07009884void RecordThread::addPatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009885{
Andy Hungf79092d2023-08-31 16:13:39 -07009886 audio_utils::lock_guard _l(mutex());
Eric Laurent83b88082014-06-20 18:31:16 -07009887 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009888 if (record->getSource()) {
9889 mSource = record->getSource();
9890 }
Eric Laurent83b88082014-06-20 18:31:16 -07009891}
9892
Andy Hung71742ab2023-07-07 13:47:37 -07009893void RecordThread::deletePatchTrack(const sp<IAfPatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009894{
Andy Hungf79092d2023-08-31 16:13:39 -07009895 audio_utils::lock_guard _l(mutex());
Mikhail Naganov2534b382019-09-25 13:05:02 -07009896 if (mSource == record->getSource()) {
9897 mSource = mInput;
9898 }
Eric Laurent83b88082014-06-20 18:31:16 -07009899 destroyTrack_l(record);
9900}
9901
Andy Hung71742ab2023-07-07 13:47:37 -07009902void RecordThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent83b88082014-06-20 18:31:16 -07009903{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009904 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009905 config->role = AUDIO_PORT_ROLE_SINK;
9906 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9907 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009908 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9909 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9910 config->flags.input = mInput->flags;
9911 }
Eric Laurent83b88082014-06-20 18:31:16 -07009912}
Eric Laurent1c333e22014-05-20 10:48:17 -07009913
Eric Laurent6acd1d42017-01-04 14:23:29 -08009914// ----------------------------------------------------------------------------
9915// Mmap
9916// ----------------------------------------------------------------------------
9917
Andy Hung667dec42023-07-07 15:58:48 -07009918// Mmap stream control interface implementation. Each MmapThreadHandle controls one
9919// MmapPlaybackThread or MmapCaptureThread instance.
9920class MmapThreadHandle : public MmapStreamInterface {
9921public:
9922 explicit MmapThreadHandle(const sp<IAfMmapThread>& thread);
9923 ~MmapThreadHandle() override;
9924
9925 // MmapStreamInterface virtuals
9926 status_t createMmapBuffer(int32_t minSizeFrames,
9927 struct audio_mmap_buffer_info* info) final;
9928 status_t getMmapPosition(struct audio_mmap_position* position) final;
9929 status_t getExternalPosition(uint64_t* position, int64_t* timeNanos) final;
9930 status_t start(const AudioClient& client,
9931 const audio_attributes_t* attr, audio_port_handle_t* handle) final;
9932 status_t stop(audio_port_handle_t handle) final;
9933 status_t standby() final;
9934 status_t reportData(const void* buffer, size_t frameCount) final;
9935private:
9936 const sp<IAfMmapThread> mThread;
9937};
9938
9939/* static */
9940sp<MmapStreamInterface> IAfMmapThread::createMmapStreamInterfaceAdapter(
9941 const sp<IAfMmapThread>& mmapThread) {
9942 return sp<MmapThreadHandle>::make(mmapThread);
9943}
9944
9945MmapThreadHandle::MmapThreadHandle(const sp<IAfMmapThread>& thread)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009946 : mThread(thread)
9947{
Phil Burk9fabbf82017-08-03 12:02:00 -07009948 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009949}
9950
Andy Hung667dec42023-07-07 15:58:48 -07009951// MmapStreamInterface could be directly implemented by MmapThread excepting this
9952// special handling on adapter dtor.
9953MmapThreadHandle::~MmapThreadHandle()
Eric Laurent6acd1d42017-01-04 14:23:29 -08009954{
Phil Burk9fabbf82017-08-03 12:02:00 -07009955 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009956}
9957
Andy Hung667dec42023-07-07 15:58:48 -07009958status_t MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009959 struct audio_mmap_buffer_info *info)
9960{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961 return mThread->createMmapBuffer(minSizeFrames, info);
9962}
9963
Andy Hung667dec42023-07-07 15:58:48 -07009964status_t MmapThreadHandle::getMmapPosition(struct audio_mmap_position* position)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009965{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009966 return mThread->getMmapPosition(position);
9967}
9968
Andy Hung667dec42023-07-07 15:58:48 -07009969status_t MmapThreadHandle::getExternalPosition(uint64_t* position,
jiabinb7d8c5a2020-08-26 17:24:52 -07009970 int64_t *timeNanos) {
9971 return mThread->getExternalPosition(position, timeNanos);
9972}
9973
Andy Hung667dec42023-07-07 15:58:48 -07009974status_t MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009975 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976{
jiabind1f1cb62020-03-24 11:57:57 -07009977 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009978}
9979
Andy Hung667dec42023-07-07 15:58:48 -07009980status_t MmapThreadHandle::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009981{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009982 return mThread->stop(handle);
9983}
9984
Andy Hung667dec42023-07-07 15:58:48 -07009985status_t MmapThreadHandle::standby()
Eric Laurent18b57012017-02-13 16:23:52 -08009986{
Eric Laurent18b57012017-02-13 16:23:52 -08009987 return mThread->standby();
9988}
9989
Andy Hung667dec42023-07-07 15:58:48 -07009990status_t MmapThreadHandle::reportData(const void* buffer, size_t frameCount)
9991{
jiabinfc791ee2023-02-15 19:43:40 +00009992 return mThread->reportData(buffer, frameCount);
9993}
9994
Eric Laurent6acd1d42017-01-04 14:23:29 -08009995
Andy Hung71742ab2023-07-07 13:47:37 -07009996MmapThread::MmapThread(
Andy Hung2cbc2722023-07-17 17:05:00 -07009997 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71ba4b32022-10-06 12:09:49 -07009998 AudioHwDevice *hwDev, const sp<StreamHalInterface>& stream, bool systemReady, bool isOut)
Andy Hung2cbc2722023-07-17 17:05:00 -07009999 : ThreadBase(afThreadCallback, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010000 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +020010001 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010002 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -070010003 mActiveTracks(&this->mLocalLog),
10004 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
10005 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006{
Eric Laurent18b57012017-02-13 16:23:52 -080010007 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010008 readHalParameters_l();
10009}
10010
Andy Hung71742ab2023-07-07 13:47:37 -070010011void MmapThread::onFirstRef()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010012{
10013 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
10014}
10015
Andy Hung71742ab2023-07-07 13:47:37 -070010016void MmapThread::disconnect()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010017{
Andy Hung3ff4b552023-06-26 19:20:57 -070010018 ActiveTracks<IAfMmapTrack> activeTracks;
Eric Laurent331679c2018-04-16 17:03:16 -070010019 {
Andy Hungf79092d2023-08-31 16:13:39 -070010020 audio_utils::lock_guard _l(mutex());
Andy Hung3ff4b552023-06-26 19:20:57 -070010021 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent331679c2018-04-16 17:03:16 -070010022 activeTracks.add(t);
10023 }
10024 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010025 for (const sp<IAfMmapTrack>& t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010026 stop(t->portId());
10027 }
Phil Burk9fabbf82017-08-03 12:02:00 -070010028 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010029 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010030 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010031 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010032 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010033 }
10034}
10035
10036
Andy Hung71742ab2023-07-07 13:47:37 -070010037void MmapThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010038 audio_stream_type_t streamType __unused,
10039 audio_session_t sessionId,
10040 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010041 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010042 audio_port_handle_t portId)
10043{
10044 mAttr = *attr;
10045 mSessionId = sessionId;
10046 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010047 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010048 mPortId = portId;
10049}
10050
Andy Hung71742ab2023-07-07 13:47:37 -070010051status_t MmapThread::createMmapBuffer(int32_t minSizeFrames,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010052 struct audio_mmap_buffer_info *info)
10053{
10054 if (mHalStream == 0) {
10055 return NO_INIT;
10056 }
Eric Laurent18b57012017-02-13 16:23:52 -080010057 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010058 return mHalStream->createMmapBuffer(minSizeFrames, info);
10059}
10060
Andy Hung71742ab2023-07-07 13:47:37 -070010061status_t MmapThread::getMmapPosition(struct audio_mmap_position* position) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010062{
10063 if (mHalStream == 0) {
10064 return NO_INIT;
10065 }
10066 return mHalStream->getMmapPosition(position);
10067}
10068
Andy Hung71742ab2023-07-07 13:47:37 -070010069status_t MmapThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070010070{
Eric Laurentdda206a2022-07-08 17:28:35 +020010071 // The HAL must receive track metadata before starting the stream
10072 updateMetadata_l();
Eric Laurent331679c2018-04-16 17:03:16 -070010073 status_t ret = mHalStream->start();
10074 if (ret != NO_ERROR) {
10075 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
10076 return ret;
10077 }
Andy Hungcf10d742020-04-28 15:38:24 -070010078 if (mStandby) {
10079 mThreadMetrics.logBeginInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010080 mThreadSnapshot.onBegin();
Andy Hungcf10d742020-04-28 15:38:24 -070010081 mStandby = false;
10082 }
Eric Laurent331679c2018-04-16 17:03:16 -070010083 return NO_ERROR;
10084}
10085
Andy Hung71742ab2023-07-07 13:47:37 -070010086status_t MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -070010087 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010088 audio_port_handle_t *handle)
10089{
Eric Laurenta54f1282017-07-01 19:39:32 -070010090 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +000010091 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010092 if (mHalStream == 0) {
10093 return NO_INIT;
10094 }
10095
10096 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010097
Eric Laurentdda206a2022-07-08 17:28:35 +020010098 // For the first track, reuse portId and session allocated when the stream was opened.
Eric Laurenta54f1282017-07-01 19:39:32 -070010099 if (*handle == mPortId) {
Eric Laurentdda206a2022-07-08 17:28:35 +020010100 acquireWakeLock();
10101 return NO_ERROR;
Eric Laurenta54f1282017-07-01 19:39:32 -070010102 }
10103
10104 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
10105
10106 audio_io_handle_t io = mId;
Andy Hungc5106312023-07-19 16:56:19 -070010107 const AttributionSourceState adjAttributionSource = afutils::checkAttributionSourcePackage(
Atneya Nairf59db5c2023-05-10 21:37:41 -070010108 client.attributionSource);
10109
Eric Laurenta54f1282017-07-01 19:39:32 -070010110 if (isOutput()) {
10111 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
10112 config.sample_rate = mSampleRate;
10113 config.channel_mask = mChannelMask;
10114 config.format = mFormat;
10115 audio_stream_type_t stream = streamType();
10116 audio_output_flags_t flags =
10117 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010118 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -080010119 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010120 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +000010121 bool isBitPerfect;
Eric Laurenta54f1282017-07-01 19:39:32 -070010122 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
10123 mSessionId,
10124 &stream,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010125 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010126 &config,
10127 flags,
10128 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -080010129 &portId,
Eric Laurentb0a7bc92022-04-05 15:06:08 +020010130 &secondaryOutputs,
jiabinc658e452022-10-21 20:52:21 +000010131 &isSpatialized,
10132 &isBitPerfect);
Kevin Rocard153f92d2018-12-18 18:33:28 -080010133 ALOGD_IF(!secondaryOutputs.empty(),
10134 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010135 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -070010136 audio_config_base_t config;
10137 config.sample_rate = mSampleRate;
10138 config.channel_mask = mChannelMask;
10139 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010140 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -070010141 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -070010142 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -070010143 mSessionId,
Atneya Nairf59db5c2023-05-10 21:37:41 -070010144 adjAttributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -070010145 &config,
10146 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
10147 &deviceId,
10148 &portId);
10149 }
10150 // APM should not chose a different input or output stream for the same set of attributes
10151 // and audo configuration
10152 if (ret != NO_ERROR || io != mId) {
10153 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
10154 __FUNCTION__, ret, io, mId);
10155 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010156 }
10157
10158 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010159 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010160 } else {
jiabincfc10a42022-06-15 19:26:01 +000010161 {
10162 // Add the track record before starting input so that the silent status for the
10163 // client can be cached.
Andy Hungf79092d2023-08-31 16:13:39 -070010164 audio_utils::lock_guard _l(mutex());
jiabincfc10a42022-06-15 19:26:01 +000010165 setClientSilencedState_l(portId, false /*silenced*/);
10166 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010167 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010168 }
10169
Andy Hungf79092d2023-08-31 16:13:39 -070010170 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010171 // abort if start is rejected by audio policy manager
10172 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -080010173 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -070010174 if (!mActiveTracks.isEmpty()) {
Andy Hung87e82412023-08-29 14:26:09 -070010175 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010177 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010178 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010179 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010180 }
Andy Hung87e82412023-08-29 14:26:09 -070010181 mutex().lock();
Eric Laurent18b57012017-02-13 16:23:52 -080010182 } else {
10183 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010184 }
jiabincfc10a42022-06-15 19:26:01 +000010185 eraseClientSilencedState_l(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010186 return PERMISSION_DENIED;
10187 }
10188
Kevin Rocard1f564ac2018-03-29 13:53:10 -070010189 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
Andy Hung3ff4b552023-06-26 19:20:57 -070010190 sp<IAfMmapTrack> track = IAfMmapTrack::create(
10191 this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +000010192 mChannelMask, mSessionId, isOutput(),
10193 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -070010194 IPCThreadState::self()->getCallingPid(), portId);
jiabincfc10a42022-06-15 19:26:01 +000010195 if (!isOutput()) {
10196 track->setSilenced_l(isClientSilenced_l(portId));
10197 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010198
Eric Laurent4eb58f12018-12-07 16:41:02 -080010199 if (isOutput()) {
10200 // force volume update when a new track is added
10201 mHalVolFloat = -1.0f;
10202 } else if (!track->isSilenced_l()) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010203 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Andy Hung71ba4b32022-10-06 12:09:49 -070010204 if (t->isSilenced_l()
10205 && t->uid() != static_cast<uid_t>(client.attributionSource.uid)) {
Eric Laurent4eb58f12018-12-07 16:41:02 -080010206 t->invalidate();
Andy Hung71ba4b32022-10-06 12:09:49 -070010207 }
Eric Laurent4eb58f12018-12-07 16:41:02 -080010208 }
10209 }
10210
Eric Laurent6acd1d42017-01-04 14:23:29 -080010211 mActiveTracks.add(track);
Andy Hungbd72c542023-06-20 18:56:17 -070010212 sp<IAfEffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010213 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +020010214 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -080010215 chain->incTrackCnt();
10216 chain->incActiveTrackCnt();
10217 }
10218
Andy Hungc2b11cb2020-04-22 09:04:01 -070010219 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -080010220 *handle = portId;
Eric Laurentdda206a2022-07-08 17:28:35 +020010221
10222 if (mActiveTracks.size() == 1) {
10223 ret = exitStandby_l();
10224 }
10225
Eric Laurent6acd1d42017-01-04 14:23:29 -080010226 broadcast_l();
10227
Eric Laurentdda206a2022-07-08 17:28:35 +020010228 ALOGV("%s DONE status %d handle %d stream %p", __FUNCTION__, ret, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010229
Eric Laurentdda206a2022-07-08 17:28:35 +020010230 return ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010231}
10232
Andy Hung71742ab2023-07-07 13:47:37 -070010233status_t MmapThread::stop(audio_port_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010234{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010235 ALOGV("%s handle %d", __FUNCTION__, handle);
10236
10237 if (mHalStream == 0) {
10238 return NO_INIT;
10239 }
10240
Eric Laurenta54f1282017-07-01 19:39:32 -070010241 if (handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +000010242 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -070010243 return NO_ERROR;
10244 }
10245
Andy Hungf79092d2023-08-31 16:13:39 -070010246 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070010247
Andy Hung3ff4b552023-06-26 19:20:57 -070010248 sp<IAfMmapTrack> track;
10249 for (const sp<IAfMmapTrack>& t : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010250 if (handle == t->portId()) {
10251 track = t;
10252 break;
10253 }
10254 }
10255 if (track == 0) {
10256 return BAD_VALUE;
10257 }
10258
10259 mActiveTracks.remove(track);
jiabincfc10a42022-06-15 19:26:01 +000010260 eraseClientSilencedState_l(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010261
Andy Hung87e82412023-08-29 14:26:09 -070010262 mutex().unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010263 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -070010264 AudioSystem::stopOutput(track->portId());
10265 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010266 } else {
Eric Laurentfee19762018-01-29 18:44:13 -080010267 AudioSystem::stopInput(track->portId());
10268 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010269 }
Andy Hung87e82412023-08-29 14:26:09 -070010270 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010271
Andy Hungbd72c542023-06-20 18:56:17 -070010272 sp<IAfEffectChain> chain = getEffectChain_l(track->sessionId());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010273 if (chain != 0) {
10274 chain->decActiveTrackCnt();
10275 chain->decTrackCnt();
10276 }
10277
Eric Laurentdda206a2022-07-08 17:28:35 +020010278 if (mActiveTracks.isEmpty()) {
10279 mHalStream->stop();
10280 }
10281
Eric Laurent6acd1d42017-01-04 14:23:29 -080010282 broadcast_l();
10283
Eric Laurent6acd1d42017-01-04 14:23:29 -080010284 return NO_ERROR;
10285}
10286
Andy Hung71742ab2023-07-07 13:47:37 -070010287status_t MmapThread::standby()
Eric Laurent18b57012017-02-13 16:23:52 -080010288{
10289 ALOGV("%s", __FUNCTION__);
10290
10291 if (mHalStream == 0) {
10292 return NO_INIT;
10293 }
Eric Tan39ec8d62018-07-24 09:49:29 -070010294 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -080010295 return INVALID_OPERATION;
10296 }
10297 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -070010298 if (!mStandby) {
10299 mThreadMetrics.logEndInterval();
Andy Hung44d648b2022-04-08 17:33:40 -070010300 mThreadSnapshot.onEnd();
Andy Hungcf10d742020-04-28 15:38:24 -070010301 mStandby = true;
10302 }
Eric Laurent18b57012017-02-13 16:23:52 -080010303 releaseWakeLock();
10304 return NO_ERROR;
10305}
10306
Andy Hung71742ab2023-07-07 13:47:37 -070010307status_t MmapThread::reportData(const void* /*buffer*/, size_t /*frameCount*/) {
jiabinfc791ee2023-02-15 19:43:40 +000010308 // This is a stub implementation. The MmapPlaybackThread overrides this function.
10309 return INVALID_OPERATION;
10310}
Eric Laurent6acd1d42017-01-04 14:23:29 -080010311
Andy Hung71742ab2023-07-07 13:47:37 -070010312void MmapThread::readHalParameters_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010313{
10314 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
10315 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
10316 mFormat = mHALFormat;
10317 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
10318 result = mHalStream->getFrameSize(&mFrameSize);
10319 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -070010320 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
10321 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010322 result = mHalStream->getBufferSize(&mBufferSize);
10323 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
10324 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -070010325
Andy Hungcf10d742020-04-28 15:38:24 -070010326 // TODO: make a readHalParameters call?
10327 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -070010328 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
Andy Hung4d693a32023-07-19 12:47:35 -070010329 .set(AMEDIAMETRICS_PROP_ENCODING, IAfThreadBase::formatToString(mFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010330 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
10331 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
10332 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
10333 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
10334 /*
10335 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
10336 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
10337 (int32_t)mHapticChannelMask)
10338 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
10339 (int32_t)mHapticChannelCount)
10340 */
10341 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
Andy Hung4d693a32023-07-19 12:47:35 -070010342 IAfThreadBase::formatToString(mHALFormat).c_str())
Andy Hungc2b11cb2020-04-22 09:04:01 -070010343 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
10344 (int32_t)mFrameCount) // sic - added HAL
10345 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010346}
10347
Andy Hung71742ab2023-07-07 13:47:37 -070010348bool MmapThread::threadLoop()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010349{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010350 checkSilentMode_l();
10351
10352 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
10353
10354 while (!exitPending())
10355 {
Andy Hungbd72c542023-06-20 18:56:17 -070010356 Vector<sp<IAfEffectChain>> effectChains;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010357
Andy Hung13850be2019-03-14 11:33:09 -070010358 { // under Thread lock
Andy Hung87e82412023-08-29 14:26:09 -070010359 audio_utils::unique_lock _l(mutex());
Andy Hung13850be2019-03-14 11:33:09 -070010360
Eric Laurent6acd1d42017-01-04 14:23:29 -080010361 if (mSignalPending) {
10362 // A signal was raised while we were unlocked
10363 mSignalPending = false;
10364 } else {
10365 if (mConfigEvents.isEmpty()) {
10366 // we're about to wait, flush the binder command buffer
10367 IPCThreadState::self()->flushCommands();
10368
10369 if (exitPending()) {
10370 break;
10371 }
10372
Eric Laurent6acd1d42017-01-04 14:23:29 -080010373 // wait until we have something to do...
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010374 ALOGV("%s going to sleep", myName.c_str());
Andy Hung87e82412023-08-29 14:26:09 -070010375 mWaitWorkCV.wait(_l);
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010376 ALOGV("%s waking up", myName.c_str());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010377
10378 checkSilentMode_l();
10379
10380 continue;
10381 }
10382 }
10383
10384 processConfigEvents_l();
10385
10386 processVolume_l();
10387
10388 checkInvalidTracks_l();
10389
10390 mActiveTracks.updatePowerState(this);
10391
Kevin Rocard069c2712018-03-29 19:09:14 -070010392 updateMetadata_l();
10393
Eric Laurent6acd1d42017-01-04 14:23:29 -080010394 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -070010395 } // release Thread lock
10396
Eric Laurent6acd1d42017-01-04 14:23:29 -080010397 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -070010398 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -080010399 }
Andy Hung13850be2019-03-14 11:33:09 -070010400
10401 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -080010402 unlockEffectChains(effectChains);
10403 // Effect chains will be actually deleted here if they were removed from
10404 // mEffectChains list during mixing or effects processing
10405 }
10406
10407 threadLoop_exit();
10408
10409 if (!mStandby) {
10410 threadLoop_standby();
10411 mStandby = true;
10412 }
10413
Eric Laurent6acd1d42017-01-04 14:23:29 -080010414 ALOGV("Thread %p type %d exiting", this, mType);
10415 return false;
10416}
10417
Andy Hung87e82412023-08-29 14:26:09 -070010418// checkForNewParameter_l() must be called with ThreadBase::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -070010419bool MmapThread::checkForNewParameter_l(const String8& keyValuePair,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010420 status_t& status)
10421{
10422 AudioParameter param = AudioParameter(keyValuePair);
10423 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -070010424 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010425 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -070010426 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -080010427 }
Eric Laurente6e9a482017-07-25 19:26:02 -070010428 if (sendToHal) {
10429 status = mHalStream->setParameters(keyValuePair);
10430 } else {
10431 status = NO_ERROR;
10432 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010433
10434 return false;
10435}
10436
Andy Hung71742ab2023-07-07 13:47:37 -070010437String8 MmapThread::getParameters(const String8& keys)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010438{
Andy Hungf79092d2023-08-31 16:13:39 -070010439 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010440 String8 out_s8;
10441 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
10442 return out_s8;
10443 }
Andy Hung71ba4b32022-10-06 12:09:49 -070010444 return {};
Eric Laurent6acd1d42017-01-04 14:23:29 -080010445}
10446
Andy Hung71742ab2023-07-07 13:47:37 -070010447void MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -070010448 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -070010449 sp<AudioIoDescriptor> desc;
10450 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010451 switch (event) {
10452 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010453 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010454 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010455 isInput = true;
10456 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010457 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -070010458 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -080010459 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010460 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
10461 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010462 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010463 case AUDIO_INPUT_CLOSED:
10464 case AUDIO_OUTPUT_CLOSED:
10465 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -070010466 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010467 break;
10468 }
Andy Hung2cbc2722023-07-17 17:05:00 -070010469 mAfThreadCallback->ioConfigChanged(event, desc, pid);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010470}
10471
Andy Hung71742ab2023-07-07 13:47:37 -070010472status_t MmapThread::createAudioPatch_l(const struct audio_patch* patch,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010473 audio_patch_handle_t *handle)
Andy Hung87e82412023-08-29 14:26:09 -070010474NO_THREAD_SAFETY_ANALYSIS // elease and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010475{
10476 status_t status = NO_ERROR;
10477
10478 // store new device and send to effects
10479 audio_devices_t type = AUDIO_DEVICE_NONE;
10480 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -070010481 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
10482 AudioDeviceTypeAddr sourceDeviceTypeAddr;
10483 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010484 if (isOutput()) {
10485 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -070010486 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
10487 && !mAudioHwDev->supportsAudioPatches(),
10488 "Enumerated device type(%#x) must not be used "
10489 "as it does not support audio patches",
10490 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -070010491 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
Andy Hung71ba4b32022-10-06 12:09:49 -070010492 sinkDeviceTypeAddrs.emplace_back(patch->sinks[i].ext.device.type,
10493 patch->sinks[i].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010494 }
10495 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010496 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010497 } else {
10498 type = patch->sources[0].ext.device.type;
10499 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -070010500 numDevices = mPatch.num_sources;
10501 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -070010502 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010503 }
10504
10505 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -080010506 if (isOutput()) {
10507 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
10508 } else {
10509 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
10510 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010511 }
10512
jiabinc52b1ff2019-10-31 17:20:42 -070010513 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010514 // store new source and send to effects
10515 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
10516 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
10517 for (size_t i = 0; i < mEffectChains.size(); i++) {
10518 mEffectChains[i]->setAudioSource_l(mAudioSource);
10519 }
10520 }
10521 }
10522
10523 if (mAudioHwDev->supportsAudioPatches()) {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010524 status = mHalDevice->createAudioPatch(patch->num_sources, patch->sources, patch->num_sinks,
10525 patch->sinks, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010526 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010527 audio_port_config port;
10528 std::optional<audio_source_t> source;
10529 if (isOutput()) {
10530 port = patch->sinks[0];
Eric Laurent6acd1d42017-01-04 14:23:29 -080010531 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010532 port = patch->sources[0];
10533 source = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010534 }
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010535 status = mHalStream->legacyCreateAudioPatch(port, source, type);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010536 *handle = AUDIO_PATCH_HANDLE_NONE;
10537 }
10538
jiabinc52b1ff2019-10-31 17:20:42 -070010539 if (numDevices == 0 || mDeviceId != deviceId) {
10540 if (isOutput()) {
10541 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
10542 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -070010543 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -070010544 } else {
10545 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
10546 mInDeviceTypeAddr = sourceDeviceTypeAddr;
10547 }
Phil Burk7f6b40d2017-02-09 13:18:38 -080010548 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010549 if (mDeviceId != deviceId && callback != 0) {
Andy Hung87e82412023-08-29 14:26:09 -070010550 mutex().unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -080010551 callback->onRoutingChanged(deviceId);
Andy Hung87e82412023-08-29 14:26:09 -070010552 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010553 }
jiabinc52b1ff2019-10-31 17:20:42 -070010554 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010555 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010556 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010557 // Force meteadata update after a route change
10558 mActiveTracks.setHasChanged();
10559
Eric Laurent6acd1d42017-01-04 14:23:29 -080010560 return status;
10561}
10562
Andy Hung71742ab2023-07-07 13:47:37 -070010563status_t MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010564{
10565 status_t status = NO_ERROR;
10566
jiabinc52b1ff2019-10-31 17:20:42 -070010567 mPatch = audio_patch{};
10568 mOutDeviceTypeAddrs.clear();
10569 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010570
10571 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
10572 supportsAudioPatches : false;
10573
10574 if (supportsAudioPatches) {
10575 status = mHalDevice->releaseAudioPatch(handle);
10576 } else {
Ytai Ben-Tsvif997ffe2022-02-03 16:38:16 -080010577 status = mHalStream->legacyReleaseAudioPatch();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010578 }
Eric Laurentdda206a2022-07-08 17:28:35 +020010579 // Force meteadata update after a route change
10580 mActiveTracks.setHasChanged();
10581
Eric Laurent6acd1d42017-01-04 14:23:29 -080010582 return status;
10583}
10584
Andy Hung71742ab2023-07-07 13:47:37 -070010585void MmapThread::toAudioPortConfig(struct audio_port_config* config)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010586{
Mikhail Naganovdc769682018-05-04 15:34:08 -070010587 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010588 if (isOutput()) {
10589 config->role = AUDIO_PORT_ROLE_SOURCE;
10590 config->ext.mix.hw_module = mAudioHwDev->handle();
10591 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
10592 } else {
10593 config->role = AUDIO_PORT_ROLE_SINK;
10594 config->ext.mix.hw_module = mAudioHwDev->handle();
10595 config->ext.mix.usecase.source = mAudioSource;
10596 }
10597}
10598
Andy Hung71742ab2023-07-07 13:47:37 -070010599status_t MmapThread::addEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010600{
10601 audio_session_t session = chain->sessionId();
10602
10603 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
10604 // Attach all tracks with same session ID to this chain.
10605 // indicate all active tracks in the chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010606 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010607 if (session == track->sessionId()) {
10608 chain->incTrackCnt();
10609 chain->incActiveTrackCnt();
10610 }
10611 }
10612
10613 chain->setThread(this);
10614 chain->setInBuffer(nullptr);
10615 chain->setOutBuffer(nullptr);
10616 chain->syncHalEffectsState();
10617
10618 mEffectChains.add(chain);
10619 checkSuspendOnAddEffectChain_l(chain);
10620 return NO_ERROR;
10621}
10622
Andy Hung71742ab2023-07-07 13:47:37 -070010623size_t MmapThread::removeEffectChain_l(const sp<IAfEffectChain>& chain)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010624{
10625 audio_session_t session = chain->sessionId();
10626
10627 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
10628
10629 for (size_t i = 0; i < mEffectChains.size(); i++) {
10630 if (chain == mEffectChains[i]) {
10631 mEffectChains.removeAt(i);
10632 // detach all active tracks from the chain
10633 // detach all tracks with same session ID from this chain
Andy Hung3ff4b552023-06-26 19:20:57 -070010634 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010635 if (session == track->sessionId()) {
10636 chain->decActiveTrackCnt();
10637 chain->decTrackCnt();
10638 }
10639 }
10640 break;
10641 }
10642 }
10643 return mEffectChains.size();
10644}
10645
Andy Hung71742ab2023-07-07 13:47:37 -070010646void MmapThread::threadLoop_standby()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010647{
10648 mHalStream->standby();
10649}
10650
Andy Hung71742ab2023-07-07 13:47:37 -070010651void MmapThread::threadLoop_exit()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010652{
Phil Burk7dce7282017-09-27 13:51:41 -070010653 // Do not call callback->onTearDown() because it is redundant for thread exit
10654 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -080010655}
10656
Andy Hung71742ab2023-07-07 13:47:37 -070010657status_t MmapThread::setSyncEvent(const sp<SyncEvent>& /* event */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010658{
10659 return BAD_VALUE;
10660}
10661
Andy Hung71742ab2023-07-07 13:47:37 -070010662bool MmapThread::isValidSyncEvent(
10663 const sp<SyncEvent>& /* event */) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010664{
10665 return false;
10666}
10667
Andy Hung71742ab2023-07-07 13:47:37 -070010668status_t MmapThread::checkEffectCompatibility_l(
Eric Laurent6acd1d42017-01-04 14:23:29 -080010669 const effect_descriptor_t *desc, audio_session_t sessionId)
10670{
10671 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -080010672 if (audio_is_global_session(sessionId)) {
10673 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -080010674 desc->name, mThreadName);
10675 return BAD_VALUE;
10676 }
10677
10678 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
10679 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
10680 desc->name);
10681 return BAD_VALUE;
10682 }
10683 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -080010684 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
10685 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010686 return BAD_VALUE;
10687 }
10688
10689 // Only allow effects without processing load or latency
10690 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
10691 return BAD_VALUE;
10692 }
10693
Andy Hungbd72c542023-06-20 18:56:17 -070010694 if (IAfEffectModule::isHapticGenerator(&desc->type)) {
jiabineb3bda02020-06-30 14:07:03 -070010695 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
10696 return BAD_VALUE;
10697 }
10698
Eric Laurent6acd1d42017-01-04 14:23:29 -080010699 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010700}
10701
Andy Hung71742ab2023-07-07 13:47:37 -070010702void MmapThread::checkInvalidTracks_l()
Andy Hung87e82412023-08-29 14:26:09 -070010703NO_THREAD_SAFETY_ANALYSIS // release and re-acquire mutex()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010704{
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010705 sp<MmapStreamCallback> callback;
Andy Hung3ff4b552023-06-26 19:20:57 -070010706 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010707 if (track->isInvalid()) {
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010708 callback = mCallback.promote();
10709 if (callback == nullptr && mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10710 ALOGW("Could not notify MMAP stream tear down: no onRoutingChanged callback!");
Eric Laurent331679c2018-04-16 17:03:16 -070010711 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010712 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010713 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010714 }
10715 }
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010716 if (callback != 0) {
Andy Hung87e82412023-08-29 14:26:09 -070010717 mutex().unlock();
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010718 callback->onRoutingChanged(AUDIO_PORT_HANDLE_NONE);
Andy Hung87e82412023-08-29 14:26:09 -070010719 mutex().lock();
Eric Laurentc9ac46b2022-10-07 14:01:59 +020010720 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010721}
10722
Andy Hung71742ab2023-07-07 13:47:37 -070010723void MmapThread::dumpInternals_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010724{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010725 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
10726 mAttr.content_type, mAttr.usage, mAttr.source);
10727 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -070010728 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010729 dprintf(fd, " No active clients\n");
10730 }
10731}
10732
Andy Hung71742ab2023-07-07 13:47:37 -070010733void MmapThread::dumpTracks_l(int fd, const Vector<String16>& /* args */)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010734{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010735 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010736 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010737 dprintf(fd, " %zu Tracks\n", numtracks);
10738 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010739 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010740 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010741 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010742 for (size_t i = 0; i < numtracks ; ++i) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010743 sp<IAfMmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010744 result.append(prefix);
10745 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010746 }
10747 } else {
10748 dprintf(fd, "\n");
10749 }
Tomasz Wasilczyk8f36f6e2023-08-15 20:59:35 +000010750 write(fd, result.c_str(), result.size());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010751}
10752
Andy Hung71742ab2023-07-07 13:47:37 -070010753/* static */
10754sp<IAfMmapPlaybackThread> IAfMmapPlaybackThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070010755 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070010756 AudioHwDevice* hwDev, AudioStreamOut* output, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070010757 return sp<MmapPlaybackThread>::make(afThreadCallback, id, hwDev, output, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070010758}
10759
10760MmapPlaybackThread::MmapPlaybackThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070010761 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010762 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070010763 : MmapThread(afThreadCallback, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010764 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010765 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010766{
10767 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10768 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Andy Hung2cbc2722023-07-17 17:05:00 -070010769 mMasterVolume = afThreadCallback->masterVolume_l();
10770 mMasterMute = afThreadCallback->masterMute_l();
Eric Laurent19611512023-07-03 18:14:07 +020010771
10772 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
10773 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
10774 mStreamTypes[stream].volume = 0.0f;
10775 mStreamTypes[stream].mute = mAfThreadCallback->streamMute_l(stream);
10776 }
10777 // Audio patch and call assistant volume are always max
10778 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
10779 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
10780 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
10781 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
10782
Eric Laurent6acd1d42017-01-04 14:23:29 -080010783 if (mAudioHwDev) {
10784 if (mAudioHwDev->canSetMasterVolume()) {
10785 mMasterVolume = 1.0;
10786 }
10787
10788 if (mAudioHwDev->canSetMasterMute()) {
10789 mMasterMute = false;
10790 }
10791 }
10792}
10793
Andy Hung71742ab2023-07-07 13:47:37 -070010794void MmapPlaybackThread::configure(const audio_attributes_t* attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010795 audio_stream_type_t streamType,
10796 audio_session_t sessionId,
10797 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010798 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010799 audio_port_handle_t portId)
10800{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010801 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010802 mStreamType = streamType;
10803}
10804
Andy Hung71742ab2023-07-07 13:47:37 -070010805AudioStreamOut* MmapPlaybackThread::clearOutput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010806{
Andy Hungf79092d2023-08-31 16:13:39 -070010807 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010808 AudioStreamOut *output = mOutput;
10809 mOutput = NULL;
10810 return output;
10811}
10812
Andy Hung71742ab2023-07-07 13:47:37 -070010813void MmapPlaybackThread::setMasterVolume(float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010814{
Andy Hungf79092d2023-08-31 16:13:39 -070010815 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010816 // Don't apply master volume in SW if our HAL can do it for us.
10817 if (mAudioHwDev &&
10818 mAudioHwDev->canSetMasterVolume()) {
10819 mMasterVolume = 1.0;
10820 } else {
10821 mMasterVolume = value;
10822 }
10823}
10824
Andy Hung71742ab2023-07-07 13:47:37 -070010825void MmapPlaybackThread::setMasterMute(bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010826{
Andy Hungf79092d2023-08-31 16:13:39 -070010827 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010828 // Don't apply master mute in SW if our HAL can do it for us.
10829 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10830 mMasterMute = false;
10831 } else {
10832 mMasterMute = muted;
10833 }
10834}
10835
Andy Hung71742ab2023-07-07 13:47:37 -070010836void MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010837{
Andy Hungf79092d2023-08-31 16:13:39 -070010838 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010839 mStreamTypes[stream].volume = value;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010840 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010841 broadcast_l();
10842 }
10843}
10844
Andy Hung71742ab2023-07-07 13:47:37 -070010845float MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
Eric Laurent6acd1d42017-01-04 14:23:29 -080010846{
Andy Hungf79092d2023-08-31 16:13:39 -070010847 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010848 return mStreamTypes[stream].volume;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010849}
10850
Andy Hung71742ab2023-07-07 13:47:37 -070010851void MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010852{
Andy Hungf79092d2023-08-31 16:13:39 -070010853 audio_utils::lock_guard _l(mutex());
Eric Laurent19611512023-07-03 18:14:07 +020010854 mStreamTypes[stream].mute = muted;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010855 if (stream == mStreamType) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010856 broadcast_l();
10857 }
10858}
10859
Andy Hung71742ab2023-07-07 13:47:37 -070010860void MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010861{
Andy Hungf79092d2023-08-31 16:13:39 -070010862 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080010863 if (streamType == mStreamType) {
Andy Hung3ff4b552023-06-26 19:20:57 -070010864 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010865 track->invalidate();
10866 }
10867 broadcast_l();
10868 }
10869}
10870
Andy Hung71742ab2023-07-07 13:47:37 -070010871void MmapPlaybackThread::invalidateTracks(std::set<audio_port_handle_t>& portIds)
jiabinc44b3462022-12-08 12:52:31 -080010872{
Andy Hungf79092d2023-08-31 16:13:39 -070010873 audio_utils::lock_guard _l(mutex());
jiabinc44b3462022-12-08 12:52:31 -080010874 bool trackMatch = false;
Andy Hung3ff4b552023-06-26 19:20:57 -070010875 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
jiabinc44b3462022-12-08 12:52:31 -080010876 if (portIds.find(track->portId()) != portIds.end()) {
10877 track->invalidate();
10878 trackMatch = true;
10879 portIds.erase(track->portId());
10880 }
10881 if (portIds.empty()) {
10882 break;
10883 }
10884 }
10885 if (trackMatch) {
10886 broadcast_l();
10887 }
10888}
10889
Andy Hung71742ab2023-07-07 13:47:37 -070010890void MmapPlaybackThread::processVolume_l()
Andy Hung71ba4b32022-10-06 12:09:49 -070010891NO_THREAD_SAFETY_ANALYSIS // access of track->processMuteEvent_l
Eric Laurent6acd1d42017-01-04 14:23:29 -080010892{
10893 float volume;
10894
Eric Laurent19611512023-07-03 18:14:07 +020010895 if (mMasterMute || streamMuted_l()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010896 volume = 0;
10897 } else {
Eric Laurent19611512023-07-03 18:14:07 +020010898 volume = mMasterVolume * streamVolume_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010899 }
10900
10901 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010902 // Convert volumes from float to 8.24
10903 uint32_t vol = (uint32_t)(volume * (1 << 24));
10904
10905 // Delegate volume control to effect in track effect chain if needed
10906 // only one effect chain can be present on DirectOutputThread, so if
10907 // there is one, the track is connected to it
10908 if (!mEffectChains.isEmpty()) {
10909 mEffectChains[0]->setVolume_l(&vol, &vol);
10910 volume = (float)vol / (1 << 24);
10911 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010912 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010913 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10914 mHalVolFloat = volume; // HW volume control worked, so update value.
10915 mNoCallbackWarningCount = 0;
10916 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010917 sp<MmapStreamCallback> callback = mCallback.promote();
10918 if (callback != 0) {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010919 mHalVolFloat = volume; // SW volume control worked, so update value.
10920 mNoCallbackWarningCount = 0;
Andy Hung87e82412023-08-29 14:26:09 -070010921 mutex().unlock();
Robert Wu4389ae62022-02-17 18:39:41 +000010922 callback->onVolumeChanged(volume);
Andy Hung87e82412023-08-29 14:26:09 -070010923 mutex().lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010924 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010925 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10926 ALOGW("Could not set MMAP stream volume: no volume callback!");
10927 mNoCallbackWarningCount++;
10928 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010929 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010930 }
Andy Hung3ff4b552023-06-26 19:20:57 -070010931 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010932 track->setMetadataHasChanged();
Andy Hung2cbc2722023-07-17 17:05:00 -070010933 track->processMuteEvent_l(mAfThreadCallback->getOrCreateAudioManager(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010934 /*muteState=*/{mMasterMute,
Eric Laurent19611512023-07-03 18:14:07 +020010935 streamVolume_l() == 0.f,
10936 streamMuted_l(),
Vlad Popaec1788e2022-08-04 11:23:30 +020010937 // TODO(b/241533526): adjust logic to include mute from AppOps
10938 false /*muteFromPlaybackRestricted*/,
10939 false /*muteFromClientVolume*/,
10940 false /*muteFromVolumeShaper*/});
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010941 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010942 }
10943}
10944
Andy Hung71742ab2023-07-07 13:47:37 -070010945ThreadBase::MetadataUpdate MmapPlaybackThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070010946{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010947 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010010948 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010949 }
10950 StreamOutHalInterface::SourceMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070010951 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070010952 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010953 playback_track_metadata_v7_t trackMetadata;
10954 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010955 .usage = track->attributes().usage,
10956 .content_type = track->attributes().content_type,
10957 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010958 };
10959 trackMetadata.channel_mask = track->channelMask(),
10960 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10961 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010962 }
10963 mOutput->stream->updateSourceMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010010964
10965 MetadataUpdate change;
10966 change.playbackMetadataUpdate = metadata.tracks;
10967 return change;
10968};
Kevin Rocard069c2712018-03-29 19:09:14 -070010969
Andy Hung71742ab2023-07-07 13:47:37 -070010970void MmapPlaybackThread::checkSilentMode_l()
Eric Laurent6acd1d42017-01-04 14:23:29 -080010971{
10972 if (!mMasterMute) {
10973 char value[PROPERTY_VALUE_MAX];
10974 if (property_get("ro.audio.silent", value, "0") > 0) {
10975 char *endptr;
10976 unsigned long ul = strtoul(value, &endptr, 0);
10977 if (*endptr == '\0' && ul != 0) {
10978 ALOGD("Silence is golden");
10979 // The setprop command will not allow a property to be changed after
10980 // the first time it is set, so we don't have to worry about un-muting.
10981 setMasterMute_l(true);
10982 }
10983 }
10984 }
10985}
10986
Andy Hung71742ab2023-07-07 13:47:37 -070010987void MmapPlaybackThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010988{
10989 MmapThread::toAudioPortConfig(config);
10990 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10991 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10992 config->flags.output = mOutput->flags;
10993 }
10994}
10995
Andy Hung71742ab2023-07-07 13:47:37 -070010996status_t MmapPlaybackThread::getExternalPosition(uint64_t* position,
Andy Hung4989d312023-06-29 21:19:25 -070010997 int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070010998{
10999 if (mOutput == nullptr) {
11000 return NO_INIT;
11001 }
11002 struct timespec timestamp;
11003 status_t status = mOutput->getPresentationPosition(position, &timestamp);
11004 if (status == NO_ERROR) {
11005 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
11006 }
11007 return status;
11008}
11009
Andy Hung71742ab2023-07-07 13:47:37 -070011010status_t MmapPlaybackThread::reportData(const void* buffer, size_t frameCount) {
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011011 // Send to MelProcessor for sound dose measurement.
11012 auto processor = mMelProcessor.load();
11013 if (processor) {
11014 processor->process(buffer, frameCount * mFrameSize);
11015 }
11016
jiabinfc791ee2023-02-15 19:43:40 +000011017 return NO_ERROR;
11018}
11019
Andy Hung87e82412023-08-29 14:26:09 -070011020// startMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -070011021void MmapPlaybackThread::startMelComputation_l(
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011022 const sp<audio_utils::MelProcessor>& processor)
11023{
11024 ALOGV("%s: starting mel processor for thread %d", __func__, id());
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011025 mMelProcessor.store(processor);
11026 if (processor) {
11027 processor->resume();
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011028 }
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011029
11030 // no need to update output format for MMapPlaybackThread since it is
11031 // assigned constant for each thread
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011032}
11033
Andy Hung87e82412023-08-29 14:26:09 -070011034// stopMelComputation_l() must be called with AudioFlinger::mutex() held
Andy Hung71742ab2023-07-07 13:47:37 -070011035void MmapPlaybackThread::stopMelComputation_l()
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011036{
Vlad Popa1c2f7e12023-03-28 02:08:56 +020011037 ALOGV("%s: pausing mel processor for thread %d", __func__, id());
11038 auto melProcessor = mMelProcessor.load();
11039 if (melProcessor != nullptr) {
11040 melProcessor->pause();
11041 }
Vlad Popa6fbbfbf2023-02-22 15:05:43 +010011042}
11043
Andy Hung71742ab2023-07-07 13:47:37 -070011044void MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080011045{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070011046 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080011047
Glenn Kastend3bb6452016-12-05 18:14:37 -080011048 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
Eric Laurent19611512023-07-03 18:14:07 +020011049 mStreamType, streamVolume_l(), mHalVolFloat, streamMuted_l());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011050 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
11051}
11052
Andy Hung71742ab2023-07-07 13:47:37 -070011053/* static */
11054sp<IAfMmapCaptureThread> IAfMmapCaptureThread::create(
Andy Hung2cbc2722023-07-17 17:05:00 -070011055 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
Andy Hung71742ab2023-07-07 13:47:37 -070011056 AudioHwDevice* hwDev, AudioStreamIn* input, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011057 return sp<MmapCaptureThread>::make(afThreadCallback, id, hwDev, input, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011058}
11059
11060MmapCaptureThread::MmapCaptureThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011061 const sp<IAfThreadCallback>& afThreadCallback, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070011062 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011063 : MmapThread(afThreadCallback, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080011064 mInput(input)
11065{
11066 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
11067 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
11068}
11069
Andy Hung71742ab2023-07-07 13:47:37 -070011070status_t MmapCaptureThread::exitStandby_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011071{
Phil Burkf054fc32018-12-06 09:45:59 -080011072 {
11073 // mInput might have been cleared by clearInput()
Phil Burkf054fc32018-12-06 09:45:59 -080011074 if (mInput != nullptr && mInput->stream != nullptr) {
11075 mInput->stream->setGain(1.0f);
11076 }
11077 }
Eric Laurentdda206a2022-07-08 17:28:35 +020011078 return MmapThread::exitStandby_l();
Eric Laurent331679c2018-04-16 17:03:16 -070011079}
11080
Andy Hung71742ab2023-07-07 13:47:37 -070011081AudioStreamIn* MmapCaptureThread::clearInput()
Eric Laurent6acd1d42017-01-04 14:23:29 -080011082{
Andy Hungf79092d2023-08-31 16:13:39 -070011083 audio_utils::lock_guard _l(mutex());
Eric Laurent6acd1d42017-01-04 14:23:29 -080011084 AudioStreamIn *input = mInput;
11085 mInput = NULL;
11086 return input;
11087}
Kevin Rocard069c2712018-03-29 19:09:14 -070011088
Andy Hung71742ab2023-07-07 13:47:37 -070011089void MmapCaptureThread::processVolume_l()
Eric Laurent331679c2018-04-16 17:03:16 -070011090{
11091 bool changed = false;
11092 bool silenced = false;
11093
11094 sp<MmapStreamCallback> callback = mCallback.promote();
11095 if (callback == 0) {
11096 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
11097 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
11098 mNoCallbackWarningCount++;
11099 }
11100 }
11101
11102 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
11103 // track is silenced and unmute otherwise
11104 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
11105 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
11106 changed = true;
11107 silenced = mActiveTracks[i]->isSilenced_l();
11108 }
11109 }
11110
11111 if (changed) {
11112 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
11113 }
11114}
11115
Andy Hung71742ab2023-07-07 13:47:37 -070011116ThreadBase::MetadataUpdate MmapCaptureThread::updateMetadata_l()
Kevin Rocard069c2712018-03-29 19:09:14 -070011117{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080011118 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Vlad Popa7e81cea2023-01-19 16:34:16 +010011119 return {}; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070011120 }
11121 StreamInHalInterface::SinkMetadata metadata;
Andy Hung3ff4b552023-06-26 19:20:57 -070011122 for (const sp<IAfMmapTrack>& track : mActiveTracks) {
Kevin Rocard069c2712018-03-29 19:09:14 -070011123 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010011124 record_track_metadata_v7_t trackMetadata;
11125 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070011126 .source = track->attributes().source,
11127 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010011128 };
11129 trackMetadata.channel_mask = track->channelMask(),
11130 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
11131 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070011132 }
11133 mInput->stream->updateSinkMetadata(metadata);
Vlad Popa7e81cea2023-01-19 16:34:16 +010011134 MetadataUpdate change;
11135 change.recordMetadataUpdate = metadata.tracks;
11136 return change;
Kevin Rocard069c2712018-03-29 19:09:14 -070011137}
11138
Andy Hung71742ab2023-07-07 13:47:37 -070011139void MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070011140{
Andy Hungf79092d2023-08-31 16:13:39 -070011141 audio_utils::lock_guard _l(mutex());
Eric Laurent331679c2018-04-16 17:03:16 -070011142 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070011143 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070011144 mActiveTracks[i]->setSilenced_l(silenced);
11145 broadcast_l();
11146 }
11147 }
jiabincfc10a42022-06-15 19:26:01 +000011148 setClientSilencedIfExists_l(portId, silenced);
Eric Laurent331679c2018-04-16 17:03:16 -070011149}
11150
Andy Hung71742ab2023-07-07 13:47:37 -070011151void MmapCaptureThread::toAudioPortConfig(struct audio_port_config* config)
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070011152{
11153 MmapThread::toAudioPortConfig(config);
11154 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
11155 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
11156 config->flags.input = mInput->flags;
11157 }
11158}
11159
Andy Hung71742ab2023-07-07 13:47:37 -070011160status_t MmapCaptureThread::getExternalPosition(
Andy Hung4989d312023-06-29 21:19:25 -070011161 uint64_t* position, int64_t* timeNanos) const
jiabinb7d8c5a2020-08-26 17:24:52 -070011162{
11163 if (mInput == nullptr) {
11164 return NO_INIT;
11165 }
11166 return mInput->getCapturePosition((int64_t*)position, timeNanos);
11167}
11168
jiabinc658e452022-10-21 20:52:21 +000011169// ----------------------------------------------------------------------------
11170
Andy Hung71742ab2023-07-07 13:47:37 -070011171/* static */
11172sp<IAfPlaybackThread> IAfPlaybackThread::createBitPerfectThread(
Andy Hung2cbc2722023-07-17 17:05:00 -070011173 const sp<IAfThreadCallback>& afThreadCallback,
Andy Hung71742ab2023-07-07 13:47:37 -070011174 AudioStreamOut* output, audio_io_handle_t id, bool systemReady) {
Andy Hung2cbc2722023-07-17 17:05:00 -070011175 return sp<BitPerfectThread>::make(afThreadCallback, output, id, systemReady);
Andy Hung71742ab2023-07-07 13:47:37 -070011176}
11177
Andy Hung2cbc2722023-07-17 17:05:00 -070011178BitPerfectThread::BitPerfectThread(const sp<IAfThreadCallback> &afThreadCallback,
jiabinc658e452022-10-21 20:52:21 +000011179 AudioStreamOut *output, audio_io_handle_t id, bool systemReady)
Andy Hung2cbc2722023-07-17 17:05:00 -070011180 : MixerThread(afThreadCallback, output, id, systemReady, BIT_PERFECT) {}
jiabinc658e452022-10-21 20:52:21 +000011181
Andy Hung71742ab2023-07-07 13:47:37 -070011182PlaybackThread::mixer_state BitPerfectThread::prepareTracks_l(
Andy Hung3ff4b552023-06-26 19:20:57 -070011183 Vector<sp<IAfTrack>>* tracksToRemove) {
jiabinc658e452022-10-21 20:52:21 +000011184 mixer_state result = MixerThread::prepareTracks_l(tracksToRemove);
11185 // If there is only one active track and it is bit-perfect, enable tee buffer.
jiabin76d94692022-12-15 21:51:21 +000011186 float volumeLeft = 1.0f;
11187 float volumeRight = 1.0f;
jiabinc658e452022-10-21 20:52:21 +000011188 if (mActiveTracks.size() == 1 && mActiveTracks[0]->isBitPerfect()) {
11189 const int trackId = mActiveTracks[0]->id();
11190 mAudioMixer->setParameter(
11191 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, (void *)mSinkBuffer);
11192 mAudioMixer->setParameter(
11193 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER_FRAME_COUNT,
11194 (void *)(uintptr_t)mNormalFrameCount);
jiabin76d94692022-12-15 21:51:21 +000011195 mActiveTracks[0]->getFinalVolume(&volumeLeft, &volumeRight);
jiabinc658e452022-10-21 20:52:21 +000011196 mIsBitPerfect = true;
11197 } else {
11198 mIsBitPerfect = false;
11199 // No need to copy bit-perfect data directly to sink buffer given there are multiple tracks
11200 // active.
11201 for (const auto& track : mActiveTracks) {
11202 const int trackId = track->id();
11203 mAudioMixer->setParameter(
11204 trackId, AudioMixer::TRACK, AudioMixer::TEE_BUFFER, nullptr);
11205 }
11206 }
jiabin76d94692022-12-15 21:51:21 +000011207 if (mVolumeLeft != volumeLeft || mVolumeRight != volumeRight) {
11208 mVolumeLeft = volumeLeft;
11209 mVolumeRight = volumeRight;
11210 setVolumeForOutput_l(volumeLeft, volumeRight);
11211 }
jiabinc658e452022-10-21 20:52:21 +000011212 return result;
11213}
11214
Andy Hung71742ab2023-07-07 13:47:37 -070011215void BitPerfectThread::threadLoop_mix() {
jiabinc658e452022-10-21 20:52:21 +000011216 MixerThread::threadLoop_mix();
11217 mHasDataCopiedToSinkBuffer = mIsBitPerfect;
11218}
11219
Glenn Kasten63238ef2015-03-02 15:50:29 -080011220} // namespace android